<template>
  <div>
    <!-- Loading State -->
    <div v-if="loading" class="flex items-center justify-center py-20">
      <div class="flex flex-col items-center gap-3">
        <svg class="w-8 h-8 text-indigo-400 animate-spin" fill="none" viewBox="0 0 24 24">
          <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4" />
          <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
        </svg>
        <p class="text-slate-400 text-sm">{{ $t('garages.details.loading') }}</p>
      </div>
    </div>

    <!-- Error State -->
    <div v-else-if="error" class="flex flex-col items-center justify-center py-20 text-center">
      <svg class="w-12 h-12 text-red-500 mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L4.082 16.5c-.77.833.192 2.5 1.732 2.5z" />
      </svg>
      <p class="text-red-400 text-sm mb-2">{{ error }}</p>
      <button @click="fetchDetails" class="px-4 py-2 text-sm bg-indigo-600/20 text-indigo-300 hover:bg-indigo-600/30 rounded-lg transition">
        {{ $t('garages.details.retry') }}
      </button>
    </div>

    <!-- Content -->
    <template v-else-if="garage">
      <!-- Header -->
      <div class="mb-8">
        <button
          @click="goBack"
          class="inline-flex items-center gap-1.5 text-sm text-slate-400 hover:text-white transition mb-4"
        >
          <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7" />
          </svg>
          {{ $t('garages.details.back') }}
        </button>

        <div class="flex items-center justify-between">
          <div class="flex items-center gap-4">
            <div
              class="w-12 h-12 rounded-xl flex items-center justify-center text-lg font-bold text-white"
              :class="getInitialsColor(garageDisplayName(garage))"
            >
              {{ getInitials(garageDisplayName(garage)) }}
            </div>
            <div>
              <h1 class="text-2xl font-bold text-white">{{ garageDisplayName(garage) }}</h1>
              <p class="text-sm text-slate-400 mt-0.5">
                {{ garage.full_name }}
                <span v-if="garage.tax_number" class="ml-2 text-slate-500">· {{ $t('garages.details.tax_number') }}: {{ garage.tax_number }}</span>
              </p>
            </div>
          </div>
          <span
            class="inline-flex items-center px-3 py-1 rounded-full text-xs font-medium"
            :class="statusBadgeClass(garage.status)"
          >
            <span class="w-1.5 h-1.5 rounded-full mr-1.5" :class="statusDotClass(garage.status)"></span>
            {{ statusLabel(garage.status) }}
          </span>
        </div>
      </div>

      <!-- Tab Navigation -->
      <div class="border-b border-slate-700 mb-6">
        <nav class="flex gap-6">
          <button
            v-for="tab in tabs"
            :key="tab.key"
            @click="activeTab = tab.key"
            class="pb-3 text-sm font-medium transition border-b-2 -mb-px"
            :class="activeTab === tab.key
              ? 'text-indigo-400 border-indigo-400'
              : 'text-slate-400 border-transparent hover:text-slate-300'"
          >
            {{ tab.label }}
          </button>
        </nav>
      </div>

      <!-- General Tab Content -->
      <div v-if="activeTab === 'general'" class="space-y-6">
        <div class="bg-slate-800/50 border border-slate-700 rounded-xl overflow-hidden">
          <div class="px-6 py-4 border-b border-slate-700 flex items-center gap-3">
            <div class="p-2 rounded-lg bg-indigo-500/10 text-indigo-400">
              <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4" />
              </svg>
            </div>
            <h3 class="text-base font-semibold text-white">{{ $t('garages.details.company_info') }}</h3>
          </div>
          <div class="px-6 py-5">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div class="space-y-4">
                <div>
                  <p class="text-xs text-slate-500 uppercase tracking-wider">{{ $t('garages.details.company_name') }}</p>
                  <p class="text-sm text-white mt-1">{{ garage.full_name }}</p>
                </div>
                <div>
                  <p class="text-xs text-slate-500 uppercase tracking-wider">{{ $t('garages.details.display_name') }}</p>
                  <p class="text-sm text-white mt-1">{{ garage.display_name || '—' }}</p>
                </div>
                <div>
                  <p class="text-xs text-slate-500 uppercase tracking-wider">{{ $t('garages.details.org_type') }}</p>
                  <p class="text-sm text-white mt-1">{{ orgTypeLabel(garage.org_type) }}</p>
                </div>
              </div>
              <div class="space-y-4">
                <div>
                  <p class="text-xs text-slate-500 uppercase tracking-wider">{{ $t('garages.details.tax_number') }}</p>
                  <p class="text-sm text-white mt-1">{{ garage.tax_number || '—' }}</p>
                </div>
                <div>
                  <p class="text-xs text-slate-500 uppercase tracking-wider">{{ $t('garages.details.reg_number') }}</p>
                  <p class="text-sm text-white mt-1">{{ garage.reg_number || '—' }}</p>
                </div>
                <div>
                  <p class="text-xs text-slate-500 uppercase tracking-wider">{{ $t('garages.details.created_at') }}</p>
                  <p class="text-sm text-white mt-1">{{ formatDate(garage.created_at) }}</p>
                </div>
              </div>
            </div>
            <div class="mt-6 pt-6 border-t border-slate-700/50">
              <p class="text-xs text-slate-500 uppercase tracking-wider mb-3">{{ $t('garages.details.address') }}</p>
              <p class="text-sm text-white">{{ formattedAddress }}</p>
            </div>
          </div>
        </div>

        <div class="bg-slate-800/50 border border-slate-700 rounded-xl overflow-hidden">
          <div class="px-6 py-4 border-b border-slate-700 flex items-center gap-3">
            <div class="p-2 rounded-lg bg-amber-500/10 text-amber-400">
              <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 7v10a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-6l-2-2H5a2 2 0 00-2 2z" />
              </svg>
            </div>
            <h3 class="text-base font-semibold text-white">{{ $t('garages.details.subscription_info') }}</h3>
          </div>
          <div class="px-6 py-5">
            <div v-if="garage.subscription" class="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div class="space-y-4">
                <div>
                  <p class="text-xs text-slate-500 uppercase tracking-wider">{{ $t('garages.details.tier_name') }}</p>
                  <span class="inline-flex mt-1 px-2.5 py-0.5 rounded-full text-xs font-medium" :class="tierBadgeClass(garage.subscription.tier_name)">
                    {{ garage.subscription.tier_name }}
                  </span>
                </div>
                <div>
                  <p class="text-xs text-slate-500 uppercase tracking-wider">{{ $t('garages.details.tier_level') }}</p>
                  <p class="text-sm text-white mt-1">{{ $t('garages.details.level_n', { n: garage.subscription.tier_level }) }}</p>
                </div>
              </div>
              <div class="space-y-4">
                <div>
                  <p class="text-xs text-slate-500 uppercase tracking-wider">{{ $t('garages.details.expires_at') }}</p>
                  <p v-if="garage.subscription.expires_at" class="text-sm text-white mt-1">{{ formatDate(garage.subscription.expires_at) }}</p>
                  <p v-else class="text-sm text-slate-400 mt-1 italic">{{ $t('garages.indefinite') }}</p>
                </div>
                <div>
                  <p class="text-xs text-slate-500 uppercase tracking-wider">{{ $t('garages.details.asset_limit') }}</p>
                  <p class="text-sm text-white mt-1">{{ garage.subscription.asset_limit }} {{ $t('garages.details.vehicles') }}</p>
                </div>
              </div>
            </div>
            <div v-else class="text-center py-4">
              <p class="text-sm text-slate-400">{{ $t('garages.details.no_subscription') }}</p>
            </div>
          </div>
        </div>

        <div class="bg-slate-800/50 border border-slate-700 rounded-xl overflow-hidden">
          <div class="px-6 py-4 border-b border-slate-700 flex items-center gap-3">
            <div class="p-2 rounded-lg bg-emerald-500/10 text-emerald-400">
              <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0z" />
              </svg>
            </div>
            <h3 class="text-base font-semibold text-white">{{ $t('garages.details.contact_info') }}</h3>
          </div>
          <div class="px-6 py-5">
            <div v-if="garage.primary_contact" class="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div class="space-y-4">
                <div>
                  <p class="text-xs text-slate-500 uppercase tracking-wider">{{ $t('garages.details.contact_name') }}</p>
                  <p class="text-sm text-white mt-1">{{ garage.primary_contact.full_name }}</p>
                </div>
                <div>
                  <p class="text-xs text-slate-500 uppercase tracking-wider">{{ $t('garages.details.contact_role') }}</p>
                  <p class="text-sm text-white mt-1">{{ garage.primary_contact.role }}</p>
                </div>
              </div>
              <div class="space-y-4">
                <div>
                  <p class="text-xs text-slate-500 uppercase tracking-wider">{{ $t('garages.details.contact_department') }}</p>
                  <p class="text-sm text-white mt-1">{{ garage.primary_contact.department || '—' }}</p>
                </div>
                <div>
                  <p class="text-xs text-slate-500 uppercase tracking-wider">{{ $t('garages.details.contact_phone') }}</p>
                  <p class="text-sm text-white mt-1">{{ garage.primary_contact.phone || '—' }}</p>
                </div>
              </div>
            </div>
            <div v-else class="text-center py-4">
              <p class="text-sm text-slate-400">{{ $t('garages.details.no_contact') }}</p>
            </div>
          </div>
        </div>
      </div>

      <!-- ============================================================ -->
      <!-- Employees Tab (Dolgozók)                                     -->
      <!-- ============================================================ -->
      <div v-if="activeTab === 'employees'" class="space-y-6">
        <div class="flex items-center justify-between">
          <div class="flex items-center gap-3">
            <div class="p-2 rounded-lg bg-cyan-500/10 text-cyan-400">
              <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4.354a4 4 0 110 5.292M15 21H3v-1a6 6 0 0112 0v1zm0 0h6v-1a6 6 0 00-9-5.197m13.5-9a2.5 2.5 0 11-5 0 2.5 2.5 0 015 0z" />
              </svg>
            </div>
            <div>
              <h3 class="text-base font-semibold text-white">{{ $t('garages.employees.title') }}</h3>
              <p class="text-xs text-slate-400 mt-0.5">{{ $t('garages.employees.total_count', { count: members.length }) }}</p>
            </div>
          </div>
        </div>

        <div class="bg-slate-800/50 border border-slate-700 rounded-xl overflow-hidden">
          <div class="overflow-x-auto">
            <table class="w-full text-sm">
              <thead>
                <tr class="border-b border-slate-700">
                  <th class="text-left px-4 py-3 text-xs font-medium text-slate-400 uppercase tracking-wider">{{ $t('garages.employees.name') }}</th>
                  <th class="text-left px-4 py-3 text-xs font-medium text-slate-400 uppercase tracking-wider">{{ $t('garages.employees.email_phone') }}</th>
                  <th class="text-left px-4 py-3 text-xs font-medium text-slate-400 uppercase tracking-wider">{{ $t('garages.employees.role') }}</th>
                  <th class="text-left px-4 py-3 text-xs font-medium text-slate-400 uppercase tracking-wider">{{ $t('garages.employees.status') }}</th>
                  <th class="text-right px-4 py-3 text-xs font-medium text-slate-400 uppercase tracking-wider">{{ $t('garages.employees.actions') }}</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="member in members" :key="member.id" class="border-b border-slate-700/50 last:border-b-0 hover:bg-slate-700/30 transition">
                  <td class="px-4 py-3">
                    <div class="flex items-center gap-3">
                      <div class="w-8 h-8 rounded-lg flex items-center justify-center text-xs font-bold text-white flex-shrink-0" :class="getInitialsColor(memberFullName(member))">
                        {{ getInitials(memberFullName(member)) }}
                      </div>
                      <div>
                        <p class="text-sm font-medium text-white">{{ memberFullName(member) }}</p>
                        <p class="text-xs text-slate-500">ID: {{ member.user_id || member.id }}</p>
                      </div>
                    </div>
                  </td>
                  <td class="px-4 py-3">
                    <div class="space-y-0.5">
                      <p v-if="member.person?.email" class="text-sm text-slate-300">{{ member.person.email }}</p>
                      <p v-else class="text-sm text-slate-500 italic">—</p>
                      <p v-if="member.person?.phone" class="text-xs text-slate-400">{{ member.person.phone }}</p>
                    </div>
                  </td>
                  <td class="px-4 py-3">
                    <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium" :class="roleBadgeClass(member.role)">
                      {{ roleLabel(member.role) }}
                    </span>
                  </td>
                  <td class="px-4 py-3">
                    <span class="inline-flex items-center gap-1.5 px-2.5 py-0.5 rounded-full text-xs font-medium" :class="memberStatusBadgeClass(member.status)">
                      <span class="w-1.5 h-1.5 rounded-full" :class="memberStatusDotClass(member.status)"></span>
                      {{ memberStatusLabel(member.status) }}
                    </span>
                  </td>
                  <td class="px-4 py-3 text-right">
                    <div class="flex items-center justify-end gap-2">
                      <button
                        @click="openEditRoleModal(member)"
                        class="inline-flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium text-indigo-300 bg-indigo-500/10 hover:bg-indigo-500/20 rounded-lg transition"
                      >
                        <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
                        </svg>
                        {{ $t('garages.employees.edit_role') }}
                      </button>
                      <button
                        @click="confirmRemoveMember(member)"
                        class="inline-flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium text-red-300 bg-red-500/10 hover:bg-red-500/20 rounded-lg transition"
                      >
                        <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                        </svg>
                        {{ $t('garages.employees.remove') }}
                      </button>
                    </div>
                  </td>
                </tr>
                <tr v-if="members.length === 0">
                  <td colspan="5" class="px-4 py-12 text-center">
                    <svg class="w-10 h-10 text-slate-600 mx-auto mb-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0z" />
                    </svg>
                    <p class="text-sm text-slate-400">{{ $t('garages.employees.no_employees') }}</p>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>

      <!-- ============================================================ -->
      <!-- Edit Role Modal                                              -->
      <!-- ============================================================ -->
      <div v-if="showEditModal" class="fixed inset-0 z-50 flex items-center justify-center">
        <div class="absolute inset-0 bg-black/60 backdrop-blur-sm" @click="closeEditModal"></div>
        <div class="relative bg-slate-800 border border-slate-700 rounded-xl shadow-2xl w-full max-w-md mx-4 overflow-hidden">
          <div class="px-6 py-4 border-b border-slate-700 flex items-center justify-between">
            <div class="flex items-center gap-3">
              <div class="p-1.5 rounded-lg bg-indigo-500/10 text-indigo-400">
                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
                </svg>
              </div>
              <h3 class="text-base font-semibold text-white">{{ $t('garages.employees.edit_role_title') }}</h3>
            </div>
            <button @click="closeEditModal" class="text-slate-400 hover:text-white transition">
              <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
              </svg>
            </button>
          </div>
          <div class="px-6 py-5 space-y-4">
            <div class="flex items-center gap-3 pb-4 border-b border-slate-700/50">
              <div class="w-10 h-10 rounded-lg flex items-center justify-center text-sm font-bold text-white flex-shrink-0" :class="getInitialsColor(memberFullName(editingMember))">
                {{ getInitials(memberFullName(editingMember)) }}
              </div>
              <div>
                <p class="text-sm font-medium text-white">{{ memberFullName(editingMember) }}</p>
                <p v-if="editingMember.person?.email" class="text-xs text-slate-400">{{ editingMember.person.email }}</p>
              </div>
            </div>
            <div>
              <label class="block text-xs font-medium text-slate-400 uppercase tracking-wider mb-2">{{ $t('garages.employees.role') }}</label>
              <select
                v-model="editRoleForm.role"
                class="w-full px-3 py-2.5 bg-slate-700/50 border border-slate-600 rounded-lg text-sm text-white focus:outline-none focus:ring-2 focus:ring-indigo-500/50 focus:border-indigo-500 transition"
              >
                <option v-for="opt in roleOptions" :key="opt.value" :value="opt.value">{{ opt.label }}</option>
              </select>
            </div>
            <div>
              <label class="block text-xs font-medium text-slate-400 uppercase tracking-wider mb-2">{{ $t('garages.employees.status') }}</label>
              <select
                v-model="editRoleForm.status"
                class="w-full px-3 py-2.5 bg-slate-700/50 border border-slate-600 rounded-lg text-sm text-white focus:outline-none focus:ring-2 focus:ring-indigo-500/50 focus:border-indigo-500 transition"
              >
                <option value="active">{{ $t('garages.employees.status_active') }}</option>
                <option value="inactive">{{ $t('garages.employees.status_inactive') }}</option>
              </select>
            </div>
            <p v-if="editRoleError" class="text-sm text-red-400">{{ editRoleError }}</p>
          </div>
          <div class="px-6 py-4 border-t border-slate-700 flex items-center justify-end gap-3">
            <button @click="closeEditModal" class="px-4 py-2 text-sm font-medium text-slate-300 hover:text-white bg-slate-700/50 hover:bg-slate-700 rounded-lg transition">
              {{ $t('garages.employees.cancel') }}
            </button>
            <button
              @click="saveRoleChange"
              :disabled="editRoleSaving"
              class="px-4 py-2 text-sm font-medium text-white bg-indigo-600 hover:bg-indigo-500 rounded-lg transition disabled:opacity-50 disabled:cursor-not-allowed inline-flex items-center gap-2"
            >
              <svg v-if="editRoleSaving" class="w-4 h-4 animate-spin" fill="none" viewBox="0 0 24 24">
                <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4" />
                <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
              </svg>
              {{ $t('garages.employees.save') }}
            </button>
          </div>
        </div>
      </div>

      <!-- ============================================================ -->
      <!-- Remove Confirmation Modal                                    -->
      <!-- ============================================================ -->
      <div v-if="showRemoveConfirm" class="fixed inset-0 z-50 flex items-center justify-center">
        <div class="absolute inset-0 bg-black/60 backdrop-blur-sm" @click="showRemoveConfirm = false"></div>
        <div class="relative bg-slate-800 border border-slate-700 rounded-xl shadow-2xl w-full max-w-sm mx-4 overflow-hidden">
          <div class="px-6 py-5 text-center">
            <div class="w-12 h-12 mx-auto mb-4 rounded-full bg-red-500/10 flex items-center justify-center">
              <svg class="w-6 h-6 text-red-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L4.082 16.5c-.77.833.192 2.5 1.732 2.5z" />
              </svg>
            </div>
            <h3 class="text-base font-semibold text-white mb-2">{{ $t('garages.employees.remove_title') }}</h3>
            <p class="text-sm text-slate-400">{{ $t('garages.employees.remove_confirm', { name: memberFullName(removingMember) }) }}</p>
          </div>
          <div class="px-6 py-4 border-t border-slate-700 flex items-center justify-end gap-3">
            <button @click="showRemoveConfirm = false" class="px-4 py-2 text-sm font-medium text-slate-300 hover:text-white bg-slate-700/50 hover:bg-slate-700 rounded-lg transition">
              {{ $t('garages.employees.cancel') }}
            </button>
            <button
              @click="executeRemoveMember"
              :disabled="removeSaving"
              class="px-4 py-2 text-sm font-medium text-white bg-red-600 hover:bg-red-500 rounded-lg transition disabled:opacity-50 disabled:cursor-not-allowed inline-flex items-center gap-2"
            >
              <svg v-if="removeSaving" class="w-4 h-4 animate-spin" fill="none" viewBox="0 0 24 24">
                <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4" />
                <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
              </svg>
              {{ $t('garages.employees.remove_btn') }}
            </button>
          </div>
        </div>
      </div>

      <!-- Placeholder for fleet & analytics tabs -->
      <div v-if="activeTab === 'fleet' || activeTab === 'analytics'" class="flex items-center justify-center py-20">
        <p class="text-slate-500 text-sm">{{ $t('garages.details.coming_soon') }}</p>
      </div>
    </template>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'

