<template>
  <div class="relative min-h-screen text-white">
    <!-- Background Image -->
    <div class="fixed inset-0 z-0">
      <div class="absolute inset-0 bg-[url('@/assets/garage-bg.png')] bg-cover bg-center bg-fixed"></div>
    </div>

    <!-- Header (modular) -->
    <BaseHeader>
      <template #left>
        <HeaderLogo to="/dashboard" />
      </template>
      <template #center>
        <span class="text-sm font-semibold text-white/70 tracking-wide">
          {{ t('profile.title') }}
        </span>
      </template>
      <template #right>
        <HeaderCompanySwitcher />
        <HeaderProfile />
      </template>
    </BaseHeader>

    <!-- ── Backdrop overlay: click outside the card closes the profile ── -->
    <div
      class="fixed inset-0 z-10 bg-black/30 backdrop-blur-[2px]"
      @click="closeProfile"
    >
      <!-- Content (card) — @click.stop prevents backdrop click from propagating -->
      <div
        @click.stop
        class="relative mx-auto max-w-4xl px-4 py-8 sm:px-6 lg:px-8 overflow-y-auto max-h-screen"
      >
      <!-- ── Loading Spinner ──────────────────────────────────────────── -->
      <div
        v-if="isPageLoading"
        class="flex flex-col items-center justify-center py-24"
      >
        <div class="flex h-16 w-16 items-center justify-center rounded-full bg-[#00E5A0]/10 mb-4">
          <svg class="h-8 w-8 animate-spin text-[#00E5A0]" 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>
        <p class="text-white/60 text-sm">{{ t('profile.loading') }}</p>
      </div>

      <!-- ── Profile Content (shown when not loading) ─────────────────── -->
      <template v-if="!isPageLoading">

        <!-- ════════════════════════════════════════════════════════════════ -->
        <!-- ── PROGRESS BAR ─────────────────────────────────────────────── -->
        <!-- ════════════════════════════════════════════════════════════════ -->
        <div class="mb-6 rounded-2xl border border-white/10 bg-black/40 p-5 backdrop-blur-xl shadow-xl shadow-black/20">
          <div class="flex items-center justify-between mb-2">
            <span class="text-sm font-medium text-white/70">{{ t('profile.completion') }}</span>
            <span class="text-sm font-bold text-[#00E5A0]">{{ profileCompletionPercentage }}%</span>
          </div>
          <div class="h-2.5 w-full overflow-hidden rounded-full bg-white/10">
            <div
              class="h-full rounded-full transition-all duration-700 ease-out"
              :class="progressBarColorClass"
              :style="{ width: profileCompletionPercentage + '%' }"
            ></div>
          </div>
        </div>

        <!-- ════════════════════════════════════════════════════════════════ -->
        <!-- ── ACCOUNT INFO CARD (Email + Phone + Password) ─────────────── -->
        <!-- ════════════════════════════════════════════════════════════════ -->
        <div
          class="relative mb-6 rounded-2xl border border-white/10 bg-black/40 p-6 backdrop-blur-xl shadow-xl shadow-black/20"
        >
          <!-- Close (X) Button -->
          <button
            type="button"
            @click="router.push('/dashboard')"
            class="absolute right-4 top-4 text-white/40 transition-colors duration-200 hover:text-red-400 cursor-pointer"
            :aria-label="t('header.close')"
          >
            <svg
              class="h-6 w-6"
              xmlns="http://www.w3.org/2000/svg"
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              stroke-width="2"
              stroke-linecap="round"
              stroke-linejoin="round"
            >
              <line x1="18" y1="6" x2="6" y2="18" />
              <line x1="6" y1="6" x2="18" y2="18" />
            </svg>
          </button>

          <div class="flex items-center gap-3 mb-6">
            <svg class="w-6 h-6 text-[#00E5A0]" 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>
            <h2 class="text-xl font-bold text-white">{{ t('profile.accountInfo') }}</h2>
          </div>

          <!-- Email + Phone side-by-side -->
          <div class="grid grid-cols-1 gap-4 sm:grid-cols-2 mb-4">
            <div>
              <label class="mb-2 block text-sm text-white/50">{{ t('profile.email') }}</label>
              <div class="w-full rounded-xl border border-white/10 bg-white/5 px-4 py-3 text-white font-medium select-none">
                {{ authStore.user?.email || '—' }}
              </div>
            </div>
            <div>
              <label class="mb-2 block text-sm text-white/50">{{ t('profile.phone') }}</label>
              <input
                v-if="isEditing"
                v-model="editForm.phone"
                class="w-full rounded-xl border border-white/10 bg-white/5 px-4 py-3 text-white font-medium placeholder-white/30 backdrop-blur-sm focus:border-[#00E5A0]/50 focus:outline-none"
                placeholder="+36 20 123 4567"
              />
              <div v-else class="w-full rounded-xl border border-white/10 bg-white/5 px-4 py-3 text-white font-medium">
                {{ person?.phone || '—' }}
              </div>
            </div>
          </div>

          <!-- Action Buttons Row -->
          <div class="flex flex-wrap items-center gap-3">
            <!-- ── Left side: Edit / (Cancel + Save) ── -->
            <template v-if="!isEditing">
              <button
                @click="startEditing"
                class="inline-flex items-center gap-2 rounded-xl border border-[#00E5A0]/40 bg-[#00E5A0]/10 px-4 py-2.5 text-sm font-semibold text-[#00E5A0] transition-all duration-200 hover:bg-[#00E5A0]/20 cursor-pointer"
              >
                <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('profile.edit') }}
              </button>
            </template>
            <template v-else>
              <button
                @click="cancelEditing"
                class="inline-flex items-center gap-2 rounded-xl border border-white/20 bg-white/5 px-4 py-2.5 text-sm font-semibold text-white/70 transition-all duration-200 hover:bg-white/10 cursor-pointer"
              >
                <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="M6 18L18 6M6 6l12 12" />
                </svg>
                {{ t('profile.cancel') }}
              </button>
              <button
                @click="savePerson"
                :disabled="isSaving"
                class="inline-flex items-center gap-2 rounded-xl bg-[#00E5A0] px-4 py-2.5 text-sm font-semibold text-black transition-all duration-200 hover:bg-[#00E5A0]/90 disabled:opacity-50 cursor-pointer"
              >
                <svg v-if="isSaving" 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>
                <svg v-else 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="M5 13l4 4L19 7" />
                </svg>
                {{ t('profile.save') }}
              </button>
            </template>

            <!-- ── Right side: Change Password ── -->
            <button
              @click="showPasswordModal = true"
              class="ml-auto inline-flex items-center gap-2 rounded-xl bg-[#00E5A0] px-6 py-2.5 text-sm font-semibold text-black transition-all duration-200 hover:bg-[#00E5A0]/90 cursor-pointer"
            >
              <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="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" />
              </svg>
              {{ t('profile.changePassword') }}
            </button>
          </div>
        </div>

        <!-- ════════════════════════════════════════════════════════════════ -->
        <!-- ── TAB NAVIGATION ───────────────────────────────────────────── -->
        <!-- ════════════════════════════════════════════════════════════════ -->
        <div
          class="rounded-2xl border border-white/10 bg-black/40 backdrop-blur-xl shadow-xl shadow-black/20 overflow-hidden"
        >
          <!-- Tab Buttons -->
          <div class="flex border-b border-white/10">
            <button
              v-for="tab in tabs"
              :key="tab.key"
              @click="activeTab = tab.key"
              class="flex-1 px-4 py-3.5 text-sm font-semibold transition-all duration-200 cursor-pointer relative"
              :class="activeTab === tab.key
                ? 'text-[#00E5A0]'
                : 'text-white/50 hover:text-white/80'"
            >
              {{ tab.label }}
              <span
                v-if="activeTab === tab.key"
                class="absolute bottom-0 left-0 right-0 h-0.5 bg-[#00E5A0]"
              ></span>
            </button>
          </div>

          <!-- ── Tab Content ──────────────────────────────────────────── -->
          <div class="p-6">

            <!-- ══════════════════════════════════════════════════════════ -->
            <!-- TAB 1: SZEMÉLYES ÉS LAKCÍM                                -->
            <!-- ══════════════════════════════════════════════════════════ -->
            <div v-if="activeTab === 'personal'">

              <!-- ── KYC Personal Data ── -->
              <div class="mb-6">
                <h3 class="text-sm font-semibold text-white/70 mb-4">{{ t('profile.personalData') }}</h3>
                <div class="grid grid-cols-1 gap-4 mb-4 sm:grid-cols-2">
                  <div>
                    <label class="mb-2 block text-sm text-white/50">{{ t('profile.lastName') }}</label>
                    <input
                      v-if="isEditing"
                      v-model="editForm.last_name"
                      class="w-full rounded-xl border border-white/10 bg-white/5 px-4 py-3 text-white font-medium placeholder-white/30 backdrop-blur-sm focus:border-[#00E5A0]/50 focus:outline-none"
                      :placeholder="t('profile.lastName')"
                    />
                    <div v-else class="w-full rounded-xl border border-white/10 bg-white/5 px-4 py-3 text-white font-medium">
                      {{ person?.last_name || '—' }}
                    </div>
                  </div>
                  <div>
                    <label class="mb-2 block text-sm text-white/50">{{ t('profile.firstName') }}</label>
                    <input
                      v-if="isEditing"
                      v-model="editForm.first_name"
                      class="w-full rounded-xl border border-white/10 bg-white/5 px-4 py-3 text-white font-medium placeholder-white/30 backdrop-blur-sm focus:border-[#00E5A0]/50 focus:outline-none"
                      :placeholder="t('profile.firstName')"
                    />
                    <div v-else class="w-full rounded-xl border border-white/10 bg-white/5 px-4 py-3 text-white font-medium">
                      {{ person?.first_name || '—' }}
                    </div>
                  </div>
                </div>

                <div class="grid grid-cols-1 gap-4 mb-4 sm:grid-cols-2">
                  <div>
                    <label class="mb-2 block text-sm text-white/50">{{ t('profile.birthPlace') }}</label>
                    <input
                      v-if="isEditing"
                      v-model="editForm.birth_place"
                      class="w-full rounded-xl border border-white/10 bg-white/5 px-4 py-3 text-white font-medium placeholder-white/30 backdrop-blur-sm focus:border-[#00E5A0]/50 focus:outline-none"
                      :placeholder="t('profile.birthPlace')"
                    />
                    <div v-else class="w-full rounded-xl border border-white/10 bg-white/5 px-4 py-3 text-white font-medium">
                      {{ person?.birth_place || '—' }}
                    </div>
                  </div>
                  <div>
                    <label class="mb-2 block text-sm text-white/50">{{ t('profile.birthDate') }}</label>
                    <input
                      v-if="isEditing"
                      v-model="editForm.birth_date"
                      type="date"
                      class="w-full rounded-xl border border-white/10 bg-white/5 px-4 py-3 text-white font-medium placeholder-white/30 backdrop-blur-sm focus:border-[#00E5A0]/50 focus:outline-none"
                    />
                    <div v-else class="w-full rounded-xl border border-white/10 bg-white/5 px-4 py-3 text-white font-medium">
                      {{ formatDate(person?.birth_date) || '—' }}
                    </div>
                  </div>
                </div>

                <div class="grid grid-cols-1 gap-4 mb-4 sm:grid-cols-2">
                  <div>
                    <label class="mb-2 block text-sm text-white/50">{{ t('profile.mothersLastName') }}</label>
                    <input
                      v-if="isEditing"
                      v-model="editForm.mothers_last_name"
                      class="w-full rounded-xl border border-white/10 bg-white/5 px-4 py-3 text-white font-medium placeholder-white/30 backdrop-blur-sm focus:border-[#00E5A0]/50 focus:outline-none"
                      :placeholder="t('profile.mothersLastName')"
                    />
                    <div v-else class="w-full rounded-xl border border-white/10 bg-white/5 px-4 py-3 text-white font-medium">
                      {{ person?.mothers_last_name || '—' }}
                    </div>
                  </div>
                  <div>
                    <label class="mb-2 block text-sm text-white/50">{{ t('profile.mothersFirstName') }}</label>
                    <input
                      v-if="isEditing"
                      v-model="editForm.mothers_first_name"
                      class="w-full rounded-xl border border-white/10 bg-white/5 px-4 py-3 text-white font-medium placeholder-white/30 backdrop-blur-sm focus:border-[#00E5A0]/50 focus:outline-none"
                      :placeholder="t('profile.mothersFirstName')"
                    />
                    <div v-else class="w-full rounded-xl border border-white/10 bg-white/5 px-4 py-3 text-white font-medium">
                      {{ person?.mothers_first_name || '—' }}
                    </div>
                  </div>
                </div>
              </div>

              <!-- ── Address Section (GlassCard + AddressDisplay) ── -->
              <GlassCard variant="standard" padding="md" customClass="mb-6">
                <template #default>
                  <h3 class="text-sm font-semibold text-white/70 mb-3">{{ t('profile.addressTitle') }}</h3>

                  <div v-if="isEditing" class="space-y-3">
                    <div class="grid grid-cols-1 gap-3 sm:grid-cols-2">
                      <div>
                        <label class="mb-1 block text-xs text-white/50">{{ t('profile.zipCode') }}</label>
                        <input
                          v-model="editForm.address_zip"
                          class="w-full rounded-xl border border-white/10 bg-white/5 px-4 py-2.5 text-sm text-white font-medium placeholder-white/30 backdrop-blur-sm focus:border-[#00E5A0]/50 focus:outline-none"
                          :placeholder="t('profile.zipCode')"
                        />
                      </div>
                      <div>
                        <label class="mb-1 block text-xs text-white/50">{{ t('profile.city') }}</label>
                        <input
                          v-model="editForm.address_city"
                          class="w-full rounded-xl border border-white/10 bg-white/5 px-4 py-2.5 text-sm text-white font-medium placeholder-white/30 backdrop-blur-sm focus:border-[#00E5A0]/50 focus:outline-none"
                          :placeholder="t('profile.city')"
                        />
                      </div>
                    </div>
                    <div class="grid grid-cols-1 gap-3 sm:grid-cols-3">
                      <div>
                        <label class="mb-1 block text-xs text-white/50">{{ t('profile.street') }}</label>
                        <input
                          v-model="editForm.address_street_name"
                          class="w-full rounded-xl border border-white/10 bg-white/5 px-4 py-2.5 text-sm text-white font-medium placeholder-white/30 backdrop-blur-sm focus:border-[#00E5A0]/50 focus:outline-none"
                          :placeholder="t('profile.street')"
                        />
                      </div>
                      <div>
                        <label class="mb-1 block text-xs text-white/50">{{ t('profile.streetType') }}</label>
                        <select
                          v-model="editForm.address_street_type"
                          class="w-full rounded-xl border border-white/10 bg-white/5 px-4 py-2.5 text-sm text-white font-medium backdrop-blur-sm focus:border-[#00E5A0]/50 focus:outline-none appearance-none cursor-pointer"
                        >
                          <option value="" disabled class="bg-gray-900 text-white/50">{{ t('profile.selectPlaceholder') }}</option>
                          <option
                            v-for="st in streetTypes"
                            :key="st.value"
                            :value="st.value"
                            class="bg-gray-900 text-white"
                          >{{ st.label }}</option>
                        </select>
                      </div>
                      <div>
                        <label class="mb-1 block text-xs text-white/50">{{ t('profile.houseNumber') }}</label>
                        <input
                          v-model="editForm.address_house_number"
                          class="w-full rounded-xl border border-white/10 bg-white/5 px-4 py-2.5 text-sm text-white font-medium placeholder-white/30 backdrop-blur-sm focus:border-[#00E5A0]/50 focus:outline-none"
                          :placeholder="t('profile.houseNumber')"
                        />
                      </div>
                    </div>
                    <div class="grid grid-cols-1 gap-3 sm:grid-cols-4">
                      <div>
                        <label class="mb-1 block text-xs text-white/50">{{ t('profile.stairwell') }}</label>
                        <input
                          v-model="editForm.address_stairwell"
                          class="w-full rounded-xl border border-white/10 bg-white/5 px-4 py-2.5 text-sm text-white font-medium placeholder-white/30 backdrop-blur-sm focus:border-[#00E5A0]/50 focus:outline-none"
                          :placeholder="t('profile.stairwell')"
                        />
                      </div>
                      <div>
                        <label class="mb-1 block text-xs text-white/50">{{ t('profile.floor') }}</label>
                        <input
                          v-model="editForm.address_floor"
                          class="w-full rounded-xl border border-white/10 bg-white/5 px-4 py-2.5 text-sm text-white font-medium placeholder-white/30 backdrop-blur-sm focus:border-[#00E5A0]/50 focus:outline-none"
                          :placeholder="t('profile.floor')"
                        />
                      </div>
                      <div>
                        <label class="mb-1 block text-xs text-white/50">{{ t('profile.door') }}</label>
                        <input
                          v-model="editForm.address_door"
                          class="w-full rounded-xl border border-white/10 bg-white/5 px-4 py-2.5 text-sm text-white font-medium placeholder-white/30 backdrop-blur-sm focus:border-[#00E5A0]/50 focus:outline-none"
                          :placeholder="t('profile.door')"
                        />
                      </div>
                      <div>
                        <label class="mb-1 block text-xs text-white/50">{{ t('profile.parcelId') }}</label>
                        <input
                          v-model="editForm.address_hrsz"
                          class="w-full rounded-xl border border-white/10 bg-white/5 px-4 py-2.5 text-sm text-white font-medium placeholder-white/30 backdrop-blur-sm focus:border-[#00E5A0]/50 focus:outline-none"
                          :placeholder="t('profile.hrsz')"
                        />
                      </div>
                    </div>
                  </div>

                  <!-- ── Read-only address display with AddressDisplay ── -->
                  <div v-else class="space-y-2">
                    <AddressDisplay
                      :zip="person?.address?.address_zip"
                      :city="person?.address?.address_city"
                      :street_name="person?.address?.address_street_name"
                      :street_type="person?.address?.address_street_type"
                      :house_number="person?.address?.address_house_number"
                      text-class="text-white font-medium"
                    />
                    <p
                      v-if="person?.address?.address_stairwell || person?.address?.address_floor || person?.address?.address_door || person?.address?.address_hrsz"
                      class="text-xs text-white/50 ml-6"
                    >
                      {{ t('address.stairwell', { value: person?.address?.address_stairwell || '—' }) }}, {{ t('address.floor', { value: person?.address?.address_floor || '—' }) }}, {{ t('address.door', { value: person?.address?.address_door || '—' }) }}
                      <template v-if="person?.address?.address_hrsz">, {{ t('address.hrsz', { value: person?.address?.address_hrsz }) }}</template>
                    </p>
                  </div>
                </template>
              </GlassCard>
            </div>

            <!-- ══════════════════════════════════════════════════════════ -->
            <!-- TAB 2: OKMÁNYOK ÉS VÉSZHELYZET                             -->
            <!-- ══════════════════════════════════════════════════════════ -->
            <div v-if="activeTab === 'docs'">
              <!-- ── Identity Docs Section ── -->
              <div class="mb-6 p-4 rounded-xl border border-white/[0.06] bg-white/[0.03]">
                <h3 class="text-sm font-semibold text-white/70 mb-3">{{ t('profile.identityDocs') }}</h3>

                <div v-if="isEditing" class="space-y-3">
                  <!-- ID Card -->
                  <div class="rounded-lg border border-white/[0.06] bg-white/[0.02] p-3">
                    <h4 class="text-xs font-semibold text-white/60 mb-2 uppercase tracking-wider">{{ t('profile.idCard') }}</h4>
                    <div class="grid grid-cols-1 gap-3 sm:grid-cols-2">
                      <div>
                        <label class="mb-1 block text-xs text-white/50">{{ t('profile.docNumber') }}</label>
                        <input
                          v-model="editForm.id_card_number"
                          class="w-full rounded-xl border border-white/10 bg-white/5 px-4 py-2.5 text-sm text-white font-medium placeholder-white/30 backdrop-blur-sm focus:border-[#00E5A0]/50 focus:outline-none"
                          :placeholder="t('profile.docNumber')"
                        />
                      </div>
                      <div>
                        <label class="mb-1 block text-xs text-white/50">{{ t('profile.docExpiry') }}</label>
                        <input
                          v-model="editForm.id_card_expiry"
                          type="date"
                          class="w-full rounded-xl border border-white/10 bg-white/5 px-4 py-2.5 text-sm text-white font-medium placeholder-white/30 backdrop-blur-sm focus:border-[#00E5A0]/50 focus:outline-none"
                        />
                      </div>
                    </div>
                  </div>

                  <!-- Driving License -->
                  <div class="rounded-lg border border-white/[0.06] bg-white/[0.02] p-3">
                    <h4 class="text-xs font-semibold text-white/60 mb-2 uppercase tracking-wider">{{ t('profile.drivingLicense') }}</h4>
                    <div class="grid grid-cols-1 gap-3 sm:grid-cols-2">
                      <div>
                        <label class="mb-1 block text-xs text-white/50">{{ t('profile.docNumber') }}</label>
                        <input
                          v-model="editForm.license_number"
                          class="w-full rounded-xl border border-white/10 bg-white/5 px-4 py-2.5 text-sm text-white font-medium placeholder-white/30 backdrop-blur-sm focus:border-[#00E5A0]/50 focus:outline-none"
                          :placeholder="t('profile.docNumber')"
                        />
                      </div>
                      <div>
                        <label class="mb-1 block text-xs text-white/50">{{ t('profile.docExpiry') }}</label>
                        <input
                          v-model="editForm.license_expiry"
                          type="date"
                          class="w-full rounded-xl border border-white/10 bg-white/5 px-4 py-2.5 text-sm text-white font-medium placeholder-white/30 backdrop-blur-sm focus:border-[#00E5A0]/50 focus:outline-none"
                        />
                      </div>
                    </div>
                    <div class="mt-3">
                      <label class="mb-1 block text-xs text-white/50">{{ t('profile.categories') }}</label>
                      <input
                        v-model="editForm.license_categories"
                        class="w-full rounded-xl border border-white/10 bg-white/5 px-4 py-2.5 text-sm text-white font-medium placeholder-white/30 backdrop-blur-sm focus:border-[#00E5A0]/50 focus:outline-none"
                        :placeholder="t('profile.categories')"
                      />
                    </div>
                  </div>
                </div>

                <div v-else class="space-y-3">
                  <!-- ID Card (read-only) -->
                  <div class="rounded-lg border border-white/[0.06] bg-white/[0.02] p-3">
                    <h4 class="text-xs font-semibold text-white/60 mb-2 uppercase tracking-wider">{{ t('profile.idCard') }}</h4>
                    <div class="grid grid-cols-2 gap-4 text-sm">
                      <div>
                        <span class="text-white/50">{{ t('profile.number') }}</span>
                        <span class="ml-2 text-white font-medium">{{ identityDocs?.ID_CARD?.number || '—' }}</span>
                      </div>
                      <div>
                        <span class="text-white/50">{{ t('profile.expiry') }}</span>
                        <span class="ml-2 text-white font-medium">{{ formatDate(identityDocs?.ID_CARD?.expiry_date) || '—' }}</span>
                      </div>
                    </div>
                  </div>

                  <!-- Driving License (read-only) -->
                  <div class="rounded-lg border border-white/[0.06] bg-white/[0.02] p-3">
                    <h4 class="text-xs font-semibold text-white/60 mb-2 uppercase tracking-wider">{{ t('profile.drivingLicense') }}</h4>
                    <div class="grid grid-cols-2 gap-4 text-sm">
                      <div>
                        <span class="text-white/50">{{ t('profile.number') }}</span>
                        <span class="ml-2 text-white font-medium">{{ identityDocs?.LICENSE?.number || '—' }}</span>
                      </div>
                      <div>
                        <span class="text-white/50">{{ t('profile.expiry') }}</span>
                        <span class="ml-2 text-white font-medium">{{ formatDate(identityDocs?.LICENSE?.expiry_date) || '—' }}</span>
                      </div>
                    </div>
                    <div class="mt-2 text-sm">
                      <span class="text-white/50">{{ t('profile.categoriesLabel') }}</span>
                      <span class="ml-2 text-white font-medium">{{ identityDocs?.LICENSE?.categories || '—' }}</span>
                    </div>
                  </div>
                </div>
              </div>

              <!-- ── ICE Contact Section ── -->
              <div class="p-4 rounded-xl border border-white/[0.06] bg-white/[0.03]">
                <h3 class="text-sm font-semibold text-white/70 mb-3">{{ t('profile.iceTitle') }}</h3>

                <div v-if="isEditing" class="space-y-3">
                  <div class="grid grid-cols-1 gap-3 sm:grid-cols-2">
                    <div>
                      <label class="mb-1 block text-xs text-white/50">{{ t('profile.iceName') }}</label>
                      <input
                        v-model="editForm.ice_name"
                        class="w-full rounded-xl border border-white/10 bg-white/5 px-4 py-2.5 text-sm text-white font-medium placeholder-white/30 backdrop-blur-sm focus:border-[#00E5A0]/50 focus:outline-none"
                        :placeholder="t('profile.iceName')"
                      />
                    </div>
                    <div>
                      <label class="mb-1 block text-xs text-white/50">{{ t('profile.iceRelation') }}</label>
                      <input
                        v-model="editForm.ice_relation"
                        class="w-full rounded-xl border border-white/10 bg-white/5 px-4 py-2.5 text-sm text-white font-medium placeholder-white/30 backdrop-blur-sm focus:border-[#00E5A0]/50 focus:outline-none"
                        :placeholder="t('profile.iceRelation')"
                      />
                    </div>
                  </div>
                  <div class="grid grid-cols-1 gap-3 sm:grid-cols-2">
                    <div>
                      <label class="mb-1 block text-xs text-white/50">{{ t('profile.icePhone') }}</label>
                      <input
                        v-model="editForm.ice_phone"
                        class="w-full rounded-xl border border-white/10 bg-white/5 px-4 py-2.5 text-sm text-white font-medium placeholder-white/30 backdrop-blur-sm focus:border-[#00E5A0]/50 focus:outline-none"
                        placeholder="+36 20 123 4567"
                      />
                    </div>
                    <div>
                      <label class="mb-1 block text-xs text-white/50">{{ t('profile.iceEmail') }}</label>
                      <input
                        v-model="editForm.ice_email"
                        type="email"
                        class="w-full rounded-xl border border-white/10 bg-white/5 px-4 py-2.5 text-sm text-white font-medium placeholder-white/30 backdrop-blur-sm focus:border-[#00E5A0]/50 focus:outline-none"
                        placeholder="email@example.com"
                      />
                    </div>
                  </div>
                </div>

                <div v-else class="space-y-2 text-sm">
                  <p>
                    <span class="text-white/50">{{ t('profile.iceNameLabel') }}</span>
                    <span class="ml-2 text-white font-medium">{{ iceContact?.name || '—' }}</span>
                  </p>
                  <p>
                    <span class="text-white/50">{{ t('profile.iceRelationLabel') }}</span>
                    <span class="ml-2 text-white font-medium">{{ iceContact?.relation || '—' }}</span>
                  </p>
                  <p>
                    <span class="text-white/50">{{ t('profile.icePhoneLabel') }}</span>
                    <span class="ml-2 text-white font-medium">{{ iceContact?.phone || '—' }}</span>
                  </p>
                  <p>
                    <span class="text-white/50">{{ t('profile.iceEmailLabel') }}</span>
                    <span class="ml-2 text-white font-medium">{{ iceContact?.email || '—' }}</span>
                  </p>
                </div>
              </div>
            </div>

            <!-- ══════════════════════════════════════════════════════════ -->
            <!-- TAB 3: TERÜLETI BEÁLLÍTÁSOK (REGIONAL)                    -->
            <!-- ══════════════════════════════════════════════════════════ -->
            <div v-if="activeTab === 'regional'">
              <div class="rounded-2xl border border-white/10 bg-black/30 backdrop-blur-xl p-6 shadow-xl shadow-black/20">
                <h3 class="text-sm font-semibold text-white/70 mb-6">{{ t('profile.tabRegional') }}</h3>

                <div class="space-y-5">
                  <!-- Language Select -->
                  <div>
                    <label class="mb-2 block text-sm text-white/50">{{ t('profile.regionalLanguage') }}</label>
                    <select
                      v-model="regionalSettings.language"
                      @change="onLanguageChange"
                      class="w-full rounded-xl border border-white/10 bg-white/5 px-4 py-3 text-white font-medium backdrop-blur-sm focus:border-[#00E5A0]/50 focus:outline-none appearance-none cursor-pointer"
                    >
                      <option value="hu" class="bg-gray-900 text-white">Magyar (HU)</option>
                      <option value="en" class="bg-gray-900 text-white">English (EN)</option>
                    </select>
                  </div>

                  <!-- Date Format Select -->
                  <div>
                    <label class="mb-2 block text-sm text-white/50">{{ t('profile.regionalDateFormat') }}</label>
                    <select
                      v-model="regionalSettings.dateFormat"
                      class="w-full rounded-xl border border-white/10 bg-white/5 px-4 py-3 text-white font-medium backdrop-blur-sm focus:border-[#00E5A0]/50 focus:outline-none appearance-none cursor-pointer"
                    >
                      <option value="hu" class="bg-gray-900 text-white">{{ t('profile.dateFormatHU') }}</option>
                      <option value="iso" class="bg-gray-900 text-white">{{ t('profile.dateFormatISO') }}</option>
                    </select>
                  </div>

                  <!-- Currency Select -->
                  <div>
                    <label class="mb-2 block text-sm text-white/50">{{ t('profile.regionalCurrency') }}</label>
                    <select
                      v-model="regionalSettings.currency"
                      class="w-full rounded-xl border border-white/10 bg-white/5 px-4 py-3 text-white font-medium backdrop-blur-sm focus:border-[#00E5A0]/50 focus:outline-none appearance-none cursor-pointer"
                    >
                      <option value="HUF" class="bg-gray-900 text-white">{{ t('profile.currencyHUF') }}</option>
                      <option value="EUR" class="bg-gray-900 text-white">{{ t('profile.currencyEUR') }}</option>
                      <option value="USD" class="bg-gray-900 text-white">{{ t('profile.currencyUSD') }}</option>
                    </select>
                  </div>
                </div>
              </div>
            </div>

          </div><!-- /tab-content -->

          <!-- ── Bottom Action Bar (always visible) ────────────────────── -->
          <div class="border-t border-white/10 px-6 py-4 flex items-center justify-between gap-4">
            <!-- Success / Error message -->
            <div
              v-if="saveMessage"
              class="flex-1 rounded-xl px-4 py-2.5 text-sm"
              :class="saveMessageType === 'success' ? 'bg-green-500/10 text-green-400 border border-green-500/20' : 'bg-red-500/10 text-red-400 border border-red-500/20'"
            >
              {{ saveMessage }}
            </div>
            <div v-else class="flex-1"></div>

            <!-- Bottom Cancel + Save (duplicate, only in edit mode) -->
            <template v-if="isEditing">
              <button
                @click="cancelEditing"
                class="inline-flex items-center gap-2 rounded-xl border border-white/20 bg-white/5 px-4 py-2.5 text-sm font-semibold text-white/70 transition-all duration-200 hover:bg-white/10 cursor-pointer shrink-0"
              >
                <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="M6 18L18 6M6 6l12 12" />
                </svg>
                {{ t('profile.cancel') }}
              </button>
              <button
                @click="savePerson"
                :disabled="isSaving"
                class="inline-flex items-center gap-2 rounded-xl bg-[#00E5A0] px-6 py-2.5 text-sm text-black font-semibold transition-all duration-200 hover:bg-[#00E5A0]/90 disabled:opacity-50 cursor-pointer shrink-0"
              >
                <svg v-if="isSaving" 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>
                <svg v-else 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="M5 13l4 4L19 7" />
                </svg>
                {{ t('profile.save') }}
              </button>
            </template>
          </div>
        </div>

        <!-- ── 🩻 DIAGNOSTIC JSON DUMP ──────────────────────────────────── -->
        <div class="rounded-2xl border border-white/10 bg-black/40 p-4 mt-6 backdrop-blur-xl shadow-xl shadow-black/20">
          <details>
            <summary class="text-xs font-semibold text-[#00E5A0] cursor-pointer select-none mb-2">{{ t('profile.xray') }}</summary>
            <pre class="text-xs text-green-400 bg-black p-4 mt-2 overflow-auto rounded-lg max-h-64">{{ JSON.stringify(authStore.user?.person, null, 2) }}</pre>
          </details>
        </div>

        <!-- ── Back to Garage Button ─────────────────────────────────────── -->
        <div class="mt-8 text-center">
          <button
            @click="router.push('/dashboard')"
            class="inline-flex items-center gap-2 rounded-xl border border-white/[0.12] bg-white/[0.04] px-6 py-3 text-white/70 transition-all duration-200 hover:border-[#00E5A0]/40 hover:text-white hover:bg-white/[0.08] backdrop-blur-sm cursor-pointer"
          >
            <svg
              class="h-5 w-5"
              xmlns="http://www.w3.org/2000/svg"
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              stroke-width="2"
              stroke-linecap="round"
              stroke-linejoin="round"
            >
              <line x1="19" y1="12" x2="5" y2="12" />
              <polyline points="12 19 5 12 12 5" />
            </svg>
            {{ t('profile.backToGarage') }}
          </button>
        </div>
      </template>
    </div><!-- /content card -->

    <!-- ── Change Password Modal ──────────────────────────────────────── -->
    <Teleport to="body">
      <div
        v-if="showPasswordModal"
        class="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm"
        @click.self="closePasswordModal"
      >
        <div
          @click.stop
          class="relative w-full max-w-md mx-4 rounded-2xl border border-white/10 bg-black/80 p-6 backdrop-blur-2xl shadow-2xl"
        >
          <!-- Modal Header -->
          <div class="flex items-center justify-between mb-6">
            <div class="flex items-center gap-3">
              <svg class="w-6 h-6 text-[#00E5A0]" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" />
              </svg>
              <h3 class="text-lg font-bold text-white">{{ t('profile.passwordTitle') }}</h3>
            </div>
            <button
              @click="closePasswordModal"
              class="text-white/40 transition-colors duration-200 hover:text-red-400 cursor-pointer"
              :aria-label="t('header.close')"
            >
              <svg class="h-5 w-5" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                <line x1="18" y1="6" x2="6" y2="18" />
                <line x1="6" y1="6" x2="18" y2="18" />
              </svg>
            </button>
          </div>

          <!-- Modal Body -->
          <div class="space-y-4">
            <div>
              <label class="mb-2 block text-sm text-white/50">{{ t('profile.currentPassword') }}</label>
              <input
                v-model="passwordForm.currentPassword"
                type="password"
                class="w-full rounded-xl border border-white/10 bg-white/5 px-4 py-3 text-white font-medium placeholder-white/30 backdrop-blur-sm focus:border-[#00E5A0]/50 focus:outline-none"
                placeholder="••••••••"
              />
            </div>
            <div>
              <label class="mb-2 block text-sm text-white/50">{{ t('profile.newPassword') }}</label>
              <input
                v-model="passwordForm.newPassword"
                type="password"
                class="w-full rounded-xl border border-white/10 bg-white/5 px-4 py-3 text-white font-medium placeholder-white/30 backdrop-blur-sm focus:border-[#00E5A0]/50 focus:outline-none"
                placeholder="••••••••"
              />
            </div>
            <div>
              <label class="mb-2 block text-sm text-white/50">{{ t('profile.confirmPassword') }}</label>
              <input
                v-model="passwordForm.confirmPassword"
                type="password"
                class="w-full rounded-xl border border-white/10 bg-white/5 px-4 py-3 text-white font-medium placeholder-white/30 backdrop-blur-sm focus:border-[#00E5A0]/50 focus:outline-none"
                placeholder="••••••••"
              />
            </div>

            <!-- Validation error -->
            <div
              v-if="passwordError"
              class="rounded-xl px-4 py-3 text-sm bg-red-500/10 text-red-400 border border-red-500/20"
            >
              {{ passwordError }}
            </div>

            <!-- Success message -->
            <div
              v-if="passwordSuccess"
              class="rounded-xl px-4 py-3 text-sm bg-green-500/10 text-green-400 border border-green-500/20"
            >
              {{ passwordSuccess }}
            </div>
          </div>

          <!-- Modal Footer -->
          <div class="flex justify-end gap-3 mt-6">
            <button
              @click="closePasswordModal"
              class="rounded-xl border border-white/20 bg-white/5 px-4 py-2 text-sm text-white/70 transition-all duration-200 hover:bg-white/10 cursor-pointer"
            >
              {{ t('profile.cancel') }}
            </button>
            <button
              @click="submitPasswordChange"
              :disabled="isPasswordSaving"
              class="inline-flex items-center gap-2 rounded-xl bg-[#00E5A0] px-6 py-2 text-sm text-black font-semibold transition-all duration-200 hover:bg-[#00E5A0]/90 disabled:opacity-50 cursor-pointer"
            >
              <svg v-if="isPasswordSaving" 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('profile.save') }}
            </button>
          </div>
        </div>
      </div>
    </Teleport>
  </div><!-- /backdrop overlay -->
