<template>
  <div class="fixed inset-0 flex flex-col">
    <!-- Fullscreen Map -->
    <div class="absolute inset-0">
      <ClientOnly>
        <CatalogMap
          ref="mapRef"
          map-id="step-hub-map"
          :items="hubMapItems"
          :use-server-clustering="false"
          point-color="#22c55e"
          entity-type="hub"
          @select-item="onMapSelect"
          @bounds-change="onBoundsChange"
        />
      </ClientOnly>
    </div>

    <!-- Bottom sheet card -->
    <div class="fixed inset-x-0 bottom-0 z-10 flex flex-col items-center pointer-events-none">
      <article
        class="w-full max-w-[980px] rounded-t-3xl bg-white shadow-[0_-8px_40px_rgba(0,0,0,0.12)] pointer-events-auto flex flex-col"
        style="max-height: 60vh"
      >
        <!-- Header -->
        <div class="shrink-0 p-5 pb-0 md:px-7 md:pt-7">
          <div class="flex justify-center mb-4">
            <div class="w-10 h-1 bg-base-300 rounded-full" />
          </div>

          <div class="flex items-center justify-between mb-1">
            <div>
              <p class="text-xs font-bold uppercase tracking-wider text-base-content/50">{{ $t('catalog.step', { n: 2 }) }}</p>
              <h2 class="text-2xl font-black tracking-tight text-base-content">{{ $t('catalog.steps.selectDestination') }}</h2>
            </div>
            <span class="badge badge-neutral">{{ hubs.length }}</span>
          </div>

          <!-- Selected product chip -->
          <div v-if="productName" class="flex items-center gap-2 mt-2 mb-1">
            <span class="badge badge-warning gap-1">
              <Icon name="lucide:package" size="12" />
              {{ productName }}
            </span>
          </div>

          <!-- Search input -->
          <label class="input input-bordered w-full mt-3 rounded-full flex items-center gap-2">
            <Icon name="lucide:search" size="16" class="text-base-content/40" />
            <input
              v-model="searchQuery"
              type="text"
              :placeholder="$t('catalog.search.searchHubs')"
              class="grow bg-transparent"
            />
          </label>
        </div>

        <!-- Hub list -->
        <div class="min-h-0 flex-1 overflow-y-auto p-5 md:px-7">
          <div v-if="isLoading" class="flex items-center justify-center py-8">
            <span class="loading loading-spinner loading-md" />
          </div>

          <div v-else-if="filteredHubs.length === 0" class="text-center py-8 text-base-content/50">
            <Icon name="lucide:warehouse" size="32" class="mb-2" />
            <p>{{ $t('catalog.empty.noHubs') }}</p>
          </div>

          <div v-else class="flex flex-col gap-2">
            <button
              v-for="hub in filteredHubs"
              :key="hub.uuid"
              class="flex items-center gap-4 rounded-2xl p-4 text-left transition-all hover:bg-base-200/60 active:scale-[0.98] group"
              @click="selectHub(hub)"
            >
              <div class="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-gradient-to-br from-green-400 to-green-600 shadow-lg">
                <Icon name="lucide:warehouse" size="20" class="text-white" />
              </div>
              <div class="flex-1 min-w-0">
                <span class="text-base font-bold text-base-content block truncate">{{ hub.name || hub.uuid }}</span>
                <span v-if="hub.country" class="text-sm text-base-content/50">{{ hub.country }}</span>
              </div>
              <Icon name="lucide:chevron-right" size="18" class="text-base-content/30 group-hover:text-base-content/60 transition-colors" />
            </button>
          </div>
        </div>
      </article>
    </div>
  </div>
</template>

<script setup lang="ts">
import type { MapBounds } from '~/components/catalog/CatalogMap.vue'

definePageMeta({ layout: 'topnav' })

const { t } = useI18n()
const router = useRouter()
const localePath = useLocalePath()
const route = useRoute()

const mapRef = ref(null)
const searchQuery = ref('')

// Get product from query
const productUuid = computed(() => route.query.product as string | undefined)
const productName = computed(() => route.query.productName as string | undefined)

// Load hubs (filtered by product if available)
const { items: hubs, isLoading, init: initHubs, setProductFilter } = useCatalogHubs()

const onBoundsChange = (_bounds: MapBounds) => {
  // No clustering needed — showing hub items directly
}

// Hub items for map
const hubMapItems = computed(() =>
  hubs.value
    .filter(h => h.latitude != null && h.longitude != null)
    .map(h => ({
      uuid: h.uuid || '',
      name: h.name || '',
      latitude: Number(h.latitude),
      longitude: Number(h.longitude),
      country: h.country || undefined,
    }))
)

// Map click → select hub
const onMapSelect = (uuid: string) => {
  const hub = hubs.value.find(h => h.uuid === uuid)
  if (hub) selectHub(hub)
}

// Filter hubs by search
const filteredHubs = computed(() => {
  if (!searchQuery.value.trim()) return hubs.value
  const q = searchQuery.value.toLowerCase().trim()
  return hubs.value.filter(h =>
    (h.name || '').toLowerCase().includes(q) ||
    (h.country || '').toLowerCase().includes(q)
  )
})

// Select hub → navigate to quantity step
const selectHub = (hub: { uuid?: string | null; name?: string | null }) => {
  if (!hub.uuid) return
  const query: Record<string, string> = {
    ...route.query as Record<string, string>,
    hub: hub.uuid,
  }
  if (hub.name) query.hubName = hub.name

  router.push({
    path: localePath('/catalog/quantity'),
    query,
  })
}

// Init
onMounted(() => {
  if (productUuid.value) {
    setProductFilter(productUuid.value)
  }
  initHubs()
})

useHead(() => ({
  title: t('catalog.steps.selectDestination')
}))
</script>