definePageMeta({
  middleware: 'auth',
})

const route = useRoute()
const router = useRouter()

// ── Types ──────────────────────────────────────────────────────────

interface PersonBrief {
  first_name: string
  last_name: string
  email: string | null
  phone: string | null
}

interface OrganizationMember {
  id: number
  user_id: number | null
  organization_id: number
  role: string
  status: string
  is_verified: boolean
  person: PersonBrief | null
  created_at: string | null
  updated_at: string | null
}

interface ContactPersonInfo {
  id: number
  full_name: string
  role: string
  department: string | null
  phone: string | null
  email: string | null
  is_primary: boolean
}

interface SubscriptionSummary {
  tier_name: string
  tier_level: number
  valid_from: string | null
  expires_at: string | null
  is_active: boolean
  asset_count: number
  asset_limit: number
}

interface GarageDetails {
  id: number
  name: string
  full_name: string
  display_name: string | null
  status: string
  is_active: boolean
  is_verified: boolean
  org_type: string
  address_city: string | null
  address_zip: string | null
  address_street_name: string | null
  address_street_type: string | null
  address_house_number: string | null
  tax_number: string | null
  reg_number: string | null
  subscription: SubscriptionSummary | null
  primary_contact: ContactPersonInfo | null
  created_at: string | null
  member_count: number
  members: OrganizationMember[]
}

