<script setup>
import { inject, useTemplateRef, watch } from "vue";
import { bindGoogleMapsEvents, MAP_INJECTION_KEY, MARKER_INJECTION_KEY, useGoogleMapsResource } from "./useGoogleMapsResource";
const props = defineProps({
  options: { type: null, required: false }
});
const emit = defineEmits(["close", "closeclick", "content_changed", "domready", "headercontent_changed", "headerdisabled_changed", "position_changed", "visible", "zindex_changed"]);
defineSlots();
const infoWindowEvents = [
  "close",
  "closeclick",
  "content_changed",
  "domready",
  "headercontent_changed",
  "headerdisabled_changed",
  "position_changed",
  "visible",
  "zindex_changed"
];
const mapContext = inject(MAP_INJECTION_KEY, void 0);
const markerContext = inject(MARKER_INJECTION_KEY, void 0);
const infoWindowContainer = useTemplateRef("info-window-container");
let gmpClickHandler;
let isOpen = false;
const infoWindow = useGoogleMapsResource({
  ready: () => !!infoWindowContainer.value,
  create({ mapsApi, map }) {
    const iw = new mapsApi.InfoWindow({
      content: infoWindowContainer.value,
      ...props.options
    });
    iw.addListener("closeclick", () => {
      isOpen = false;
    });
    iw.addListener("close", () => {
      isOpen = false;
    });
    bindGoogleMapsEvents(iw, emit, { noPayload: infoWindowEvents });
    const toggleOpen = (anchor) => {
      if (isOpen) {
        iw.close();
        isOpen = false;
      } else {
        mapContext?.activateInfoWindow(iw);
        iw.open({ anchor, map });
        isOpen = true;
      }
    };
    if (markerContext?.advancedMarkerElement.value) {
      const ame = markerContext.advancedMarkerElement.value;
      ame.gmpClickable = true;
      gmpClickHandler = () => toggleOpen(ame);
      ame.addEventListener("gmp-click", gmpClickHandler);
    } else {
      iw.setPosition(props.options?.position);
      iw.open(map);
      isOpen = true;
    }
    return iw;
  },
  cleanup(iw, { mapsApi }) {
    if (gmpClickHandler && markerContext?.advancedMarkerElement.value) {
      markerContext.advancedMarkerElement.value.removeEventListener("gmp-click", gmpClickHandler);
      gmpClickHandler = void 0;
    }
    mapsApi.event.clearInstanceListeners(iw);
    iw.close();
    isOpen = false;
  }
});
watch(() => props.options, (options) => {
  if (infoWindow.value && options) {
    infoWindow.value.setOptions(options);
  }
}, { deep: true });
</script>

<template>
  <div class="info-window-container">
    <div ref="info-window-container">
      <slot />
    </div>
  </div>
</template>

<style scoped>
.info-window-container{display:none}
</style>
