<script setup lang="ts">
import { ChevronDownIcon, ChevronUpIcon } from '@heroicons/vue/24/outline';
import { vOnClickOutside } from '@vueuse/components';
import { useEventListener } from '@vueuse/core';
import { ref } from 'vue';

const isOpen = ref(false);

useEventListener('keyup', e => {
    if (e.key === 'Escape') {
        isOpen.value = false;
    }
});
</script>

<template>
    <div class="dropdown" :class="{'dropdown-open': isOpen, 'dropdown-close': !isOpen}" v-on-click-outside="() => isOpen = false">
        <button @click="isOpen = !isOpen">
            <slot name="button" />
            <Transition
                enter-active-class="transition-transform"
                enter-from-class="rotate-180"
                leave-active-class="hidden"
                leave-to-class="rotate-180">
                <ChevronDownIcon v-if="!isOpen" class="chevron" />
                <ChevronUpIcon v-else class="chevron" />
            </Transition>
        </button>

        <Transition
            enter-active-class="transition-opacity"
            enter-from-class="opacity-0"
            leave-from-class="transition-opacity"
            leave-to-class="opacity-0">
            <div v-if="isOpen" class="relative">
                <div class="z-10 divide-y rounded-b-md absolute">
                    <slot />
                </div>
            </div>
        </Transition>
    </div>
</template>

<style scoped>
@reference "tailwindcss";

.chevron {
    @apply w-4 h-4 ms-1;
}
</style>
