<template>
  <div ref="mapContainer" class="w-full" style="height: calc(100dvh - 54px)" />
  <div v-if="!coordsReady" class="p-4 text-center">
    ⏳ Определяем ваше местоположение...
  </div>
</template>

<script setup lang="ts">
import { useGeolocation } from '@vueuse/core'
import { ref, watch } from 'vue'

const props = defineProps<{
  pickupPoints: {
    id: string
    address: string
    position: { latitude: number, longitude: number }
  }[]
}>()

const token = '13f4c06b-cb7e-4eeb-81f1-af52f12587b2'
const mapContainer = ref<HTMLDivElement | null>(null)
const { coords } = useGeolocation()
const coordsReady = ref(false)
const mapInstance = ref<any | null>(null)

const initMap = async (lat: number, lon: number) => {
  if (!window.ymaps) {
    await new Promise<void>((resolve) => {
      const script = document.createElement('script')
      script.src = `https://api-maps.yandex.ru/2.1/?apikey=${token}&lang=ru_RU`
      script.onload = () => resolve()
      document.head.appendChild(script)
    })
  }

  window.ymaps.ready(() => {
    const map = new window.ymaps.Map(mapContainer.value!, {
      center: [lat, lon],
      zoom: 10,
      controls: ['zoomControl'],
    })
    mapInstance.value = map

    props?.pickupPoints?.forEach((point) => {
      const placemark = new window.ymaps.Placemark(
        [point?.position?.latitude, point?.position?.longitude],
        {
          balloonContent: `<strong>${Object.values(point?.position)}</strong>`,
          hintContent: Object.values(point?.position),
        },
        { preset: 'islands#redIcon' },
      )
      map.geoObjects.add(placemark)
    })
  })
}

const centerMap = (lat: number, lon: number) => {
  if (!mapInstance.value)
    return

  mapInstance.value.setCenter([lat, lon], 18)
}

defineExpose({ centerMap })

watch(
  () => coords.value,
  async (val) => {
    if (val.latitude && val.longitude && !coordsReady.value) {
      coordsReady.value = true
      await initMap(val.latitude, val.longitude)
    }
  },
  { deep: true },
)
</script>
