<script setup>
import { Marker, Popup } from "mapbox-gl";
import {} from "vue";
import { onUnmounted, onMounted, defineMapboxPopup, inject, ref, watch } from "#imports";
const props = defineProps({
  popupId: { type: String, required: true },
  options: { type: Object, required: false, default: () => ({}) },
  lnglat: { type: [Object, Array], required: true },
  text: { type: String, required: false, default: void 0 }
});
const popupTemplate = ref(null);
const emit = defineEmits(["open", "close"]);
const markerRef = inject("MarkerRef", null);
const popupRef = ref();
onMounted(() => {
  const popup = defineMapboxPopup(props.popupId, props.options, popupTemplate);
  popupRef.value = popup;
  if (popup) {
    if (props.lnglat) popup?.setLngLat(props.lnglat);
    popup?.on("open", () => {
      emit("open", popup);
    });
    popup?.on("close", () => {
      emit("close", popup);
    });
    if (props.text) popup?.setText(props.text);
  }
  if (markerRef) {
    if (markerRef.value) {
      markerRef.value.setPopup(popup);
    } else {
      watch(markerRef, () => {
        if (markerRef.value) {
          markerRef.value.setPopup(popup);
        }
      });
    }
  }
});
watch(() => props.lnglat, () => {
  if (props.lnglat) popupRef.value?.setLngLat(props.lnglat);
});
watch(() => props.options, () => {
  if (props.options.offset) popupRef.value?.setOffset(props.options.offset);
  if (props.options.maxWidth) popupRef.value?.setMaxWidth(props.options.maxWidth);
});
watch(() => props.text, () => {
  if (props.text) popupRef.value?.setText(props.text);
});
</script>

<template>
  <div
    ref="popupTemplate"
    hidden
  >
    <slot />
  </div>
</template>
