<script setup>
import { GeolocateControl } from "mapbox-gl";
import { ref, inject, useMapbox, onUnmounted } from "#imports";
const props = defineProps({
  options: { type: Object, required: false, default: () => ({}) },
  position: { type: String, required: false, default: () => "top-right" }
});
const emit = defineEmits(["geolocate", "error", "outofmaxbounds", "trackuserlocationstart", "trackuserlocationend"]);
const mapId = inject("MapID");
if (!mapId) throw "Mapbox Controls must be placed inside a Map component";
const geolocateRef = ref();
useMapbox(mapId, (map) => {
  const geolocate = new GeolocateControl(props.options);
  geolocateRef.value = geolocate;
  map?.addControl(geolocate, props.position);
  geolocate.on("geolocate", () => {
    emit("geolocate", geolocate);
  });
  geolocate.on("error", () => {
    emit("error", geolocate);
  });
  geolocate.on("outofmaxbounds", () => {
    emit("outofmaxbounds", geolocate);
  });
  geolocate.on("trackuserlocationstart", () => {
    emit("trackuserlocationstart", geolocate);
  });
  geolocate.on("trackuserlocationend", () => {
    emit("trackuserlocationend", geolocate);
  });
});
onUnmounted(() => {
  useMapbox(mapId, (map) => {
    if (geolocateRef.value) map.removeControl(geolocateRef.value);
  });
});
</script>

<template>
  <div>
    <slot />
  </div>
</template>
