<script setup>
import { default as mapboxgl } from "mapbox-gl";
import { ref, onMounted, useMapbox, inject, onUnmounted, initMapbox } from "#imports";
import "@mapbox/mapbox-gl-geocoder/dist/mapbox-gl-geocoder.css";
const emit = defineEmits(["update:modelValue", "clear", "loading", "results", "result", "error"]);
async function initGeocoder() {
  if (import.meta.client) {
    const MapboxGeocoder2 = await import("https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-geocoder/v5.0.0/mapbox-gl-geocoder.min.js");
    initMapbox();
  }
}
const geocoderPromise = initGeocoder();
const props = defineProps({
  modelValue: { type: null, required: false, default: void 0 },
  options: { type: Object, required: false, default: () => ({}) },
  position: { type: String, required: false, default: () => "top-right" }
});
const geocoderRef = ref();
const mapId = inject("MapID");
const containerRef = ref();
if (mapId) {
  useMapbox(mapId, async (map) => {
    await geocoderPromise;
    const geocoder = new MapboxGeocoder({
      //@ts-ignore
      accessToken: mapboxgl.accessToken,
      //@ts-ignore
      mapboxgl,
      ...props.options
    });
    geocoderRef.value = geocoder;
    map?.addControl(geocoder, props.position);
    geocoder.on("clear", () => {
      emit("update:modelValue", void 0);
      emit("clear");
    });
    geocoder.on("loading", (q) => {
      emit("loading", q);
    });
    geocoder.on("results", (r) => {
      emit("results", r.features);
    });
    geocoder.on("result", (r) => {
      emit("update:modelValue", r.result);
      emit("result", r.result);
    });
    geocoder.on("error", (e) => {
      emit("error", e);
    });
  });
  onUnmounted(() => {
    useMapbox(mapId, (map) => {
      if (geocoderRef.value) map?.removeControl(geocoderRef.value);
    });
  });
} else {
  onMounted(() => {
    if (containerRef.value) {
      const geocoder = new MapboxGeocoder({
        //@ts-ignore
        accessToken: mapboxgl.accessToken,
        //@ts-ignore
        mapboxgl,
        ...props.options
      });
      geocoderRef.value = geocoder;
      geocoder.addTo(containerRef.value);
    }
  });
}
defineExpose({
  geocoder: geocoderRef
});
</script>

<template>
  <div ref="containerRef">
    <slot />
  </div>
</template>
