<template>
  <div class="flex flex-col h-[calc(100vh-200px)]">
    <!-- Header -->
    <div class="py-4">
      <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>
    </div>

    <!-- Loading state -->
    <div v-if="isLoading || productsLoading" class="flex-1 flex items-center justify-center">
      <Card padding="lg">
        <Stack align="center" justify="center" gap="3">
          <Spinner />
          <Text tone="muted">{{ t('catalogLanding.states.loading') }}</Text>
        </Stack>
      </Card>
    </div>

    <!-- Products catalog (when no product selected) -->
    <div v-else-if="!selectedProductUuid" class="flex-1 overflow-y-auto py-4">
      <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>
    </div>

    <!-- Offers for selected product - Split Layout -->
    <div v-else class="flex-1 flex gap-4 min-h-0">
      <!-- Left side: Filters + Cards (scrollable) -->
      <div class="w-full lg:w-2/5 overflow-y-auto pr-2">
        <Stack gap="4">
          <CatalogFilters :filters="filters" v-model="selectedFilter" />

          <Stack gap="3">
            <OfferCard
              v-for="offer in items"
              :key="offer.uuid"
              :offer="offer"
            />
          </Stack>

          <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>
      </div>

      <!-- Right side: Map (sticky, hidden on mobile) -->
      <div class="hidden lg:block lg:w-3/5 rounded-lg overflow-hidden">
        <ClientOnly>
          <MapboxGlobe
            map-id="offers-map"
            :locations="itemsWithCoords"
            class="h-full w-full"
          />
        </ClientOnly>
      </div>
    </div>
  </div>
</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 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>
