<template>
  <CatalogPage
    :items="items"
    :loading="isLoading"
    map-id="hubs-map"
    point-color="#10b981"
    :selected-id="selectedHubId"
    v-model:hovered-id="hoveredHubId"
    @select="onSelectHub"
  >
    <template #filters>
      <div class="flex gap-2">
        <CatalogFilterSelect :filters="filters" v-model="selectedFilter" />
        <CatalogFilterSelect :filters="countryFilters" v-model="selectedCountry" />
      </div>
    </template>

    <template #card="{ item }">
      <template v-for="country in getCountryForHub(item)" :key="country.name">
        <Text v-if="isFirstInCountry(item)" weight="semibold" class="mb-2">{{ country.name }}</Text>
      </template>
      <HubCard :hub="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('catalogHubsSection.empty.no_hubs') }}</Text>
    </template>
  </CatalogPage>
</template>

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

const { t } = useI18n()

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

// Selected/hovered hub for map highlighting
const selectedHubId = ref<string>()
const hoveredHubId = ref<string>()

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

// Helper to get country for hub
const getCountryForHub = (hub: any) => {
  return itemsByCountry.value.filter(c => c.hubs.some(h => h.uuid === hub.uuid))
}

// Check if this hub is first in its country group
const isFirstInCountry = (hub: any) => {
  for (const country of itemsByCountry.value) {
    if (country.hubs[0]?.uuid === hub.uuid) return true
  }
  return false
}

await init()

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