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

const dropdownSubState = inject<{ [key: string]: boolean }>("dropdownSubState");
// eslint-disable-next-line no-unused-vars
const setDropdownSubState = inject<(key: string) => void>("setDropdownSubState");

if (!dropdownSubState) {
  throw new Error("Dropdown state not provided");
}
if (!setDropdownSubState) {
  throw new Error("setDropdownSubState not provided");
}

const id = `dropdown-sub-${Math.random().toString(36).substr(2, 9)}`;

const dropdownSubOpen = ref(dropdownSubState[id] || false);

watchEffect(() => {
  dropdownSubOpen.value = !!dropdownSubState[id];
});

function toggleSubDropdown() {
  if (setDropdownSubState) {
    setDropdownSubState(id);
  }
}

provide("dropdownSubOpen", dropdownSubOpen);
provide("toggleSubDropdown", toggleSubDropdown);
</script>

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

<style scoped lang="scss">
.gr-dropdown-sub {
  width: var(--w-full);
  position: relative;
}
</style>