</div><!-- /root -->
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, onMounted, onUnmounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { useAuthStore } from '../stores/auth'
import api from '../api/axios'
import BaseHeader from '../components/layout/BaseHeader.vue'
import HeaderLogo from '../components/header/HeaderLogo.vue'
import HeaderCompanySwitcher from '../components/header/HeaderCompanySwitcher.vue'
import HeaderProfile from '../components/header/HeaderProfile.vue'
import GlassCard from '../components/ui/GlassCard.vue'
import AddressDisplay from '../components/ui/AddressDisplay.vue'

const router = useRouter()
const { t, locale } = useI18n()
const authStore = useAuthStore()

// ── Page-level loading state ──────────────────────────────────────────
const isPageLoading = ref(true)

// ── Computed helpers ──────────────────────────────────────────────────
const person = computed(() => authStore.user?.person ?? null)
const identityDocs = computed(() => person.value?.identity_docs ?? null)
const iceContact = computed(() => person.value?.ice_contact ?? null)
const isCityLoading = ref(false)

// ── Tab state ─────────────────────────────────────────────────────────
const tabs = [
  { key: 'personal', label: t('profile.tabPersonal') },
  { key: 'docs', label: t('profile.tabDocs') },
  { key: 'regional', label: t('profile.tabRegional') },
]
const activeTab = ref('personal')

