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

const props = defineProps({
    align: {
        default: 'right',
        type: String
    },
    contentClasses: {
        default: () => [
            'pt-1',
            '!bg-white dark:!bg-primary-d !text-gray-800 dark:!text-primary-dt'
        ],
        type: Array
    },
    width: {
        default: '48',
        type: String
    }
});

const 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': 'w-48',
        '52': 'w-52',
        '56': 'w-56',
        '60': 'w-60',
        '64': 'w-64',
        '72': 'w-52 md:w-72',
    }[props.width.toString()];
});

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

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

    if (props.align === 'icon') {
        const size = {
            '48': '-right-20',
            '52': '-right-22',
            '56': '-right-24',
            '60': '-right-26',
            '64': '-right-28',
            '72': '-right-36',
        }[props.width.toString()];

        return `origin-top-right ${size}`;
    }

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

<template>
    <div class="relative">
        <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 ease-out duration-200"
            enter-from-class="transform opacity-0 scale-95"
            enter-to-class="transform opacity-100 scale-100"
            leave-active-class="transition ease-in duration-75"
            leave-from-class="transform opacity-100 scale-100"
            leave-to-class="transform opacity-0 scale-95"
        >
            <div
                v-show="open"
                class="absolute z-[1000] mt-2 rounded-t-md shadow-lg"
                :class="[widthClass, alignmentClasses]"
                style="display: none;"
                @click="open = false"
            >
                <div class="rounded-sm ring-1 ring-black/5" :class="contentClasses">
                    <slot name="content" />
                </div>
            </div>
        </transition>
    </div>
</template>
