<template>
  <div ref="mapContainer" class="w-full" style="height: calc(100dvh - 54px)" />
  {{ coords }}
  {{ locatedAt }}
</template>

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

const props = defineProps<{
  pickupPoints: {
    id: string
    address: string
    location: { lat: number, lon: number }
  }[]
}>()

const { coords, locatedAt } = useGeolocation()

const token = '13f4c06b-cb7e-4eeb-81f1-af52f12587b2'

const mapContainer = ref<HTMLDivElement | null>(null)

const loadYandexMap = async () => {
  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: [coords.value.latitude, coords.value.longitude],
      zoom: 10,
      controls: ['zoomControl'],
    })

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

onMounted(async () => {
  await loadYandexMap()
})
</script>