// ── Read ?tab=regional from query on mount ────────────────────────────
const route = useRoute()
watch(
  () => route.query.tab,
  (tab) => {
    if (tab === 'regional') {
      activeTab.value = 'regional'
    }
  },
  { immediate: true }
)

// ── Street types for the dropdown ─────────────────────────────────────
const streetTypes = [
  { value: 'utca', label: 'utca' },
  { value: 'út', label: 'út' },
  { value: 'tér', label: 'tér' },
  { value: 'köz', label: 'köz' },
  { value: 'körút', label: 'körút' },
  { value: 'sugárút', label: 'sugárút' },
  { value: 'sétány', label: 'sétány' },
  { value: 'liget', label: 'liget' },
  { value: 'park', label: 'park' },
  { value: 'rakpart', label: 'rakpart' },
  { value: 'fasor', label: 'fasor' },
  { value: 'dűlő', label: 'dűlő' },
  { value: 'major', label: 'major' },
  { value: 'telep', label: 'telep' },
  { value: 'lépcső', label: 'lépcső' },
]

// ── Profile Completion Percentage ─────────────────────────────────────
const profileCompletionPercentage = computed(() => {
  const p = person.value
  if (!p) return 0

  let total = 0
  let filled = 0

  // Names (2)
  total += 2
  if (p.first_name) filled++
  if (p.last_name) filled++

  // Phone (1)
  total += 1
  if (p.phone) filled++

  // Birth data (3: place, date, mother's names count as 2)
  total += 3
  if (p.birth_place) filled++
  if (p.birth_date) filled++
  if (p.mothers_last_name && p.mothers_first_name) filled++

  // Full address (7 fields: zip, city, street_name, street_type, house_number, floor, door)
  total += 7
  if (p?.address?.address_zip) filled++
  if (p?.address?.address_city) filled++
  if (p?.address?.address_street_name) filled++
  if (p?.address?.address_street_type) filled++
  if (p?.address?.address_house_number) filled++
  if (p?.address?.address_floor) filled++
  if (p?.address?.address_door) filled++

  // Identity docs (2: ID_CARD number, LICENSE number)
  const docs = p.identity_docs
  total += 2
  if (docs?.ID_CARD?.number) filled++
  if (docs?.LICENSE?.number) filled++

  // ICE contact (4 fields)
  const ice = p.ice_contact
  total += 4
  if (ice?.name) filled++
  if (ice?.relation) filled++
  if (ice?.phone) filled++
  if (ice?.email) filled++

  return Math.round((filled / total) * 100)
})

