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

    <CatalogMap
      ref="mapRef"
      map-id="offers-fullscreen-map"
      :items="itemsWithCoords"
      point-color="#f59e0b"
      @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
} = useCatalogOffers()

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
  const lat = item.locationLatitude
  const lng = item.locationLongitude
  if (lat && lng) {
    mapRef.value?.flyTo(lat, lng, 8)
  }
}

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