// ── State ──────────────────────────────────────────────────────────

const loading = ref(true)
const error = ref<string | null>(null)
const garage = ref<GarageDetails | null>(null)
const activeTab = ref('general')

const tabs = [
  { key: 'general', label: 'Általános' },
  { key: 'employees', label: 'Dolgozók' },
  { key: 'fleet', label: 'Flotta' },
  { key: 'analytics', label: 'Analitika' },
]

// ── Computed ───────────────────────────────────────────────────────

const members = computed(() => garage.value?.members || [])

const formattedAddress = computed(() => {
  if (!garage.value) return '—'
  const parts: string[] = []
  if (garage.value.address_zip) parts.push(garage.value.address_zip)
  if (garage.value.address_city) parts.push(garage.value.address_city)
  const streetParts: string[] = []
  if (garage.value.address_street_name) streetParts.push(garage.value.address_street_name)
  if (garage.value.address_street_type) streetParts.push(garage.value.address_street_type)
  if (garage.value.address_house_number) streetParts.push(garage.value.address_house_number)
  if (streetParts.length > 0) parts.push(streetParts.join(' '))
  return parts.length > 0 ? parts.join(', ') : '—'
})

// ── Auth Helper ────────────────────────────────────────────────────

function getAuthHeaders() {
  const tokenCookie = useCookie('access_token')
  const token = tokenCookie.value
  return token ? { Authorization: `Bearer ${token}` } : {}
}