const progressBarColorClass = computed(() => {
  const pct = profileCompletionPercentage.value
  if (pct < 30) return 'bg-red-500'
  if (pct < 60) return 'bg-yellow-500'
  if (pct < 85) return 'bg-blue-500'
  return 'bg-[#00E5A0]'
})

// ── Close profile and go back to dashboard ──────────────────────────
function closeProfile() {
  router.push('/dashboard')
}

// ── Force-fetch fresh profile data on mount ───────────────────────────
onMounted(async () => {
  try {
    await authStore.fetchUser()
  } catch (err) {
    console.warn('ProfileView: fetchUser failed', err)
  } finally {
    isPageLoading.value = false
  }
  // ── Escape key listener: close profile on Escape ────────────────────
  document.addEventListener('keydown', handleEscapeKey)
})

onUnmounted(() => {
  document.removeEventListener('keydown', handleEscapeKey)
})

// ── Close profile on Escape key ─────────────────────────────────────
function handleEscapeKey(e: KeyboardEvent) {
  if (e.key === 'Escape') {
    if (showPasswordModal.value) {
      closePasswordModal()
    } else {
      closeProfile()
    }
  }
}

// ── Edit State ────────────────────────────────────────────────────────
const isEditing = ref(false)
const isSaving = ref(false)
const saveMessage = ref('')
const saveMessageType = ref<'success' | 'error'>('success')

