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

    <CatalogMap
      ref="mapRef"
      map-id="hubs-fullscreen-map"
      :items="itemsWithCoords"
      point-color="#10b981"
      @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
} = useCatalogHubs()

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>