// ── Data Fetching ──────────────────────────────────────────────────

async function fetchDetails() {
  const orgId = route.params.id
  if (!orgId) {
    error.value = 'Invalid garage ID'
    loading.value = false
    return
  }

  loading.value = true
  error.value = null
  try {
    const response = await $fetch<GarageDetails>(`/api/v1/admin/organizations/${orgId}/details`, {
      headers: getAuthHeaders(),
    })
    garage.value = response
  } catch (err: any) {
    console.error('[GarageDetails] Failed to fetch:', err)
    error.value = err?.data?.detail || err?.message || 'Failed to load garage details'
  } finally {
    loading.value = false
  }
}

// ── Navigation ─────────────────────────────────────────────────────

function goBack() {
  router.push('/garages')
}

// ── Employee Helpers ───────────────────────────────────────────────

function memberFullName(m: OrganizationMember): string {
  if (m.person) {
    return [m.person.last_name, m.person.first_name].filter(Boolean).join(' ').trim() || 'Unknown User'
  }
  return `User #${m.user_id || m.id}`
}

const roleOptions = [
  { value: 'OWNER', label: 'Tulajdonos' },
  { value: 'ADMIN', label: 'Adminisztrátor' },
  { value: 'MANAGER', label: 'Menedzser' },
  { value: 'MEMBER', label: 'Tag' },
  { value: 'AGENT', label: 'Ügynök' },
]

