<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('users.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="fetchUser" class="px-4 py-2 text-sm bg-indigo-600/20 text-indigo-300 hover:bg-indigo-600/30 rounded-lg transition">
        {{ $t('users.details.retry') }}
      </button>
    </div>

    <!-- Content -->
    <template v-else-if="user">
      <!-- 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('users.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(userDisplayName)"
            >
              {{ getInitials(userDisplayName) }}
            </div>
            <div>
              <div class="flex items-center gap-3">
                <h1 class="text-2xl font-bold text-white">{{ userDisplayName }}</h1>
                <span
                  class="inline-flex items-center px-3 py-1 rounded-full text-xs font-medium"
                  :class="statusBadgeClass"
                >
                  <span class="w-1.5 h-1.5 rounded-full mr-1.5" :class="statusDotClass"></span>
                  {{ statusLabel }}
                </span>
                <span
                  v-if="user.is_vip"
                  class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-yellow-500/10 text-yellow-400"
                >
                  <svg class="w-3 h-3 mr-1" fill="currentColor" viewBox="0 0 20 20">
                    <path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z" />
                  </svg>
                  VIP
                </span>
              </div>
              <p class="text-sm text-slate-400 mt-0.5">
                {{ user.email }}
                <span v-if="user.person?.phone" class="ml-2 text-slate-500">· {{ user.person.phone }}</span>
              </p>
            </div>
          </div>
          <div class="flex items-center gap-3">
            <button
              v-if="hasEditPermission"
              @click="openEditModal"
              class="inline-flex items-center gap-1.5 px-4 py-2 text-sm font-medium bg-indigo-600/20 text-indigo-300 hover:bg-indigo-600/30 rounded-lg transition"
            >
              <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>
              {{ $t('users.details.edit') }}
            </button>
          </div>
        </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'"
          >
            {{ $t(tab.label) }}
          </button>
        </nav>
      </div>

      <!-- ============================================================ -->
      <!-- Profile Tab                                                   -->
      <!-- ============================================================ -->
      <div v-if="activeTab === 'profile'" class="space-y-6">
        <!-- User Account Info Card -->
        <div class="bg-slate-800/50 border border-slate-700 rounded-xl p-6">
          <div class="flex items-center gap-3 mb-5">
            <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="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
              </svg>
            </div>
            <h3 class="text-base font-semibold text-white">{{ $t('users.details.account_info') }}</h3>
          </div>

          <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            <div>
              <label class="block text-xs text-slate-400 mb-1">{{ $t('users.details.user_id') }}</label>
              <p class="text-sm text-white font-mono">{{ user.id }}</p>
            </div>
            <div>
              <label class="block text-xs text-slate-400 mb-1">{{ $t('users.email') }}</label>
              <p class="text-sm text-white">{{ user.email }}</p>
            </div>
            <div>
              <label class="block text-xs text-slate-400 mb-1">{{ $t('users.role') }}</label>
              <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium" :class="roleBadgeClass(user.role)">
                {{ roleLabel(user.role) }}
              </span>
            </div>
            <div>
              <label class="block text-xs text-slate-400 mb-1">{{ $t('users.details.registration_date') }}</label>
              <p class="text-sm text-white">{{ formatDate(user.created_at) }}</p>
            </div>
            <div>
              <label class="block text-xs text-slate-400 mb-1">{{ $t('users.details.last_login') }}</label>
              <p class="text-sm text-white">{{ formatDate(user.last_login_at) || '—' }}</p>
            </div>
            <div>
              <label class="block text-xs text-slate-400 mb-1">{{ $t('users.details.ui_mode') }}</label>
              <p class="text-sm text-white capitalize">{{ user.ui_mode || 'personal' }}</p>
            </div>
            <div>
              <label class="block text-xs text-slate-400 mb-1">{{ $t('users.language') }}</label>
              <p class="text-sm text-white uppercase">{{ user.preferred_language || '—' }}</p>
            </div>
            <div>
              <label class="block text-xs text-slate-400 mb-1">{{ $t('users.details.region') }}</label>
              <p class="text-sm text-white">{{ user.region_code || '—' }}</p>
            </div>
            <div>
              <label class="block text-xs text-slate-400 mb-1">{{ $t('users.details.currency') }}</label>
              <p class="text-sm text-white">{{ user.preferred_currency || '—' }}</p>
            </div>
          </div>
        </div>

        <!-- Subscription Info Card -->
        <div class="bg-slate-800/50 border border-slate-700 rounded-xl p-6">
          <div class="flex items-center gap-3 mb-5">
            <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="M3 10h18M7 15h1m4 0h1m-7 4h12a3 3 0 003-3V8a3 3 0 00-3-3H6a3 3 0 00-3 3v8a3 3 0 003 3z" />
              </svg>
            </div>
            <h3 class="text-base font-semibold text-white">{{ $t('users.details.subscription_info') }}</h3>
          </div>

          <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            <div>
              <label class="block text-xs text-slate-400 mb-1">{{ $t('users.package') }}</label>
              <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium" :class="planBadgeClass(user.subscription_plan)">
                {{ user.subscription_plan || '—' }}
              </span>
            </div>
            <div>
              <label class="block text-xs text-slate-400 mb-1">{{ $t('users.details.subscription_expires') }}</label>
              <p class="text-sm text-white">{{ formatDate(user.subscription_expires_at) || '—' }}</p>
            </div>
            <div>
              <label class="block text-xs text-slate-400 mb-1">{{ $t('users.details.scope_level') }}</label>
              <p class="text-sm text-white">{{ user.scope_level || 'individual' }}</p>
            </div>
            <div>
              <label class="block text-xs text-slate-400 mb-1">{{ $t('users.details.max_vehicles') }}</label>
              <p class="text-sm text-white">{{ user.max_vehicles }}</p>
            </div>
            <div>
              <label class="block text-xs text-slate-400 mb-1">{{ $t('users.details.max_garages') }}</label>
              <p class="text-sm text-white">{{ user.max_garages }}</p>
            </div>
          </div>
        </div>

        <!-- Person Details Card (if exists) -->
        <div v-if="user.person" class="bg-slate-800/50 border border-slate-700 rounded-xl p-6">
          <div class="flex items-center gap-3 mb-5">
            <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="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
              </svg>
            </div>
            <h3 class="text-base font-semibold text-white">{{ $t('users.details.personal_info') }}</h3>
          </div>

          <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            <div>
              <label class="block text-xs text-slate-400 mb-1">{{ $t('users.details.last_name') }}</label>
              <p class="text-sm text-white">{{ user.person.last_name || '—' }}</p>
            </div>
            <div>
              <label class="block text-xs text-slate-400 mb-1">{{ $t('users.details.first_name') }}</label>
              <p class="text-sm text-white">{{ user.person.first_name || '—' }}</p>
            </div>
            <div>
              <label class="block text-xs text-slate-400 mb-1">{{ $t('users.details.phone') }}</label>
              <p class="text-sm text-white">{{ user.person.phone || '—' }}</p>
            </div>
            <div>
              <label class="block text-xs text-slate-400 mb-1">{{ $t('users.details.birth_place') }}</label>
              <p class="text-sm text-white">{{ user.person.birth_place || '—' }}</p>
            </div>
            <div>
              <label class="block text-xs text-slate-400 mb-1">{{ $t('users.details.birth_date') }}</label>
              <p class="text-sm text-white">{{ formatDate(user.person.birth_date) || '—' }}</p>
            </div>
            <div>
              <label class="block text-xs text-slate-400 mb-1">{{ $t('users.details.mothers_name') }}</label>
              <p class="text-sm text-white">{{ [user.person.mothers_last_name, user.person.mothers_first_name].filter(Boolean).join(' ') || '—' }}</p>
            </div>
          </div>

          <!-- Address sub-card -->
          <div v-if="user.person.address" class="mt-6 pt-6 border-t border-slate-700">
            <h4 class="text-sm font-semibold text-slate-300 mb-3">{{ $t('users.details.address') }}</h4>
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
              <div>
                <label class="block text-xs text-slate-400 mb-1">{{ $t('users.details.zip') }}</label>
                <p class="text-sm text-white">{{ user.person.address.address_zip || '—' }}</p>
              </div>
              <div>
                <label class="block text-xs text-slate-400 mb-1">{{ $t('users.details.city') }}</label>
                <p class="text-sm text-white">{{ user.person.address.address_city || '—' }}</p>
              </div>
              <div>
                <label class="block text-xs text-slate-400 mb-1">{{ $t('users.details.street') }}</label>
                <p class="text-sm text-white">{{ [user.person.address.address_street_type, user.person.address.address_street_name].filter(Boolean).join(' ') || '—' }}</p>
              </div>
              <div>
                <label class="block text-xs text-slate-400 mb-1">{{ $t('users.details.house_number') }}</label>
                <p class="text-sm text-white">{{ user.person.address.address_house_number || '—' }}</p>
              </div>
            </div>
          </div>
        </div>

        <!-- No Person record -->
        <div v-else class="bg-slate-800/50 border border-slate-700 rounded-xl p-6 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="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
          </svg>
          <p class="text-sm text-slate-400">{{ $t('users.details.no_person_record') }}</p>
        </div>
      </div>

      <!-- ============================================================ -->
      <!-- Memberships Tab                                               -->
      <!-- ============================================================ -->
      <div v-if="activeTab === 'memberships'" 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-purple-500/10 text-purple-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 2v16l3.5-2 3.5 2 3.5-2 3.5 2M10 8.5a.5.5 0 11-1 0 .5.5 0 011 0zm5 5a.5.5 0 11-1 0 .5.5 0 011 0z" />
              </svg>
            </div>
            <div>
              <h3 class="text-base font-semibold text-white">{{ $t('users.details.memberships') }}</h3>
              <p class="text-xs text-slate-400 mt-0.5">{{ $t('users.details.memberships_count', { count: memberships.length }) }}</p>
            </div>
          </div>
        </div>

        <div v-if="membershipsLoading" class="flex items-center justify-center py-12">
          <svg class="w-6 h-6 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>
        </div>

        <div v-else-if="memberships.length === 0" class="bg-slate-800/50 border border-slate-700 rounded-xl p-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('users.details.no_memberships') }}</p>
        </div>

        <div v-else 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('users.details.org_name') }}</th>
                  <th class="text-left px-4 py-3 text-xs font-medium text-slate-400 uppercase tracking-wider">{{ $t('users.details.org_role') }}</th>
                  <th class="text-left px-4 py-3 text-xs font-medium text-slate-400 uppercase tracking-wider">{{ $t('users.details.member_status') }}</th>
                  <th class="text-left px-4 py-3 text-xs font-medium text-slate-400 uppercase tracking-wider">{{ $t('users.details.joined_at') }}</th>
                  <th class="text-left px-4 py-3 text-xs font-medium text-slate-400 uppercase tracking-wider">{{ $t('users.details.verified') }}</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="m in memberships" :key="m.id" class="border-b border-slate-700/50 last:border-b-0 hover:bg-slate-700/30 transition">
                  <td class="px-4 py-3">
                    <NuxtLink
                      :to="'/garages/' + m.organization_id"
                      class="text-sm font-medium text-white hover:text-indigo-400 hover:underline transition-colors"
                    >
                      {{ m.organization_display_name || m.organization_name }}
                    </NuxtLink>
                  </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(m.role)">
                      {{ orgRoleLabel(m.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(m.status)">
                      <span class="w-1.5 h-1.5 rounded-full" :class="memberStatusDotClass(m.status)"></span>
                      {{ memberStatusLabel(m.status) }}
                    </span>
                  </td>
                  <td class="px-4 py-3 text-slate-300 text-xs">{{ formatDate(m.joined_at) || '—' }}</td>
                  <td class="px-4 py-3">
                    <span v-if="m.is_verified" class="inline-flex items-center gap-1 text-xs text-emerald-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="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
                      </svg>
                      {{ $t('users.details.verified_yes') }}
                    </span>
                    <span v-else class="text-xs text-slate-500">{{ $t('users.details.verified_no') }}</span>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>

      <!-- ============================================================ -->
      <!-- Edit Modal                                                    -->
      <!-- ============================================================ -->
      <div
        v-if="showEditModal"
        class="fixed inset-0 z-50 flex items-center justify-center p-4"
      >
        <!-- Backdrop -->
        <div class="absolute inset-0 bg-black/60 backdrop-blur-sm" @click="closeEditModal"></div>

        <!-- Modal -->
        <div class="relative w-full max-w-2xl bg-slate-800 border border-slate-700 rounded-2xl shadow-2xl max-h-[90vh] overflow-hidden flex flex-col">
          <!-- Header -->
          <div class="px-6 py-4 border-b border-slate-700 flex items-center justify-between flex-shrink-0">
            <h3 class="text-lg font-semibold text-white">{{ $t('users.details.edit_user') }}</h3>
            <button @click="closeEditModal" class="p-1.5 rounded-lg text-slate-400 hover:text-white hover:bg-slate-700 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>

          <!-- Scrollable Body -->
          <div class="flex-1 overflow-y-auto p-6 space-y-5">
            <!-- Account Fields -->
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <label class="block text-xs font-medium text-slate-400 mb-1.5">{{ $t('users.email') }}</label>
                <input
                  v-model="editForm.email"
                  type="email"
                  class="w-full px-3 py-2 text-sm bg-slate-700/50 border border-slate-600 rounded-lg text-white placeholder-slate-500 focus:outline-none focus:ring-2 focus:ring-indigo-500/50 focus:border-indigo-500"
                />
              </div>
              <div>
                <label class="block text-xs font-medium text-slate-400 mb-1.5">{{ $t('users.details.preferred_language') }}</label>
                <select
                  v-model="editForm.preferred_language"
                  class="w-full px-3 py-2 text-sm bg-slate-700/50 border border-slate-600 rounded-lg text-white focus:outline-none focus:ring-2 focus:ring-indigo-500/50 focus:border-indigo-500"
                >
                  <option value="hu">HU</option>
                  <option value="en">EN</option>
                  <option value="de">DE</option>
                  <option value="ro">RO</option>
                </select>
              </div>
            </div>

            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <label class="block text-xs font-medium text-slate-400 mb-1.5">{{ $t('users.details.region') }}</label>
                <input
                  v-model="editForm.region_code"
                  type="text"
                  maxlength="5"
                  class="w-full px-3 py-2 text-sm bg-slate-700/50 border border-slate-600 rounded-lg text-white placeholder-slate-500 focus:outline-none focus:ring-2 focus:ring-indigo-500/50 focus:border-indigo-500"
                />
              </div>
              <div>
                <label class="block text-xs font-medium text-slate-400 mb-1.5">{{ $t('users.details.currency') }}</label>
                <input
                  v-model="editForm.preferred_currency"
                  type="text"
                  maxlength="3"
                  class="w-full px-3 py-2 text-sm bg-slate-700/50 border border-slate-600 rounded-lg text-white placeholder-slate-500 focus:outline-none focus:ring-2 focus:ring-indigo-500/50 focus:border-indigo-500"
                />
              </div>
            </div>

            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <label class="block text-xs font-medium text-slate-400 mb-1.5">{{ $t('users.package') }}</label>
                <select
                  v-model="editForm.subscription_plan"
                  class="w-full px-3 py-2 text-sm bg-slate-700/50 border border-slate-600 rounded-lg text-white focus:outline-none focus:ring-2 focus:ring-indigo-500/50 focus:border-indigo-500"
                >
                  <option value="FREE">FREE</option>
                  <option value="PREMIUM">PREMIUM</option>
                  <option value="ENTERPRISE">ENTERPRISE</option>
                </select>
              </div>
              <div>
                <label class="block text-xs font-medium text-slate-400 mb-1.5">{{ $t('users.details.subscription_expires') }}</label>
                <input
                  v-model="editForm.subscription_expires_at"
                  type="datetime-local"
                  class="w-full px-3 py-2 text-sm bg-slate-700/50 border border-slate-600 rounded-lg text-white focus:outline-none focus:ring-2 focus:ring-indigo-500/50 focus:border-indigo-500"
                />
              </div>
            </div>

            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <label class="block text-xs font-medium text-slate-400 mb-1.5">{{ $t('users.details.scope_level') }}</label>
                <select
                  v-model="editForm.scope_level"
                  class="w-full px-3 py-2 text-sm bg-slate-700/50 border border-slate-600 rounded-lg text-white focus:outline-none focus:ring-2 focus:ring-indigo-500/50 focus:border-indigo-500"
                >
                  <option value="individual">individual</option>
                  <option value="organization">organization</option>
                  <option value="group">group</option>
                </select>
              </div>
              <div>
                <label class="block text-xs font-medium text-slate-400 mb-1.5">{{ $t('users.details.scope_id') }}</label>
                <input
                  v-model="editForm.scope_id"
                  type="text"
                  class="w-full px-3 py-2 text-sm bg-slate-700/50 border border-slate-600 rounded-lg text-white placeholder-slate-500 focus:outline-none focus:ring-2 focus:ring-indigo-500/50 focus:border-indigo-500"
                />
              </div>
            </div>

            <div class="flex items-center gap-6 pt-2">
              <label class="flex items-center gap-2 cursor-pointer">
                <input
                  v-model="editForm.is_active"
                  type="checkbox"
                  class="rounded border-slate-600 bg-slate-700 text-indigo-600 focus:ring-indigo-500/50"
                />
                <span class="text-sm text-slate-300">{{ $t('users.details.is_active') }}</span>
              </label>
              <label class="flex items-center gap-2 cursor-pointer">
                <input
                  v-model="editForm.is_vip"
                  type="checkbox"
                  class="rounded border-slate-600 bg-slate-700 text-indigo-600 focus:ring-indigo-500/50"
                />
                <span class="text-sm text-slate-300">{{ $t('users.details.is_vip') }}</span>
              </label>
            </div>

            <!-- Person Fields -->
            <div class="border-t border-slate-700 pt-5">
              <h4 class="text-sm font-semibold text-white mb-4">{{ $t('users.details.personal_info') }}</h4>
              <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label class="block text-xs font-medium text-slate-400 mb-1.5">{{ $t('users.details.last_name') }}</label>
                  <input
                    v-model="editForm.person_last_name"
                    type="text"
                    class="w-full px-3 py-2 text-sm bg-slate-700/50 border border-slate-600 rounded-lg text-white placeholder-slate-500 focus:outline-none focus:ring-2 focus:ring-indigo-500/50 focus:border-indigo-500"
                  />
                </div>
                <div>
                  <label class="block text-xs font-medium text-slate-400 mb-1.5">{{ $t('users.details.first_name') }}</label>
                  <input
                    v-model="editForm.person_first_name"
                    type="text"
                    class="w-full px-3 py-2 text-sm bg-slate-700/50 border border-slate-600 rounded-lg text-white placeholder-slate-500 focus:outline-none focus:ring-2 focus:ring-indigo-500/50 focus:border-indigo-500"
                  />
                </div>
                <div>
                  <label class="block text-xs font-medium text-slate-400 mb-1.5">{{ $t('users.details.phone') }}</label>
                  <input
                    v-model="editForm.person_phone"
                    type="text"
                    class="w-full px-3 py-2 text-sm bg-slate-700/50 border border-slate-600 rounded-lg text-white placeholder-slate-500 focus:outline-none focus:ring-2 focus:ring-indigo-500/50 focus:border-indigo-500"
                  />
                </div>
                <div>
                  <label class="block text-xs font-medium text-slate-400 mb-1.5">{{ $t('users.details.mothers_name') }}</label>
                  <input
                    v-model="editForm.person_mothers_last_name"
                    type="text"
                    placeholder="Last name"
                    class="w-full px-3 py-2 text-sm bg-slate-700/50 border border-slate-600 rounded-lg text-white placeholder-slate-500 focus:outline-none focus:ring-2 focus:ring-indigo-500/50 focus:border-indigo-500"
                  />
                </div>
                <div>
                  <label class="block text-xs font-medium text-slate-400 mb-1.5">{{ $t('users.details.mothers_first_name') }}</label>
                  <input
                    v-model="editForm.person_mothers_first_name"
                    type="text"
                    placeholder="First name"
                    class="w-full px-3 py-2 text-sm bg-slate-700/50 border border-slate-600 rounded-lg text-white placeholder-slate-500 focus:outline-none focus:ring-2 focus:ring-indigo-500/50 focus:border-indigo-500"
                  />
                </div>
                <div>
                  <label class="block text-xs font-medium text-slate-400 mb-1.5">{{ $t('users.details.birth_place') }}</label>
                  <input
                    v-model="editForm.person_birth_place"
                    type="text"
                    class="w-full px-3 py-2 text-sm bg-slate-700/50 border border-slate-600 rounded-lg text-white placeholder-slate-500 focus:outline-none focus:ring-2 focus:ring-indigo-500/50 focus:border-indigo-500"
                  />
                </div>
                <div>
                  <label class="block text-xs font-medium text-slate-400 mb-1.5">{{ $t('users.details.birth_date') }}</label>
                  <input
                    v-model="editForm.person_birth_date"
                    type="date"
                    class="w-full px-3 py-2 text-sm bg-slate-700/50 border border-slate-600 rounded-lg text-white focus:outline-none focus:ring-2 focus:ring-indigo-500/50 focus:border-indigo-500"
                  />
                </div>
              </div>
            </div>
          </div>

          <!-- Footer -->
          <div class="px-6 py-4 border-t border-slate-700 flex items-center justify-end gap-3 flex-shrink-0">
            <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('users.details.cancel') }}
            </button>
            <button
              @click="saveEdit"
              :disabled="saving"
              class="inline-flex items-center gap-2 px-4 py-2 text-sm font-medium bg-indigo-600 text-white hover:bg-indigo-500 rounded-lg transition disabled:opacity-50"
            >
              <svg v-if="saving" 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>
              {{ saving ? $t('users.details.saving') : $t('users.details.save') }}
            </button>
          </div>
        </div>
      </div>

      <!-- ============================================================ -->
      <!-- Notification Toast                                             -->
      <!-- ============================================================ -->
      <div
        v-if="notification.show"
        class="fixed bottom-6 right-6 z-50 px-5 py-3 rounded-xl shadow-2xl text-sm font-medium transition-all"
        :class="notification.type === 'success' ? 'bg-emerald-600 text-white' : 'bg-red-600 text-white'"
      >
        <div class="flex items-center gap-2">
          <svg v-if="notification.type === 'success'" 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="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
          </svg>
          <svg v-else 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 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
          </svg>
          {{ notification.message }}
        </div>
      </div>
    </template>
  </div>
</template>

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

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

const userId = route.params.id as string

// State
const loading = ref(true)
const error = ref<string | null>(null)
const user = ref<any>(null)
const memberships = ref<any[]>([])
const membershipsLoading = ref(false)
const activeTab = ref('profile')

// Edit Modal
const showEditModal = ref(false)
const saving = ref(false)
const editForm = ref({
  email: '',
  preferred_language: '',
  region_code: '',
  preferred_currency: '',
  subscription_plan: '',
  subscription_expires_at: '',
  scope_level: '',
  scope_id: '',
  is_active: true,
  is_vip: false,
  person_last_name: '',
  person_first_name: '',
  person_phone: '',
  person_mothers_last_name: '',
  person_mothers_first_name: '',
  person_birth_place: '',
  person_birth_date: '',
})

// Notification
const notification = ref({ show: false, type: 'success' as 'success' | 'error', message: '' })

// Tab definitions
const tabs = [
  { key: 'profile', label: 'users.details.profile_tab' },
  { key: 'memberships', label: 'users.details.memberships_tab' },
]

// Computed
const userDisplayName = computed(() => {
  if (!user.value) return ''
  const p = user.value.person
  if (p?.last_name || p?.first_name) {
    return [p.last_name, p.first_name].filter(Boolean).join(' ')
  }
  return user.value.email || 'User #' + user.value.id
})

const statusLabel = computed(() => {
  if (!user.value) return ''
  const map: Record<string, string> = {
    active: 'Active',
    inactive: 'Inactive',
    deleted: 'Deleted',
    banned: 'Banned',
  }
  return map[user.value.status?.toLowerCase()] || user.value.status || 'Active'
})

const statusBadgeClass = computed(() => {
  if (!user.value) return ''
  const map: Record<string, string> = {
    active: 'bg-emerald-500/10 text-emerald-400',
    inactive: 'bg-slate-500/10 text-slate-400',
    deleted: 'bg-red-500/10 text-red-400',
    banned: 'bg-red-500/10 text-red-400',
  }
  return map[user.value.status?.toLowerCase()] || 'bg-emerald-500/10 text-emerald-400'
})

const statusDotClass = computed(() => {
  if (!user.value) return ''
  const map: Record<string, string> = {
    active: 'bg-emerald-400',
    inactive: 'bg-slate-400',
    deleted: 'bg-red-400',
    banned: 'bg-red-400',
  }
  return map[user.value.status?.toLowerCase()] || 'bg-emerald-400'
})

const hasEditPermission = computed(() => {
  if (auth.isAdmin) return true
  return !!auth.user?.system_capabilities?.['users:edit']
})

// API calls
async function fetchUser() {
  loading.value = true
  error.value = null
  try {
    const tokenCookie = useCookie('access_token')
    const token = (tokenCookie.value || auth.token || '').trim()
    const headers: Record<string, string> = {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json',
    }

    const res = await fetch(`/api/v1/admin/users/${userId}`, { headers })
    if (!res.ok) {
      if (res.status === 404) throw new Error('User not found')
      if (res.status === 403) throw new Error('Access denied')
      throw new Error(`Failed to fetch user: ${res.status}`)
    }

    const data = await res.json()
    user.value = data

    // Fetch memberships after user loads
    fetchMemberships()
  } catch (e: any) {
    error.value = e.message || 'Failed to load user details'
  } finally {
    loading.value = false
  }
}

async function fetchMemberships() {
  membershipsLoading.value = true
  try {
    const tokenCookie = useCookie('access_token')
    const token = (tokenCookie.value || auth.token || '').trim()
    const headers: Record<string, string> = {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json',
    }

    const res = await fetch(`/api/v1/admin/users/${userId}/memberships`, { headers })
    if (!res.ok) throw new Error(`Failed to fetch memberships: ${res.status}`)

    const data = await res.json()
    memberships.value = Array.isArray(data) ? data : (data.memberships || [])
  } catch (e: any) {
    console.error('Memberships fetch error:', e)
    memberships.value = []
  } finally {
    membershipsLoading.value = false
  }
}

// Edit Modal
function openEditModal() {
  if (!user.value) return
  const u = user.value
  const p = u.person || {}
  editForm.value = {
    email: u.email || '',
    preferred_language: u.preferred_language || '',
    region_code: u.region_code || '',
    preferred_currency: u.preferred_currency || '',
    subscription_plan: u.subscription_plan || '',
    subscription_expires_at: u.subscription_expires_at
      ? u.subscription_expires_at.slice(0, 16)
      : '',
    scope_level: u.scope_level || '',
    scope_id: u.scope_id || '',
    is_active: u.status === 'active',
    is_vip: u.is_vip || false,
    person_last_name: p.last_name || '',
    person_first_name: p.first_name || '',
    person_phone: p.phone || '',
    person_mothers_last_name: p.mothers_last_name || '',
    person_mothers_first_name: p.mothers_first_name || '',
    person_birth_place: p.birth_place || '',
    person_birth_date: p.birth_date ? p.birth_date.slice(0, 10) : '',
  }
  showEditModal.value = true
}

function closeEditModal() {
  showEditModal.value = false
}

async function saveEdit() {
  saving.value = true
  try {
    const tokenCookie = useCookie('access_token')
    const token = (tokenCookie.value || auth.token || '').trim()
    const headers: Record<string, string> = {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json',
    }

    const payload: Record<string, any> = {
      email: editForm.value.email || undefined,
      preferred_language: editForm.value.preferred_language || undefined,
      region_code: editForm.value.region_code || undefined,
      preferred_currency: editForm.value.preferred_currency || undefined,
      subscription_plan: editForm.value.subscription_plan || undefined,
      subscription_expires_at: editForm.value.subscription_expires_at
        ? new Date(editForm.value.subscription_expires_at).toISOString()
        : null,
      scope_level: editForm.value.scope_level || undefined,
      scope_id: editForm.value.scope_id ? Number(editForm.value.scope_id) : undefined,
      is_active: editForm.value.is_active,
      is_vip: editForm.value.is_vip,
    }

    // Only include person fields if any are filled
    const hasPersonData = editForm.value.person_last_name || editForm.value.person_first_name ||
      editForm.value.person_phone || editForm.value.person_mothers_last_name ||
      editForm.value.person_mothers_first_name || editForm.value.person_birth_place ||
      editForm.value.person_birth_date

    if (hasPersonData) {
      payload.person = {
        last_name: editForm.value.person_last_name || undefined,
        first_name: editForm.value.person_first_name || undefined,
        phone: editForm.value.person_phone || undefined,
        mothers_last_name: editForm.value.person_mothers_last_name || undefined,
        mothers_first_name: editForm.value.person_mothers_first_name || undefined,
        birth_place: editForm.value.person_birth_place || undefined,
        birth_date: editForm.value.person_birth_date
          ? new Date(editForm.value.person_birth_date).toISOString()
          : undefined,
      }
    }

    // Clean undefined values
    Object.keys(payload).forEach(key => {
      if (payload[key] === undefined) delete payload[key]
    })
    if (payload.person) {
      Object.keys(payload.person).forEach(key => {
        if (payload.person[key] === undefined) delete payload.person[key]
      })
      if (Object.keys(payload.person).length === 0) delete payload.person
    }

    const res = await fetch(`/api/v1/admin/users/${userId}`, {
      method: 'PATCH',
      headers,
      body: JSON.stringify(payload),
    })

    if (!res.ok) {
      const errData = await res.json().catch(() => ({}))
      throw new Error(errData.detail || `Save failed: ${res.status}`)
    }

    const result = await res.json()
    user.value = result
    closeEditModal()
    showNotification('success', 'User updated successfully')
  } catch (e: any) {
    showNotification('error', e.message || 'Failed to save')
  } finally {
    saving.value = false
  }
}

// Notification helper
function showNotification(type: 'success' | 'error', message: string) {
  notification.value = { show: true, type, message }
  setTimeout(() => {
    notification.value.show = false
  }, 4000)
}

// Navigation
function goBack() {
  router.push('/users')
}

// Helpers
function getInitials(name: string): string {
  if (!name) return '?'
  return name.split(' ').map(w => w[0]).join('').toUpperCase().slice(0, 2)
}

function getInitialsColor(name: string): string {
  const colors = [
    'bg-red-500', 'bg-yellow-500', 'bg-green-500', 'bg-blue-500',
    'bg-indigo-500', 'bg-purple-500', 'bg-pink-500', 'bg-teal-500',
  ]
  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 formatDate(date: string | null | undefined): string {
  if (!date) return ''
  try {
    return new Date(date).toLocaleDateString('en-GB', {
      year: 'numeric',
      month: 'short',
      day: 'numeric',
    })
  } catch {
    return String(date)
  }
}

function roleLabel(role: string): string {
  const map: Record<string, string> = {
    admin: 'Admin',
    user: 'User',
    staff: 'Staff',
    superadmin: 'Superadmin',
  }
  return map[role?.toLowerCase()] || role || 'User'
}

function roleBadgeClass(role: string): string {
  const map: Record<string, string> = {
    admin: 'bg-purple-500/10 text-purple-400',
    user: 'bg-blue-500/10 text-blue-400',
    staff: 'bg-cyan-500/10 text-cyan-400',
    superadmin: 'bg-amber-500/10 text-amber-400',
  }
  return map[role?.toLowerCase()] || 'bg-slate-500/10 text-slate-400'
}

function planBadgeClass(plan: string): string {
  const map: Record<string, string> = {
    FREE: 'bg-slate-500/10 text-slate-400',
    PREMIUM: 'bg-emerald-500/10 text-emerald-400',
    ENTERPRISE: 'bg-amber-500/10 text-amber-400',
  }
  return map[plan?.toUpperCase()] || 'bg-slate-500/10 text-slate-400'
}

function orgRoleLabel(role: string): string {
  const map: Record<string, string> = {
    admin: 'Admin',
    manager: 'Manager',
    member: 'Member',
    owner: 'Owner',
  }
  return map[role?.toLowerCase()] || role || 'Member'
}

function memberStatusLabel(status: string): string {
  const map: Record<string, string> = {
    active: 'Active',
    invited: 'Invited',
    suspended: 'Suspended',
    inactive: 'Inactive',
  }
  return map[status?.toLowerCase()] || status || 'Unknown'
}

function memberStatusBadgeClass(status: string): string {
  const map: Record<string, string> = {
    active: 'bg-emerald-500/10 text-emerald-400',
    invited: 'bg-blue-500/10 text-blue-400',
    suspended: 'bg-red-500/10 text-red-400',
    inactive: 'bg-slate-500/10 text-slate-400',
  }
  return map[status?.toLowerCase()] || 'bg-slate-500/10 text-slate-400'
}

function memberStatusDotClass(status: string): string {
  const map: Record<string, string> = {
    active: 'bg-emerald-400',
    invited: 'bg-blue-400',
    suspended: 'bg-red-400',
    inactive: 'bg-slate-400',
  }
  return map[status?.toLowerCase()] || 'bg-slate-400'
}

// Lifecycle
onMounted(() => {
  fetchUser()
})
</script>