const editForm = reactive({
  first_name: '',
  last_name: '',
  phone: '',
  mothers_last_name: '',
  mothers_first_name: '',
  birth_place: '',
  birth_date: '',
  // Identity docs
  id_card_number: '',
  id_card_expiry: '',
  license_number: '',
  license_expiry: '',
  license_categories: '',
  // Address
  address_zip: '',
  address_city: '',
  address_street_name: '',
  address_street_type: '',
  address_house_number: '',
  address_stairwell: '',
  address_floor: '',
  address_door: '',
  address_hrsz: '',
  // ICE contact
  ice_name: '',
  ice_relation: '',
  ice_phone: '',
  ice_email: '',
})

// ── Regional Settings State ──────────────────────────────────────────
const regionalSettings = reactive({
  language: localStorage.getItem('user-locale') || 'hu',
  dateFormat: localStorage.getItem('user-date-format') || 'hu',
  currency: localStorage.getItem('user-currency') || 'HUF',
})

function onLanguageChange() {
  locale.value = regionalSettings.language
  localStorage.setItem('user-locale', regionalSettings.language)
}

// ── Password Modal State ──────────────────────────────────────────────
const showPasswordModal = ref(false)
const isPasswordSaving = ref(false)
const passwordError = ref('')
const passwordSuccess = ref('')

