<script setup>
import { default as mapboxgl } from "mapbox-gl";
import { ref, onMounted, watch, initMapbox } from "#imports";
import "@mapbox/mapbox-gl-geocoder/dist/mapbox-gl-geocoder.css";
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: () => ({}) }
});
const emit = defineEmits(["update:modelValue", "change", "keydown"]);
const geocoderInput = ref();
const customInputContainer = ref();
const geocoderRef = ref();
onMounted(async () => {
  await geocoderPromise;
  const geocoder = new MapboxGeocoder({
    //@ts-ignore
    accessToken: mapboxgl.accessToken,
    //@ts-ignore
    mapboxgl,
    //@ts-ignore
    ...props.options
  });
  geocoderRef.value = geocoder;
  if (geocoderInput.value) geocoder.addTo(geocoderInput.value);
  const defaultInput = geocoder._inputEl;
  const defaultContainer = geocoder.container;
  const keyDown = geocoder._typeahead.handleKeyDown.bind(geocoder._typeahead);
  defaultInput.addEventListener("change", (e) => {
    emit("change", e);
  });
  defaultInput.addEventListener("keydown", (e) => {
    emit("keydown", e);
  });
  geocoder.on("result", (e) => {
    emit("update:modelValue", e.result);
  });
  geocoder.on("clear", () => {
    emit("update:modelValue", void 0);
  });
  const customInputs = customInputContainer.value?.querySelectorAll("input");
  if (customInputs) {
    customInputs.forEach((input) => {
      geocoder.on("result", (e) => {
        input.value = e.result.place_name;
      });
      geocoder.on("clear", () => {
        input.value = "";
      });
      defaultInput.addEventListener("change", (e) => {
        input.value = e.target?.value;
      });
      defaultInput.addEventListener("keydown", (e) => {
        input.value = e.target?.value;
      });
      input.addEventListener("input", (e) => {
        geocoder.setInput(e.target?.value);
      });
      input.addEventListener("keydown", keyDown);
    });
  }
});
watch(() => props.modelValue, () => {
  geocoderRef.value?.setInput(props.modelValue?.place_name || "");
});
</script>

<template>
  <div ref="geocoderInput" />
  <div ref="customInputContainer">
    <slot />
  </div>
</template>
