<template>
  <div class="flex flex-col flex-1 min-h-0">
    <!-- Header -->
    <div class="py-4">
      <PageHeader :title="t('catalogSuppliersSection.header.title')" />
    </div>

    <!-- Loading state -->
    <div v-if="isLoading" 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>

    <!-- ListMapLayout -->
    <ListMapLayout
      v-else
      ref="listMapRef"
      :items="items"
      :selected-item-id="selectedSupplierId"
      map-id="suppliers-map"
      point-color="#3b82f6"
      @select-item="onSelectSupplier"
    >
      <template #list>
        <Stack gap="4">
          <CatalogFilters :filters="filters" v-model="selectedFilter" />

          <Stack gap="3">
            <SupplierCard
              v-for="supplier in items"
              :key="supplier.uuid || supplier.teamUuid"
              :supplier="supplier"
              :class="{ 'ring-2 ring-primary': (supplier.uuid || supplier.teamUuid) === selectedSupplierId }"
              @click="onSelectSupplier(supplier.uuid || supplier.teamUuid)"
            />
          </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('catalogSuppliersSection.empty.no_suppliers') }}</Text>
          </Stack>
        </Stack>
      </template>
    </ListMapLayout>
  </div>
</template>

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

const { t } = useI18n()

const {
  items,
  total,
  selectedFilter,
  filters,
  isLoading,
  isLoadingMore,
  canLoadMore,
  loadMore,
  init
} = useCatalogSuppliers()

// Selected supplier for map highlighting
const selectedSupplierId = ref<string>()
const listMapRef = ref<{ flyToItem: (uuid: string) => void } | null>(null)

const onSelectSupplier = (uuid: string) => {
  selectedSupplierId.value = uuid
}

await init()

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