<template>
  <div class="fixed inset-0">
    <ClientOnly>
      <CatalogMap
        map-id="step-product-map"
        :items="[]"
        :clustered-points="clusteredNodes"
        :use-server-clustering="true"
        point-color="#f97316"
        entity-type="offer"
        :fit-padding-left="460"
        @bounds-change="onBoundsChange"
      />
    </ClientOnly>

    <MapSidePanel
      :title="t('catalog.steps.selectProduct')"
      :initial-collapsed="false"
      width-class="w-[min(calc(100vw-1rem),440px)] md:w-[420px] xl:w-[460px]"
    >
      <div class="space-y-3">
        <p class="text-xs font-bold uppercase tracking-wider text-[#8a7761]">{{ $t('catalog.step', { n: 1 }) }}</p>

        <label class="input w-full rounded-full bg-white border-[#dccfbf] flex items-center gap-2">
          <Icon name="lucide:search" size="16" class="text-[#8a7761]" />
          <input
            v-model="searchQuery"
            type="text"
            :placeholder="$t('catalog.search.searchProducts')"
            class="grow bg-transparent"
          >
        </label>
      </div>

      <div class="mt-4 flex flex-col gap-2">
        <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="rounded-2xl border border-[#e4d9ca] bg-white px-4 py-8 text-center text-[#7c6d5a]">
          <Icon name="lucide:package-x" size="30" class="mx-auto mb-2" />
          <p>{{ $t('catalog.empty.noProducts') }}</p>
        </div>

        <button
          v-for="product in filteredProducts"
          v-else
          :key="product.uuid"
          class="flex items-center gap-4 rounded-2xl border border-[#e4d9ca] bg-white p-4 text-left transition-colors hover:bg-[#f8f3ec]"
          @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="min-w-0 flex-1">
            <span class="block truncate text-base font-bold text-[#2f2418]">{{ product.name || product.uuid }}</span>
            <span v-if="product.offersCount" class="text-sm text-[#7a6d5d]">{{ product.offersCount }} {{ $t('catalog.offers') }}</span>
          </div>
          <Icon name="lucide:chevron-right" size="18" class="text-[#8a7761]" />
        </button>
      </div>
    </MapSidePanel>
  </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 searchQuery = ref('')

const { items: products, isLoading, init: initProducts } = useCatalogProducts()
const { clusteredNodes, fetchClusters } = useClusteredNodes(undefined, ref('offer'))

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

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)
  )
})

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,
  })
}

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

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