<template>
  <div class="flex flex-col flex-1 min-h-0">
    <!-- Header -->
    <div class="py-4">
      <PageHeader :title="t('catalogHubsSection.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="selectedHubId"
      map-id="hubs-map"
      point-color="#10b981"
      @select-item="onSelectHub"
    >
      <template #list>
        <Stack gap="4">
          <CatalogFilters :filters="filters" v-model="selectedFilter" />

          <div v-for="country in itemsByCountry" :key="country.name" class="space-y-3">
            <Text weight="semibold">{{ country.name }}</Text>
            <Stack gap="3">
              <HubCard
                v-for="hub in country.hubs"
                :key="hub.uuid"
                :hub="hub"
                :class="{ 'ring-2 ring-primary': hub.uuid === selectedHubId }"
                @click="onSelectHub(hub.uuid)"
              />
            </Stack>
          </div>

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

          <Stack v-if="items.length === 0" align="center" gap="2">
            <Text tone="muted">{{ t('catalogHubsSection.empty.no_hubs') }}</Text>
          </Stack>
        </Stack>
      </template>
    </ListMapLayout>
  </div>
</template>

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

const { t } = useI18n()

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

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

const onSelectHub = (uuid: string) => {
  selectedHubId.value = uuid
}

await init()

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