const passwordForm = reactive({
  currentPassword: '',
  newPassword: '',
  confirmPassword: '',
})

function formatDate(dateVal: string | null | undefined): string {
  if (!dateVal) return ''
  return dateVal.substring(0, 10)
}

function startEditing() {
  const p = person.value
  const docs = identityDocs.value
  const ice = iceContact.value

  editForm.first_name = p?.first_name || ''
  editForm.last_name = p?.last_name || ''
  editForm.phone = p?.phone || ''
  editForm.mothers_last_name = p?.mothers_last_name || ''
  editForm.mothers_first_name = p?.mothers_first_name || ''
  editForm.birth_place = p?.birth_place || ''
  editForm.birth_date = formatDate(p?.birth_date)

  // Identity docs
  editForm.id_card_number = docs?.ID_CARD?.number || ''
  editForm.id_card_expiry = formatDate(docs?.ID_CARD?.expiry_date) || ''
  editForm.license_number = docs?.LICENSE?.number || ''
  editForm.license_expiry = formatDate(docs?.LICENSE?.expiry_date) || ''
  editForm.license_categories = docs?.LICENSE?.categories || ''

  // Address — data is nested in p.address as address_* fields
  const addr = p?.address
  editForm.address_zip = addr?.address_zip || ''
  editForm.address_city = addr?.address_city || ''
  editForm.address_street_name = addr?.address_street_name || ''
  editForm.address_street_type = addr?.address_street_type || ''
  editForm.address_house_number = addr?.address_house_number || ''
  editForm.address_stairwell = addr?.address_stairwell || ''
  editForm.address_floor = addr?.address_floor || ''
  editForm.address_door = addr?.address_door || ''
  editForm.address_hrsz = addr?.address_hrsz || ''

  // ICE contact
  editForm.ice_name = ice?.name || ''
  editForm.ice_relation = ice?.relation || ''
  editForm.ice_phone = ice?.phone || ''
  editForm.ice_email = ice?.email || ''

  saveMessage.value = ''
  isEditing.value = true
}

