<template>
  <Section variant="plain" paddingY="md">
    <Card>
      <Stack gap="4">
        <Stack direction="row" align="center" justify="between">
          <Heading :level="2">Ключевые хабы и страны</Heading>
          <NuxtLink :to="localePath('/catalog/hubs')">
            <Button variant="secondary" size="small">Смотреть все</Button>
          </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">
              <Card
                v-for="hub in country.hubs"
                :key="hub.uuid"
                padding="sm"
                tone="muted"
              >
                <Stack gap="2">
                  <Stack gap="1">
                    <Text size="base" weight="semibold">{{ hub.name }}</Text>
                    <Text tone="muted">{{ hub.country }}</Text>
                  </Stack>
                  <Text v-if="hub.distance" tone="muted" size="base">{{ hub.distance }}</Text>
                </Stack>
              </Card>
            </Grid>
          </div>
        </Stack>
      </Stack>
    </Card>
  </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[]
}>()

const localePath = useLocalePath()

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

  props.hubs.forEach(hub => {
    const country = hub.country || 'Другие'
    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>
