<template>
  <CatalogPage
    :items="items"
    :loading="isLoading"
    :total-count="total"
    map-id="hubs-map"
    point-color="#10b981"
    use-server-clustering
    :selected-id="selectedHubId"
    v-model:hovered-id="hoveredHubId"
    @select="onSelectHub"
  >
    <template #searchBar="{ displayedCount, totalCount }">
      <CatalogSearchBar
        v-model:search-query="searchQuery"
        :active-filters="activeFilterBadges"
        :displayed-count="displayedCount"
        :total-count="totalCount"
        @remove-filter="onRemoveFilter"
        @search="onSearch"
      >
        <template #filters>
          <div class="p-2 space-y-3">
            <div>
              <div class="text-xs font-semibold mb-1 text-base-content/70">{{ t('catalogHubsSection.filters.transport') }}</div>
              <ul class="menu menu-compact">
                <li v-for="filter in filters" :key="filter.id">
                  <a
                    :class="{ active: selectedFilter === filter.id }"
                    @click="selectedFilter = filter.id"
                  >
                    {{ filter.label }}
                  </a>
                </li>
              </ul>
            </div>
            <div class="divider my-0"></div>
            <div>
              <div class="text-xs font-semibold mb-1 text-base-content/70">{{ t('catalogHubsSection.filters.country') }}</div>
              <ul class="menu menu-compact max-h-48 overflow-y-auto">
                <li v-for="filter in countryFilters" :key="filter.id">
                  <a
                    :class="{ active: selectedCountry === filter.id }"
                    @click="selectedCountry = filter.id"
                  >
                    {{ filter.label }}
                  </a>
                </li>
              </ul>
            </div>
          </div>
        </template>
      </CatalogSearchBar>
    </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"
        hide-counter
        @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>()

// Search bar
const searchQuery = ref('')

// Active filter badges (non-default filters shown as badges)
const activeFilterBadges = computed(() => {
  const badges: { id: string; label: string }[] = []
  if (selectedFilter.value !== 'all') {
    const filter = filters.value.find(f => f.id === selectedFilter.value)
    if (filter) badges.push({ id: `transport:${filter.id}`, label: filter.label })
  }
  if (selectedCountry.value !== 'all') {
    const filter = countryFilters.value.find(f => f.id === selectedCountry.value)
    if (filter) badges.push({ id: `country:${filter.id}`, label: filter.label })
  }
  return badges
})

// Remove filter badge
const onRemoveFilter = (id: string) => {
  if (id.startsWith('transport:')) {
    selectedFilter.value = 'all'
  } else if (id.startsWith('country:')) {
    selectedCountry.value = 'all'
  }
}

// Search handler (for future use)
const onSearch = () => {
  // TODO: Implement search by hub name
}

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>
