<template>
  <div class="fixed inset-0 flex flex-col">
    <!-- Fullscreen Map -->
    <div class="absolute inset-0">
      <ClientOnly>
        <CatalogMap
          ref="mapRef"
          map-id="step-product-map"
          :items="[]"
          :clustered-points="clusteredNodes"
          :use-server-clustering="true"
          point-color="#f97316"
          entity-type="offer"
          @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">
          <!-- Drag handle -->
          <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: 1 }) }}</p>
              <h2 class="text-2xl font-black tracking-tight text-base-content">{{ $t('catalog.steps.selectProduct') }}</h2>
            </div>
            <span class="badge badge-neutral">{{ products.length }}</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.searchProducts')"
              class="grow bg-transparent"
            />
          </label>
        </div>

        <!-- Product 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="filteredProducts.length === 0" class="text-center py-8 text-base-content/50">
            <Icon name="lucide:package-x" size="32" class="mb-2" />
            <p>{{ $t('catalog.empty.noProducts') }}</p>
          </div>

          <div v-else class="flex flex-col gap-2">
            <button
              v-for="product in filteredProducts"
              :key="product.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="selectProduct(product)"
            >
              <div class="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-gradient-to-br from-orange-400 to-orange-600 shadow-lg">
                <Icon name="lucide:package" size="20" class="text-white" />
              </div>
              <div class="flex-1 min-w-0">
                <span class="text-base font-bold text-base-content block truncate">{{ product.name || product.uuid }}</span>
                <span v-if="product.offersCount" class="text-sm text-base-content/50">{{ product.offersCount }} {{ $t('catalog.offers') }}</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('')

// Load products
const { items: products, isLoading, init: initProducts } = useCatalogProducts()

// Clustering for map background
const { clusteredNodes, fetchClusters } = useClusteredNodes(undefined, ref('offer'))

const onBoundsChange = (bounds: MapBounds) => {
  fetchClusters(bounds)
}

const onMapSelect = (uuid: string) => {
  // Map click — ignore for product step
}

// Filter products by search
const filteredProducts = computed(() => {
  if (!searchQuery.value.trim()) return products.value
  const q = searchQuery.value.toLowerCase().trim()
  return products.value.filter(p =>
    (p.name || '').toLowerCase().includes(q) ||
    (p.uuid || '').toLowerCase().includes(q)
  )
})

// Select product → navigate to hub step
const selectProduct = (product: { uuid: string; name?: string | null }) => {
  const query: Record<string, string> = {
    ...route.query as Record<string, string>,
    product: product.uuid,
  }
  if (product.name) query.productName = product.name

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

// Init
onMounted(() => {
  initProducts()
})

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