function roleLabel(role: string): string {
  const map: Record<string, string> = {
    OWNER: 'Tulajdonos',
    ADMIN: 'Adminisztrátor',
    MANAGER: 'Menedzser',
    MEMBER: 'Tag',
    AGENT: 'Ügynök',
  }
  return map[role] || role
}

function roleBadgeClass(role: string): string {
  if (role === 'OWNER') return 'bg-amber-500/20 text-amber-300'
  if (role === 'ADMIN') return 'bg-purple-500/20 text-purple-300'
  if (role === 'MANAGER') return 'bg-blue-500/20 text-blue-300'
  if (role === 'AGENT') return 'bg-cyan-500/20 text-cyan-300'
  return 'bg-slate-500/20 text-slate-300'
}

function memberStatusLabel(status: string): string {
  if (status === 'active') return 'Aktív'
  if (status === 'inactive') return 'Inaktív'
  if (status === 'archived') return 'Archivált'
  return status
}

function memberStatusBadgeClass(status: string): string {
  if (status === 'active') return 'bg-emerald-500/10 text-emerald-400'
  if (status === 'inactive') return 'bg-slate-500/10 text-slate-400'
  if (status === 'archived') return 'bg-red-500/10 text-red-400'
  return 'bg-slate-500/10 text-slate-400'
}

