<template>
  <CatalogPage
    :items="itemsForMap"
    :loading="isLoading"
    map-id="addresses-map"
    point-color="#10b981"
    :selected-id="selectedAddressId"
    v-model:hovered-id="hoveredAddressId"
    @select="onSelectAddress"
  >
    <template #header>
      <NuxtLink :to="localePath('/clientarea/addresses/new')">
        <Button variant="outline" class="w-full">
          <Icon name="lucide:plus" size="16" class="mr-2" />
          {{ t('profileAddresses.actions.add') }}
        </Button>
      </NuxtLink>
    </template>

    <template #card="{ item }">
      <NuxtLink
        :to="localePath(`/clientarea/addresses/${item.uuid}`)"
        class="block"
      >
        <Card padding="sm" interactive>
          <div class="flex flex-col gap-1">
            <Text size="base" weight="semibold" class="truncate">{{ item.name }}</Text>
            <Text tone="muted" size="sm" class="line-clamp-2">{{ item.address }}</Text>
            <div class="flex items-center mt-1">
              <span class="text-lg">{{ isoToEmoji(item.countryCode) }}</span>
            </div>
          </div>
        </Card>
      </NuxtLink>
    </template>

    <template #empty>
      <EmptyState
        icon="📍"
        :title="t('profileAddresses.empty.title')"
        :description="t('profileAddresses.empty.description')"
        :action-label="t('profileAddresses.empty.cta')"
        :action-to="localePath('/clientarea/addresses/new')"
        action-icon="lucide:plus"
      />
    </template>
  </CatalogPage>
</template>

<script setup lang="ts">
definePageMeta({
  layout: 'topnav',
  middleware: ['auth-oidc']
})

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

const {
  items,
  isLoading,
  isoToEmoji,
  init
} = useTeamAddresses()

const selectedAddressId = ref<string>()
const hoveredAddressId = ref<string>()

// Map items for CatalogPage
const itemsForMap = computed(() => {
  return items.value.map(addr => ({
    uuid: addr.uuid,
    name: addr.name,
    address: addr.address,
    latitude: addr.latitude,
    longitude: addr.longitude,
    countryCode: addr.countryCode,
    country: addr.countryCode
  }))
})

const onSelectAddress = (item: any) => {
  selectedAddressId.value = item.uuid
}

await init()
</script>
