<script setup lang="ts">
import { ref, provide, onMounted, onUnmounted } from "vue";

const GrDropDown = ref<HTMLElement | null>(null);
const dropdownOpen = ref(false);
const dropdownSubState = ref<{ [key: string]: boolean }>({});

function toggleDropdown() {
  dropdownOpen.value = !dropdownOpen.value;
}

function setDropdownSubState(key: string): void {
  for (const k in dropdownSubState.value) {
    if (k !== key) {
      dropdownSubState.value[k] = false;
    }
  }
  dropdownSubState.value[key as string] = !dropdownSubState.value[key as string];
}

function closeIfOutsideDropDown(event: Event) {
  if (GrDropDown.value && !GrDropDown.value.contains(event.target as Node)) {
    dropdownOpen.value = false;
  }
}

provide("dropdownValue", dropdownOpen);
provide("toggleDropdown", toggleDropdown);
provide("dropdownSubState", dropdownSubState.value);
provide("setDropdownSubState", setDropdownSubState);

onMounted(async () => {
  document.addEventListener("click", closeIfOutsideDropDown);
});

onUnmounted(() => {
  document.removeEventListener("click", closeIfOutsideDropDown);
});
</script>

<template>
  <div ref="GrDropDown" class="gr-dropdown">
    <slot />
  </div>
</template>

<style scoped lang="scss">
.gr-dropdown {
  height: min-content;
  user-select: none;
  min-width: min-content;
  position: relative;
}
</style>
