<template>
  <Section variant="plain" paddingY="md">
    <Stack gap="4">
      <Stack direction="row" align="center" justify="between">
        <Heading :level="2">{{ t('catalogHubsSection.header.title') }}</Heading>
        <NuxtLink
          :to="localePath('/catalog?select=hub')"
          class="btn btn-sm btn-ghost"
        >
          <span>{{ t('catalogHubsSection.actions.view_all') }}</span>
          <Icon name="lucide:arrow-right" size="16" />
        </NuxtLink>
      </Stack>

      <Stack gap="6">
        <div v-for="country in hubsByCountry" :key="country.name">
          <Text weight="semibold" class="mb-3">{{ country.name }}</Text>
          <Grid :cols="1" :md="2" :lg="3" :gap="4">
            <HubCard
              v-for="(hub, index) in country.hubs"
              :key="hub.uuid ?? index"
              :hub="hub"
            />
          </Grid>
        </div>

        <Stack v-if="totalHubs > 0" direction="row" align="center" justify="between">
          <Text tone="muted">
            {{ t('common.pagination.showing', { shown: hubs.length, total: totalHubs }) }}
          </Text>
          <Button v-if="canLoadMore" variant="outline" @click="loadMore">
            {{ t('common.actions.load_more') }}
          </Button>
        </Stack>
      </Stack>
    </Stack>
  </Section>
</template>

<script setup lang="ts">
interface Hub {
  uuid?: string | null
  name?: string | null
  country?: string | null
  latitude?: number | null
  longitude?: number | null
  distance?: string
}

const props = defineProps<{
  hubs: Hub[]
  total?: number
  canLoadMore?: boolean
  onLoadMore?: () => void
}>()

const localePath = useLocalePath()
const { t } = useI18n()
const totalHubs = computed(() => props.total ?? props.hubs.length)
const canLoadMore = computed(() => props.canLoadMore ?? false)
const loadMore = () => {
  props.onLoadMore?.()
}

const hubsByCountry = computed(() => {
  const grouped = new Map<string, Hub[]>()

  props.hubs.forEach(hub => {
    const country = hub.country || 'Other'
    if (!grouped.has(country)) {
      grouped.set(country, [])
    }
    grouped.get(country)!.push(hub)
  })

  return Array.from(grouped.entries())
    .map(([name, hubs]) => ({ name, hubs }))
    .sort((a, b) => a.name.localeCompare(b.name))
})
</script>
