<template>
  <NuxtLayout name="map">
    <template #sidebar>
      <CatalogMapSidebar
        :title="t('profileAddresses.header.title')"
        :back-link="localePath('/clientarea/addresses')"
        :back-label="t('catalogMap.actions.list_view')"
        :items-count="items.length"
        :loading="isLoading"
        :empty-text="t('profileAddresses.empty.title')"
      >
        <template #cards>
          <Card
            v-for="addr in items"
            :key="addr.uuid"
            padding="small"
            interactive
            :class="{ 'ring-2 ring-primary': selectedItemId === addr.uuid }"
            @click="selectItem(addr)"
          >
            <div class="flex flex-col gap-1">
              <div class="flex items-center justify-between">
                <Text size="base" weight="semibold" class="truncate">{{ addr.name }}</Text>
                <span class="text-lg">{{ isoToEmoji(addr.countryCode) }}</span>
              </div>
              <Text tone="muted" size="sm" class="line-clamp-2">{{ addr.address }}</Text>
            </div>
          </Card>
        </template>
      </CatalogMapSidebar>
    </template>

    <CatalogMap
      ref="mapRef"
      map-id="addresses-fullscreen-map"
      :items="itemsWithCoords"
      point-color="#3b82f6"
      @select-item="onMapSelectItem"
    />
  </NuxtLayout>
</template>

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

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

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

await init()

const mapRef = ref<{ flyTo: (lat: number, lng: number, zoom?: number) => void } | null>(null)
const selectedItemId = ref<string | null>(null)

const selectItem = (item: { uuid?: string | null; latitude?: number | null; longitude?: number | null }) => {
  if (item.uuid) {
    selectedItemId.value = item.uuid
    if (item.latitude && item.longitude) {
      mapRef.value?.flyTo(item.latitude, item.longitude, 8)
    }
  }
}

const onMapSelectItem = (uuid: string) => {
  selectedItemId.value = uuid
}
</script>