function cancelEditing() {
  isEditing.value = false
  saveMessage.value = ''
}

// ── Debounced ZIP → City auto-fill via internal API ──
let zipTimeout: ReturnType<typeof setTimeout>
watch(
  () => editForm.address_zip,
  (newZip) => {
    clearTimeout(zipTimeout)
    if (newZip && newZip.length >= 3) {
      isCityLoading.value = true
      zipTimeout = setTimeout(async () => {
        try {
          const countryCode = 'HU'
          const response = await api.get('/system/parameters/zip-lookup', {
            params: { country_code: countryCode, zip_code: newZip }
          })
          if (response.data?.city) {
            editForm.address_city = response.data.city
          }
        } catch (error) {
          console.warn('Zip lookup failed:', error)
        } finally {
          isCityLoading.value = false
        }
      }, 600)
    } else {
      isCityLoading.value = false
    }
  }
)

function buildIdentityDocsPayload(): Record<string, any> | null {
  const idCardNumber = editForm.id_card_number?.trim()
  const idCardExpiry = editForm.id_card_expiry?.trim()
  const licenseNumber = editForm.license_number?.trim()
  const licenseExpiry = editForm.license_expiry?.trim()
  const licenseCategories = editForm.license_categories?.trim()

  if (!idCardNumber && !idCardExpiry && !licenseNumber && !licenseExpiry && !licenseCategories) {
    return null
  }

  const payload: Record<string, any> = {}

  if (idCardNumber || idCardExpiry) {
    payload.ID_CARD = {}
    if (idCardNumber) payload.ID_CARD.number = idCardNumber
    if (idCardExpiry) payload.ID_CARD.expiry_date = idCardExpiry
  }

  if (licenseNumber || licenseExpiry || licenseCategories) {
    payload.LICENSE = {}
    if (licenseNumber) payload.LICENSE.number = licenseNumber
    if (licenseExpiry) payload.LICENSE.expiry_date = licenseExpiry
    if (licenseCategories) payload.LICENSE.categories = licenseCategories
  }

  return payload
}

