<template>
  <NuxtLayout name="map">
    <template #sidebar>
      <CatalogMapSidebar
        :title="t('catalogSuppliersSection.header.title')"
        :back-link="localePath('/catalog/suppliers')"
        :back-label="t('catalogMap.actions.list_view')"
        :items-count="items.length"
        :filters="filters"
        :selected-filter="selectedFilter"
        :loading="isLoading"
        :empty-text="t('catalogMap.empty.suppliers')"
        @update:selected-filter="selectedFilter = $event"
      >
        <template #cards>
          <SupplierCard
            v-for="supplier in items"
            :key="supplier.uuid"
            :supplier="supplier"
            selectable
            :is-selected="selectedItemId === supplier.uuid"
            @select="selectItem(supplier)"
          />
        </template>
      </CatalogMapSidebar>
    </template>

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

<script setup lang="ts">
definePageMeta({
  layout: false
})

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

const {
  items,
  selectedFilter,
  filters,
  isLoading,
  itemsWithCoords,
  init
} = useCatalogSuppliers()

await init()

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

const selectItem = (item: any) => {
  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>
