<template>
  <CatalogPage
    :items="items"
    :loading="isLoading || productsLoading"
    map-id="offers-map"
    point-color="#f59e0b"
    :selected-id="selectedOfferId"
    @select="onSelectOffer"
  >
    <template #filters>
      <CatalogFilterSelect
        v-if="productFilters.length > 1"
        :filters="productFilters"
        :model-value="selectedProductUuid || 'all'"
        @update:model-value="onProductFilterChange"
      />
    </template>

    <template #card="{ item }">
      <OfferCard :offer="item" />
    </template>

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

    <template #empty>
      <Text tone="muted">{{ t('catalogOffersSection.empty.no_offers') }}</Text>
    </template>
  </CatalogPage>
</template>

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

const { t } = useI18n()

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

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

// Product filter options
const productFilters = computed(() => {
  const all = [{ id: 'all', label: t('catalogOffersSection.filters.all_products') }]
  const productOptions = products.value.map(p => ({
    id: p.uuid,
    label: p.name
  }))
  return [...all, ...productOptions]
})

// Handle product filter change
const onProductFilterChange = (value: string) => {
  setProductUuid(value === 'all' ? null : value)
}

// Selected offer for map highlighting
const selectedOfferId = ref<string>()

const onSelectOffer = (offer: any) => {
  selectedOfferId.value = offer.uuid
}

// Initialize
await Promise.all([initProducts(), initOffers()])

useHead(() => ({
  title: t('catalogOffersSection.header.title')
}))
</script>