function buildIceContactPayload(): Record<string, any> | null {
  const name = editForm.ice_name?.trim()
  const relation = editForm.ice_relation?.trim()
  const phone = editForm.ice_phone?.trim()
  const email = editForm.ice_email?.trim()

  if (!name && !relation && !phone && !email) {
    return null
  }

  const payload: Record<string, any> = {}
  if (name) payload.name = name
  if (relation) payload.relation = relation
  if (phone) payload.phone = phone
  if (email) payload.email = email
  return payload
}

async function savePerson() {
  isSaving.value = true
  saveMessage.value = ''

  try {
    const payload: Record<string, any> = {}
    const fields = [
      'first_name', 'last_name', 'phone',
      'mothers_last_name', 'mothers_first_name',
      'birth_place', 'birth_date',
      'address_zip', 'address_city',
      'address_street_name', 'address_street_type', 'address_house_number',
      'address_stairwell', 'address_floor', 'address_door',
      'address_hrsz',
    ]
    for (const field of fields) {
      const val = (editForm as any)[field]
      if (val !== null && val !== undefined && val !== '') {
        payload[field] = val
      }
    }

    const docsPayload = buildIdentityDocsPayload()
    if (docsPayload) {
      payload.identity_docs = docsPayload
    }

    const icePayload = buildIceContactPayload()
    if (icePayload) {
      payload.ice_contact = icePayload
    }

    await authStore.updatePerson(payload)
    saveMessage.value = t('profile.saveSuccess')
    saveMessageType.value = 'success'
    isEditing.value = false
  } catch (err: any) {
    saveMessage.value = err?.response?.data?.detail || t('profile.saveError')
    saveMessageType.value = 'error'
  } finally {
    isSaving.value = false
  }
}

// ── Change Password ──────────────────────────────────────────────────
function closePasswordModal() {
  showPasswordModal.value = false
  passwordError.value = ''
  passwordSuccess.value = ''
  passwordForm.currentPassword = ''
  passwordForm.newPassword = ''
  passwordForm.confirmPassword = ''
}

async function submitPasswordChange() {
  passwordError.value = ''
  passwordSuccess.value = ''

  if (!passwordForm.currentPassword || !passwordForm.newPassword || !passwordForm.confirmPassword) {
    passwordError.value = t('profile.passwordRequired')
    return
  }

  if (passwordForm.newPassword !== passwordForm.confirmPassword) {
    passwordError.value = t('profile.passwordMismatch')
    return
  }

  if (passwordForm.newPassword.length < 6) {
    passwordError.value = t('profile.passwordMinLength')
    return
  }

  isPasswordSaving.value = true

  try {
    const result = await authStore.changePassword(
      passwordForm.currentPassword,
      passwordForm.newPassword
    )
    passwordSuccess.value = result.message || t('profile.passwordChanged')

    setTimeout(() => {
      closePasswordModal()
    }, 2000)
  } catch (err: any) {
    passwordError.value = err?.response?.data?.detail || t('profile.passwordChangeFailed')
  } finally {
    isPasswordSaving.value = false
  }
}
</script>