function memberStatusDotClass(status: string): string {
  if (status === 'active') return 'bg-emerald-400'
  if (status === 'inactive') return 'bg-slate-400'
  if (status === 'archived') return 'bg-red-400'
  return 'bg-slate-400'
}

// ── Edit Role Modal ────────────────────────────────────────────────

const showEditModal = ref(false)
const editRoleSaving = ref(false)
const editRoleError = ref<string | null>(null)
const editingMember = ref<OrganizationMember>({} as OrganizationMember)
const editRoleForm = ref({ role: 'MEMBER', status: 'active' })

function openEditRoleModal(member: OrganizationMember) {
  editingMember.value = member
  editRoleForm.value = {
    role: member.role,
    status: member.status,
  }
  editRoleError.value = null
  showEditModal.value = true
}

function closeEditModal() {
  showEditModal.value = false
  editRoleError.value = null
}

async function saveRoleChange() {
  if (!editingMember.value?.id) return
  editRoleSaving.value = true
  editRoleError.value = null
  try {
    const orgId = route.params.id
    await $fetch(`/api/v1/admin/organizations/${orgId}/members/${editingMember.value.id}`, {
      method: 'PUT',
      headers: getAuthHeaders(),
      body: {
        role: editRoleForm.value.role,
        status: editRoleForm.value.status,
      },
    })
    closeEditModal()
    await fetchDetails()
  } catch (err: any) {
    console.error('[GarageDetails] Failed to update member:', err)
    editRoleError.value = err?.data?.detail || err?.message || 'Failed to update member role'
  } finally {
    editRoleSaving.value = false
  }
}

