<script setup>
import { computed, onMounted, onUnmounted, ref } from "vue";

const props = defineProps({
    align: {
        type: String,
        default: "right",
    },
    width: {
        type: String,
        default: "48",
    },
    maxHeight: {
        type: String,
        default: "400",
    },
    contentClasses: {
        type: Array,
        default: () => ["py-1", "bg-white"],
    },
});

let open = ref(false);

const closeOnEscape = (e) => {
    if (open.value && e.key === "Escape") {
        open.value = false;
    }
};

onMounted(() => document.addEventListener("keydown", closeOnEscape));
onUnmounted(() => document.removeEventListener("keydown", closeOnEscape));

const widthClass = computed(() => {
    return {
        48: "max-w-48 w-full",
        210: "w-[215px]",
        400: "max-w-[400px] w-full",
        full: "w-full",
    }[props.width.toString()];
});

const heightClass = computed(() => {
    return {
        400: "max-h-[400px]",
        800: "max-h-[800px]",
    }[props.maxHeight.toString()];
});

const alignmentClasses = computed(() => {
    if (props.align === "left") {
        return "origin-top-left left-0";
    }

    if (props.align === "right") {
        return "origin-top-right right-0";
    }

    return "origin-top";
});
</script>

<template>
    <div class="">
        <div @click="open = !open">
            <slot name="trigger" />
        </div>

        <!-- Full Screen Dropdown Overlay -->
        <div v-show="open" class="fixed inset-0 z-40" @click="open = false" />

        <transition
            enter-active-class="transition duration-200 ease-out"
            enter-from-class="transform scale-95 opacity-0"
            enter-to-class="transform scale-100 opacity-100"
            leave-active-class="transition duration-75 ease-in"
            leave-from-class="transform scale-100 opacity-100"
            leave-to-class="transform scale-95 opacity-0"
        >
            <div
                v-show="open"
                :class="[widthClass, alignmentClasses, heightClass]"
                class="absolute z-50 mt-2 overflow-y-auto rounded-md shadow-lg"
                style="display: none"
                @click="open = false"
            >
                <div
                    :class="contentClasses"
                    class="rounded-md ring-1 ring-gray-200 ring-opacity-5"
                >
                    <slot name="content" />
                </div>
            </div>
        </transition>
    </div>
</template>
