<template>
  <div>
    <!-- Page Header -->
    <div class="mb-8">
      <h1 class="text-2xl font-bold text-white">{{ $t('garages.title') }}</h1>
      <p class="text-slate-400 mt-1">{{ $t('garages.subtitle') }}</p>
    </div>
    <!-- Search & Filter Bar (always rendered — stable DOM for input focus) -->
    <div class="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4 mb-6">
      <div class="relative flex-1 max-w-md">
        <svg class="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
        </svg>
        <input
          v-model="searchQuery"
          type="text"
          :placeholder="$t('garages.search_placeholder')"
          class="w-full pl-10 pr-4 py-2.5 bg-slate-800 border border-slate-700 rounded-lg text-sm text-white placeholder-slate-500 focus:outline-none focus:ring-2 focus:ring-indigo-500/50 focus:border-indigo-500 transition"
        />
      </div>
      <div class="flex items-center gap-2">
        <select
          v-model="filterType"
          class="px-3 py-2.5 bg-slate-800 border border-slate-700 rounded-lg text-sm text-slate-300 focus:outline-none focus:ring-2 focus:ring-indigo-500/50 transition"
        >
          <option value="all">{{ $t('garages.all_types') }}</option>
          <option value="individual">{{ $t('garages.type_individual') }}</option>
          <option value="corporate">{{ $t('garages.type_corporate') }}</option>
        </select>
        <select
          v-model="selectedPackage"
          class="px-3 py-2.5 bg-slate-800 border border-slate-700 rounded-lg text-sm text-slate-300 focus:outline-none focus:ring-2 focus:ring-indigo-500/50 transition"
        >
          <option value="all">{{ $t('garages.all_tiers') }}</option>
          <option
            v-for="tier in availableTierNames"
            :key="tier"
            :value="tier"
          >
            {{ tier }}
          </option>
        </select>
      </div>
    </div>

    <!-- Loading State -->
    <div v-if="loading" class="flex items-center justify-center py-20">
      <div class="flex flex-col items-center gap-3">
        <svg class="w-8 h-8 text-indigo-400 animate-spin" fill="none" viewBox="0 0 24 24">
          <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4" />
          <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
        </svg>
        <p class="text-slate-400 text-sm">{{ $t('garages.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="fetchGarages" class="px-4 py-2 text-sm bg-indigo-600/20 text-indigo-300 hover:bg-indigo-600/30 rounded-lg transition">
        {{ $t('garages.retry') }}
      </button>
    </div>

    <!-- Content -->
    <template v-else>
      <!-- P0 HOTFIX: Global Stats Cards - always show unfiltered global counts -->
      <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4 mb-8">
        <div class="bg-slate-800 rounded-xl border border-slate-700 p-4">
          <div class="flex items-center gap-3">
            <div class="p-2 rounded-lg bg-indigo-500/10 text-indigo-400">
              <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4" />
              </svg>
            </div>
            <div>
              <p class="text-xs text-slate-400 uppercase tracking-wider">{{ $t('garages.total_garages') }}</p>
              <p class="text-2xl font-bold text-white">{{ globalTotalCount }}</p>
            </div>
          </div>
        </div>
        <div class="bg-slate-800 rounded-xl border border-slate-700 p-4">
          <div class="flex items-center gap-3">
            <div class="p-2 rounded-lg bg-emerald-500/10 text-emerald-400">
              <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="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>
            <div>
              <p class="text-xs text-slate-400 uppercase tracking-wider">{{ $t('garages.private_garages') }}</p>
              <p class="text-2xl font-bold text-emerald-400">{{ globalIndividualCount }}</p>
            </div>
          </div>
        </div>
        <div class="bg-slate-800 rounded-xl border border-slate-700 p-4">
          <div class="flex items-center gap-3">
            <div class="p-2 rounded-lg bg-amber-500/10 text-amber-400">
              <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4" />
              </svg>
            </div>
            <div>
              <p class="text-xs text-slate-400 uppercase tracking-wider">{{ $t('garages.corporate_garages') }}</p>
              <p class="text-2xl font-bold text-amber-400">{{ globalCorporateCount }}</p>
            </div>
          </div>
        </div>
      </div>

      <!-- P0 HOTFIX: Filtered results indicator -->
      <div v-if="isFilterActive" class="mb-4 text-xs text-slate-500">
        Szűrt találat: <span class="text-slate-300 font-semibold">{{ garages.length }}</span> db
      </div>

      <!-- Data Table -->
      <div class="bg-slate-800/50 border border-slate-700 rounded-xl overflow-hidden">
        <div class="overflow-x-auto">
          <table class="w-full text-sm">
            <thead>
              <tr class="border-b border-slate-700 bg-slate-800/80">
                <th class="text-left py-3.5 px-4 text-xs font-semibold uppercase tracking-wider text-slate-400">ID</th>
                <th class="text-left py-3.5 px-4 text-xs font-semibold uppercase tracking-wider text-slate-400">{{ $t('garages.company_name') }}</th>
                <th class="text-left py-3.5 px-4 text-xs font-semibold uppercase tracking-wider text-slate-400">{{ $t('garages.status') }}</th>
                <th class="text-left py-3.5 px-4 text-xs font-semibold uppercase tracking-wider text-slate-400">{{ $t('garages.current_package') }}</th>
                <th class="text-left py-3.5 px-4 text-xs font-semibold uppercase tracking-wider text-slate-400">{{ $t('garages.expiration_date') }}</th>
                <th class="text-left py-3.5 px-4 text-xs font-semibold uppercase tracking-wider text-slate-400">{{ $t('garages.actions') }}</th>
              </tr>
            </thead>
            <tbody>
              <tr
                v-for="garage in filteredGarages"
                :key="garage.id"
                class="border-b border-slate-700/50 hover:bg-slate-700/30 transition"
              >
                <!-- ID -->
                <td class="py-3.5 px-4 text-slate-400 font-mono text-xs">{{ garage.id }}</td>

                <!-- Company Name (display_name priority, fallback to name) -->
                <td class="py-3.5 px-4">
                  <div class="flex items-center gap-3">
                    <div
                      class="w-8 h-8 rounded-lg flex items-center justify-center text-sm font-bold text-white"
                      :class="getInitialsColor(garageDisplayName(garage))"
                    >
                      {{ getInitials(garageDisplayName(garage)) }}
                    </div>
                    <div>
                      <NuxtLink
                        :to="'/garages/' + garage.id"
                        class="text-sm font-medium text-white hover:underline cursor-pointer hover:text-indigo-400 transition-colors"
                      >
                        {{ garageDisplayName(garage) }}
                      </NuxtLink>
                      <p class="text-xs text-slate-500">{{ garage.city || '—' }} · {{ garage.member_count }} {{ $t('garages.members') }}</p>
                    </div>
                  </div>
                </td>

                <!-- Status -->
                <td class="py-3.5 px-4">
                  <span
                    class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium"
                    :class="statusBadgeClass(garage.status)"
                  >
                    <span
                      class="w-1.5 h-1.5 rounded-full mr-1.5"
                      :class="statusDotClass(garage.status)"
                    ></span>
                    {{ statusLabel(garage.status) }}
                  </span>
                </td>

                <!-- Current Package -->
                <td class="py-3.5 px-4">
                  <span
                    class="px-2.5 py-0.5 rounded-full text-xs font-medium"
                    :class="tierBadgeClass(garage.subscription_tier_name)"
                  >
                    {{ garage.subscription_tier_name }}
                  </span>
                </td>

                <!-- Expiration Date -->
                <td class="py-3.5 px-4">
                  <span v-if="garage.subscription_expires_at" class="text-slate-300 text-xs">
                    {{ formatDate(garage.subscription_expires_at) }}
                  </span>
                  <span v-else class="text-slate-500 text-xs italic">{{ $t('garages.indefinite') }}</span>
                </td>

                <!-- Actions -->
                <td class="py-3.5 px-4">
                  <div class="flex items-center gap-2">
                    <button
                      @click="openDetails(garage)"
                      class="px-3 py-1.5 text-xs font-medium bg-slate-600/20 text-slate-300 hover:bg-slate-600/30 rounded-lg transition"
                      :title="$t('garages.view_details')"
                    >
                      {{ $t('garages.view_details') }}
                    </button>
                    <button
                      @click="openSubscriptionModal(garage)"
                      class="px-3 py-1.5 text-xs font-medium bg-indigo-600/20 text-indigo-300 hover:bg-indigo-600/30 rounded-lg transition"
                    >
                      {{ $t('garages.manage_subscription') }}
                    </button>
                    <button
                      @click="toggleStatus(garage)"
                      class="px-3 py-1.5 text-xs font-medium rounded-lg transition"
                      :class="garage.is_active
                        ? 'bg-red-500/10 text-red-300 hover:bg-red-500/20'
                        : 'bg-emerald-500/10 text-emerald-300 hover:bg-emerald-500/20'"
                    >
                      {{ garage.is_active ? $t('garages.deactivate') : $t('garages.activate') }}
                    </button>
                  </div>
                </td>
              </tr>
            </tbody>
          </table>
        </div>

        <!-- Empty State -->
        <div
          v-if="filteredGarages.length === 0 && !loading"
          class="flex flex-col items-center justify-center py-16 text-center"
        >
          <svg class="w-12 h-12 text-slate-600 mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4" />
          </svg>
          <p class="text-slate-400 text-sm">{{ $t('garages.no_results') }}</p>
        </div>
      </div>
    </template>

    <!-- ================================================================ -->
    <!-- Subscription Management Modal -->
    <!-- ================================================================ -->
    <div
      v-if="showSubscriptionModal"
      class="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm"
      @click.self="closeSubscriptionModal"
    >
      <div class="bg-slate-800 border border-slate-700 rounded-2xl shadow-2xl w-full max-w-lg mx-4 overflow-hidden">
        <!-- Modal Header -->
        <div class="px-6 py-4 border-b border-slate-700 flex items-center justify-between">
          <div>
            <h3 class="text-lg font-semibold text-white">{{ $t('garages.manage_subscription') }}</h3>
            <p class="text-sm text-slate-400 mt-0.5">{{ selectedGarage ? garageDisplayName(selectedGarage) : '' }}</p>
          </div>
          <button @click="closeSubscriptionModal" 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>

        <!-- Modal Body -->
        <div class="px-6 py-5 space-y-5">
          <!-- Current Subscription Info -->
          <div class="bg-slate-900/50 rounded-xl p-4 border border-slate-700/50">
            <p class="text-xs text-slate-500 uppercase tracking-wider mb-1">{{ $t('garages.current_package') }}</p>
            <p class="text-sm font-medium text-white">
              {{ selectedGarage?.subscription_tier_name || $t('garages.free_fallback') }}
            </p>
            <p v-if="selectedGarage?.subscription_expires_at" class="text-xs text-slate-400 mt-1">
              {{ $t('garages.expires') }}: {{ formatDate(selectedGarage.subscription_expires_at) }}
            </p>
          </div>

          <!-- Tier Selection -->
          <div>
            <label class="block text-sm font-medium text-slate-300 mb-2">{{ $t('garages.select_package') }}</label>
            <select
              v-model="selectedTierId"
              class="w-full px-3 py-2.5 bg-slate-900 border border-slate-700 rounded-lg text-sm text-white focus:outline-none focus:ring-2 focus:ring-indigo-500/50 transition"
            >
              <option value="" disabled>{{ $t('garages.select_package_placeholder') }}</option>
              <option
                v-for="tier in availableTiers"
                :key="tier.id"
                :value="tier.id"
              >
                {{ tier.name }} (Level {{ tier.tier_level }})
              </option>
            </select>
          </div>

          <!-- Custom Expiration Date -->
          <div>
            <label class="block text-sm font-medium text-slate-300 mb-2">
              {{ $t('garages.custom_expiration') }}
              <span class="text-xs text-slate-500 ml-1">({{ $t('garages.optional') }})</span>
            </label>
            <input
              v-model="customExpiresAt"
              type="datetime-local"
              class="w-full px-3 py-2.5 bg-slate-900 border border-slate-700 rounded-lg text-sm text-white focus:outline-none focus:ring-2 focus:ring-indigo-500/50 transition"
            />
            <p class="text-xs text-slate-500 mt-1.5">{{ $t('garages.custom_expiration_hint') }}</p>
          </div>

          <!-- Save Error -->
          <div
            v-if="saveError"
            class="bg-red-500/10 border border-red-500/20 rounded-lg px-4 py-3"
          >
            <p class="text-sm text-red-400">{{ saveError }}</p>
          </div>
        </div>

        <!-- Modal Footer -->
        <div class="px-6 py-4 border-t border-slate-700 flex items-center justify-end gap-3">
          <button
            @click="closeSubscriptionModal"
            class="px-4 py-2 text-sm font-medium text-slate-300 hover:text-white transition"
          >
            {{ $t('garages.cancel') }}
          </button>
          <button
            @click="saveSubscription"
            :disabled="saving || !selectedTierId"
            class="px-5 py-2 text-sm font-medium rounded-lg transition disabled:opacity-50 disabled:cursor-not-allowed"
            :class="saving
              ? 'bg-indigo-600/50 text-indigo-200 cursor-wait'
              : 'bg-indigo-600 text-white hover:bg-indigo-500'"
          >
            <span v-if="saving" class="flex items-center gap-2">
              <svg class="w-4 h-4 animate-spin" fill="none" viewBox="0 0 24 24">
                <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4" />
                <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
              </svg>
              {{ $t('garages.saving') }}
            </span>
            <span v-else>{{ $t('garages.save') }}</span>
          </button>
        </div>
      </div>
    </div>

    <!-- Save Notification -->
    <div
      v-if="saveNotification"
      class="fixed bottom-6 right-6 px-5 py-3 rounded-xl shadow-xl text-sm font-medium z-50"
      :class="saveNotification.type === 'success'
        ? 'bg-emerald-600 text-white'
        : 'bg-red-600 text-white'"
    >
      {{ saveNotification.message }}
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'

definePageMeta({
  middleware: 'auth',
})

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

interface SubscriptionInfo {
  id: number
  org_id: number
  tier_id: number
  tier_name: string
  valid_from: string | null
  valid_until: string | null
  is_active: boolean
  extra_allowances: Record<string, unknown>
}

interface Garage {
  id: number
  name: string
  full_name: string
  display_name: string | null
  email: string | null
  status: string
  is_active: boolean
  is_verified: boolean
  is_deleted: boolean
  org_type: string
  city: string | null
  region: string | null
  segment: string | null
  member_count: number
  created_at: string | null
  subscription: SubscriptionInfo | null
  subscription_tier_name: string
  subscription_expires_at: string | null
}

interface Tier {
  id: number
  name: string
  tier_level: number
  rules: Record<string, unknown>
}

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

const loading = ref(true)
const error = ref<string | null>(null)
const garages = ref<Garage[]>([])
const availableTiers = ref<Tier[]>([])
const searchQuery = ref('')
const filterType = ref('all')
const selectedPackage = ref('all')

// P0 HOTFIX: Accumulating tier names — never shrinks, only grows.
// This prevents the dropdown from losing options when filtering by tier.
const availableTierNames = ref<string[]>([])

// Modal state
const showSubscriptionModal = ref(false)
const selectedGarage = ref<Garage | null>(null)
const selectedTierId = ref<number | ''>('')
const customExpiresAt = ref<string>('')
const saving = ref(false)
const saveError = ref<string | null>(null)

// Notification
const saveNotification = ref<{ type: 'success' | 'error'; message: string } | null>(null)

// ── Debounced Search Timer ──────────────────────────────────────────

let searchDebounceTimer: ReturnType<typeof setTimeout> | null = null

/**
 * P0: Debounced search — waits 400ms after the user stops typing
 * before triggering a server-side API call. This prevents excessive
 * requests on every keystroke while keeping the UI responsive.
 */
function debouncedFetchGarages() {
  if (searchDebounceTimer) {
    clearTimeout(searchDebounceTimer)
  }
  searchDebounceTimer = setTimeout(() => {
    fetchGarages()
  }, 400)
}

// ── Watchers ────────────────────────────────────────────────────────

// Watch searchQuery with debounce — only fires API call after 400ms idle
watch(searchQuery, () => {
  debouncedFetchGarages()
})

// Watch filterType — immediate API call (no debounce needed for dropdowns)
watch(filterType, () => {
  fetchGarages()
})

// Watch selectedPackage — immediate API call
watch(selectedPackage, () => {
  fetchGarages()
})

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

// P0 HOTFIX: Global stats stored from initial unfiltered load
// These NEVER change when filters are applied, so the stat cards
// always reflect the true database totals.
const globalTotalCount = ref(0)
const globalIndividualCount = ref(0)
const globalCorporateCount = ref(0)

// P0 HOTFIX: Detect if any filter is active
const isFilterActive = computed(() => {
  return searchQuery.value !== '' || filterType.value !== 'all' || selectedPackage.value !== 'all'
})

// P0 HOTFIX: Accumulating tier names — never shrinks, only grows.
// Watcher on garages adds newly discovered tier names to availableTierNames.
// This prevents the dropdown from losing options when filtering by tier.
watch(garages, (newGarages) => {
  const currentSet = new Set(availableTierNames.value)
  for (const g of newGarages) {
    if (g.subscription_tier_name) {
      currentSet.add(g.subscription_tier_name)
    }
  }
  availableTierNames.value = Array.from(currentSet).sort()
}, { immediate: true, deep: true })

// P0: Server-side filtered — the API handles all filtering.
// This computed is now a simple pass-through; the real filtering
// happens in fetchGarages() via query params.
const filteredGarages = computed(() => garages.value)

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

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

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

async function fetchGarages() {
  loading.value = true
  error.value = null
  try {
    // P0: Server-side search — pass all filter params to the API
    const params: Record<string, any> = { limit: 200 }

    // Debounced search query → server-side omni-search
    if (searchQuery.value) {
      params.search_term = searchQuery.value
    }

    // Org type filter
    if (filterType.value !== 'all') {
      params.org_type_filter = filterType.value
    }

    // Subscription tier filter
    if (selectedPackage.value !== 'all') {
      params.tier_name_filter = selectedPackage.value
    }

    const response = await $fetch<{ total: number; skip: number; limit: number; garages: Garage[] }>('/api/v1/admin/organizations', {
      params,
      headers: getAuthHeaders(),
    })
    garages.value = response.garages

    // P0 HOTFIX: Store global counts from unfiltered API response.
    // When no filters are active, the API returns the full dataset,
    // so we capture the global totals here. When filters ARE active,
    // we keep the previously captured global counts unchanged.
    if (!isFilterActive.value) {
      globalTotalCount.value = response.total
      globalIndividualCount.value = garages.value.filter(g => g.org_type === 'individual').length
      globalCorporateCount.value = garages.value.filter(g => g.org_type !== 'individual').length
    }
  } catch (err: any) {
    console.error('[Garages] Failed to fetch garages:', err)
    error.value = err?.data?.detail || err?.message || 'Failed to load garages'
  } finally {
    loading.value = false
  }
}

async function fetchTiers() {
  try {
    const response = await $fetch<{ total: number; tiers: Tier[] }>('/api/v1/admin/packages', {
      params: { include_hidden: true, limit: 100 },
      headers: getAuthHeaders(),
    })
    availableTiers.value = response.tiers
  } catch (err: any) {
    console.error('[Garages] Failed to fetch tiers:', err)
  }
}

// ── Subscription Modal ─────────────────────────────────────────────

function openSubscriptionModal(garage: Garage) {
  selectedGarage.value = garage
  selectedTierId.value = garage.subscription?.tier_id || ''
  customExpiresAt.value = ''
  saveError.value = null
  showSubscriptionModal.value = true
}

function closeSubscriptionModal() {
  showSubscriptionModal.value = false
  selectedGarage.value = null
  selectedTierId.value = ''
  customExpiresAt.value = ''
  saveError.value = null
}

async function saveSubscription() {
  if (!selectedGarage.value || !selectedTierId.value) return

  saving.value = true
  saveError.value = null

  try {
    const payload: Record<string, unknown> = {
      tier_id: selectedTierId.value,
    }

    // If custom expiration date is set, include it
    if (customExpiresAt.value) {
      payload.expires_at = new Date(customExpiresAt.value).toISOString()
    }

    await $fetch(`/api/v1/admin/organizations/${selectedGarage.value.id}/subscription`, {
      method: 'PATCH',
      headers: {
        ...getAuthHeaders(),
        'Content-Type': 'application/json',
      },
      body: payload,
    })

    showNotification('success', `"${garageDisplayName(selectedGarage.value)}" ${useNuxtApp().$i18n.t('garages.subscription_updated')}`)
    closeSubscriptionModal()

    // Refresh the list
    await fetchGarages()
  } catch (err: any) {
    console.error('[Garages] Failed to save subscription:', err)
    saveError.value = err?.data?.detail || err?.message || 'Failed to save subscription'
  } finally {
    saving.value = false
  }
}

// ── Status Toggle ──────────────────────────────────────────────────

async function toggleStatus(garage: Garage) {
  // Determine the new status based on current state
  const newStatus = garage.is_active ? 'inactive' : 'active'
  const actionLabel = garage.is_active ? 'deaktiválása' : 'aktiválása'

  try {
    await $fetch(`/api/v1/admin/organizations/${garage.id}/status`, {
      method: 'PUT',
      headers: {
        ...getAuthHeaders(),
        'Content-Type': 'application/json',
      },
      body: { status: newStatus },
    })

    showNotification('success', `"${garageDisplayName(garage)}" ${actionLabel} sikeresen megtörtént.`)

    // Refresh the list to reflect changes
    await fetchGarages()
  } catch (err: any) {
    console.error('[Garages] Failed to toggle status:', err)
    showNotification('error', err?.data?.detail || err?.message || `A garázs ${actionLabel} sikertelen.`)
  }
}

// ── Helpers ────────────────────────────────────────────────────────

/**
 * Returns the display name for a garage, prioritizing display_name over name.
 * This ensures clean, human-readable names are shown in the UI.
 */
function garageDisplayName(garage: Garage): string {
  return garage.display_name || garage.name || garage.full_name
}

function openDetails(garage: Garage) {
  navigateTo(`/garages/${garage.id}`)
}

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

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

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

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

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

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

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

function showNotification(type: 'success' | 'error', message: string) {
  saveNotification.value = { type, message }
  setTimeout(() => {
    saveNotification.value = null
  }, 4000)
}

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

onMounted(() => {
  fetchGarages()
  fetchTiers()
})
</script>