// ── Remove Member ──────────────────────────────────────────────────

const showRemoveConfirm = ref(false)
const removeSaving = ref(false)
const removingMember = ref<OrganizationMember>({} as OrganizationMember)

function confirmRemoveMember(member: OrganizationMember) {
  removingMember.value = member
  showRemoveConfirm.value = true
}

async function executeRemoveMember() {
  if (!removingMember.value?.id) return
  removeSaving.value = true
  try {
    const orgId = route.params.id
    await $fetch(`/api/v1/admin/organizations/${orgId}/members/${removingMember.value.id}`, {
      method: 'DELETE',
      headers: getAuthHeaders(),
    })
    showRemoveConfirm.value = false
    await fetchDetails()
  } catch (err: any) {
    console.error('[GarageDetails] Failed to remove member:', err)
  } finally {
    removeSaving.value = false
  }
}

// ── General Helpers ────────────────────────────────────────────────

function garageDisplayName(g: GarageDetails): string {
  return g.display_name || g.name || g.full_name
}

function getInitials(name: string): string {
  return name
    .split(' ')
    .map(w => w.charAt(0))
    .join('')
    .toUpperCase()
    .slice(0, 2)
}

function getInitialsColor(name: string): string {
  const colors = [
    'bg-amber-600', 'bg-purple-600', 'bg-slate-600',
    'bg-indigo-600', 'bg-emerald-600', 'bg-rose-600',
    'bg-cyan-600', 'bg-orange-600', 'bg-teal-600',
  ]
  let hash = 0
  for (let i = 0; i < name.length; i++) {
    hash = name.charCodeAt(i) + ((hash << 5) - hash)
  }
  return colors[Math.abs(hash) % colors.length]
}

