<template>
  <Stack gap="6">
    <Section variant="plain" paddingY="md">
      <PageHeader :title="pageTitle">
        <template v-if="selectedProduct" #actions>
          <NuxtLink :to="localePath('/catalog/offers')" class="btn btn-ghost btn-sm">
            <Icon name="lucide:arrow-left" size="16" />
            {{ t('common.back') }}
          </NuxtLink>
        </template>
      </PageHeader>
    </Section>

    <!-- Loading state -->
    <Section v-if="isLoading || productsLoading" variant="plain" paddingY="md">
      <Card padding="lg">
        <Stack align="center" justify="center" gap="3">
          <Spinner />
          <Text tone="muted">{{ t('catalogLanding.states.loading') }}</Text>
        </Stack>
      </Card>
    </Section>

    <!-- Products catalog (when no product selected) -->
    <Section v-else-if="!selectedProductUuid" variant="plain" paddingY="md">
      <Stack gap="4">
        <Grid :cols="1" :md="2" :lg="3" :gap="4">
          <Card
            v-for="product in products"
            :key="product.uuid"
            padding="sm"
            interactive
            @click="selectProduct(product)"
          >
            <Stack gap="2">
              <Text size="base" weight="semibold">{{ product.name }}</Text>
              <Text tone="muted">{{ product.categoryName || t('catalogProduct.labels.category_unknown') }}</Text>
            </Stack>
          </Card>
        </Grid>

        <Stack v-if="products.length === 0" align="center" gap="2">
          <Text tone="muted">{{ t('catalogOffersSection.empty.no_products') }}</Text>
        </Stack>
      </Stack>
    </Section>

    <!-- Offers for selected product -->
    <Section v-else variant="plain" paddingY="md">
      <Stack gap="4">
        <NuxtLink :to="offersMapLink" class="block h-48 rounded-lg overflow-hidden cursor-pointer">
          <ClientOnly>
            <MapboxGlobe
              map-id="offers-map"
              :locations="itemsWithCoords"
              :height="192"
            />
          </ClientOnly>
        </NuxtLink>

        <CatalogFilters :filters="filters" v-model="selectedFilter" />

        <Grid :cols="1" :md="2" :lg="3" :gap="4">
          <OfferCard
            v-for="offer in items"
            :key="offer.uuid"
            :offer="offer"
          />
        </Grid>

        <PaginationLoadMore
          :shown="items.length"
          :total="total"
          :can-load-more="canLoadMore"
          :loading="isLoadingMore"
          @load-more="loadMore"
        />

        <Stack v-if="total === 0" align="center" gap="2">
          <Text tone="muted">{{ t('catalogOffersSection.empty.no_offers') }}</Text>
        </Stack>
      </Stack>
    </Section>
  </Stack>
</template>

<script setup lang="ts">
definePageMeta({
  layout: 'topnav'
})

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

// Products catalog
const {
  items: products,
  isLoading: productsLoading,
  init: initProducts
} = useCatalogProducts()

// Offers
const {
  items,
  total,
  selectedFilter,
  filters,
  isLoading,
  isLoadingMore,
  itemsWithCoords,
  canLoadMore,
  loadMore,
  init: initOffers,
  setProductUuid
} = useCatalogOffers()

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

// Selected product info
const selectedProduct = computed(() => {
  if (!selectedProductUuid.value) return null
  return products.value.find(p => p.uuid === selectedProductUuid.value)
})

const pageTitle = computed(() => {
  if (selectedProduct.value) {
    return `${t('catalogOffersSection.header.title')}: ${selectedProduct.value.name}`
  }
  return t('catalogOffersSection.header.select_product')
})

const offersMapLink = computed(() => {
  if (selectedProductUuid.value) {
    return localePath(`/catalog/offers/map?product=${selectedProductUuid.value}`)
  }
  return localePath('/catalog/offers/map')
})

const selectProduct = (product: any) => {
  router.push({
    path: route.path,
    query: { product: product.uuid }
  })
}

// Initialize
await initProducts()

// Watch for product changes
watch(selectedProductUuid, async (uuid) => {
  setProductUuid(uuid || null)
  if (uuid) {
    await initOffers()
  }
}, { immediate: true })

useHead(() => ({
  title: pageTitle.value
}))
</script>
