<template>
  <component
    :is="linkable ? NuxtLink : 'div'"
    :to="linkable ? resolvedLink : undefined"
    class="block"
    :class="{ 'cursor-pointer': selectable }"
    @click="selectable && $emit('select')"
    @mouseenter="$emit('hover', true)"
    @mouseleave="$emit('hover', false)"
  >
    <Card
      padding="small"
      :interactive="linkable || selectable"
      :class="[
        isSelected && 'ring-2 ring-primary ring-offset-2'
      ]"
    >
      <div class="flex flex-col gap-1">
        <!-- Title -->
        <Text size="base" weight="semibold" class="truncate">{{ hub.name }}</Text>
        <!-- Country left, distance right -->
        <div class="flex items-center justify-between">
          <Text tone="muted" size="sm">
            {{ countryFlag }} {{ hub.country || t('catalogMap.labels.country_unknown') }}
          </Text>
          <span v-if="distanceLabel" class="badge badge-neutral badge-dash text-xs">
            {{ distanceLabel }}
          </span>
        </div>
        <!-- Transport icons bottom -->
        <div v-if="hub.transportTypes?.length" class="flex items-center gap-1 pt-1">
          <Icon v-if="hasTransport('auto')" name="lucide:truck" size="14" class="text-base-content/50" />
          <Icon v-if="hasTransport('rail')" name="lucide:train-front" size="14" class="text-base-content/50" />
          <Icon v-if="hasTransport('sea')" name="lucide:ship" size="14" class="text-base-content/50" />
          <Icon v-if="hasTransport('air')" name="lucide:plane" size="14" class="text-base-content/50" />
        </div>
      </div>
    </Card>
  </component>
</template>

<script setup lang="ts">
import { NuxtLink } from '#components'

interface Hub {
  uuid?: string | null
  name?: string | null
  country?: string | null
  countryCode?: string | null
  distance?: string
  distanceKm?: number | null
  transportTypes?: (string | null)[] | null
}

const props = defineProps<{
  hub: Hub
  selectable?: boolean
  isSelected?: boolean
  linkTo?: string
}>()

defineEmits<{
  (e: 'select'): void
  (e: 'hover', hovered: boolean): void
}>()

const localePath = useLocalePath()
const { t } = useI18n()

const linkable = computed(() => !props.selectable && !!(props.linkTo || props.hub.uuid))
const resolvedLink = computed(() => props.linkTo || localePath(`/catalog/hubs/${props.hub.uuid}`))

// ISO code to emoji flag
const isoToEmoji = (code: string): string => {
  return code.toUpperCase().split('').map(char => String.fromCodePoint(0x1F1E6 - 65 + char.charCodeAt(0))).join('')
}

const countryFlag = computed(() => {
  if (props.hub.countryCode) {
    return isoToEmoji(props.hub.countryCode)
  }
  return '🌍'
})

const hasTransport = (type: string) => props.hub.transportTypes?.some(t => t === type)
const distanceLabel = computed(() => {
  if (props.hub.distance) return props.hub.distance
  if (props.hub.distanceKm != null) return `${Math.round(props.hub.distanceKm)} km`
  return ''
})
</script>