function statusBadgeClass(status: string): string {
  if (status === 'active') return 'bg-emerald-500/10 text-emerald-400'
  if (status === 'suspended') return 'bg-red-500/10 text-red-400'
  if (status === 'pending_verification') return 'bg-amber-500/10 text-amber-400'
  return 'bg-slate-500/10 text-slate-400'
}

function statusDotClass(status: string): string {
  if (status === 'active') return 'bg-emerald-400'
  if (status === 'suspended') return 'bg-red-400'
  if (status === 'pending_verification') return 'bg-amber-400'
  return 'bg-slate-400'
}

function statusLabel(status: string): string {
  if (status === 'active') return 'Aktív'
  if (status === 'suspended') return 'Felfüggesztve'
  if (status === 'pending_verification') return 'Függőben'
  return 'Inaktív'
}

function tierBadgeClass(tierName: string): string {
  const name = tierName.toLowerCase()
  if (name.includes('enterprise') || name.includes('vip') || name.includes('corp')) return 'bg-purple-500/20 text-purple-300'
  if (name.includes('premium') || name.includes('pro')) return 'bg-amber-500/20 text-amber-300'
  return 'bg-slate-500/20 text-slate-300'
}

function orgTypeLabel(type: string): string {
  const labels: Record<string, string> = {
    individual: 'Magánszemély',
    service: 'Szerviz',
    service_provider: 'Szolgáltató',
    fleet_owner: 'Flottatulajdonos',
    club: 'Klub',
    business: 'Vállalkozás',
  }
  return labels[type] || type
}

function formatDate(dateStr: string | null): string {
  if (!dateStr) return '—'
  try {
    const d = new Date(dateStr)
    return d.toLocaleDateString('hu-HU', {
      year: 'numeric',
      month: 'short',
      day: 'numeric',
    })
  } catch {
    return dateStr
  }
}

// ── Lifecycle ──────────────────────────────────────────────────────

onMounted(() => {
  fetchDetails()
})
</script>