<script setup>
import { computed, onBeforeUnmount, onMounted, ref, toRef, watch } from 'vue'
import { useFocusTrap } from '@/composables/useFocusTrap'

const props = defineProps({
  open: Boolean,
  title: String,
  titleId: { type: String, default: 'modal-title' },
})

const emit = defineEmits(['close'])
const modalRef = ref(null)
const isActive = computed(() => props.open)

useFocusTrap(modalRef, isActive)

function onKeydown(e) {
  if (e.key === 'Escape') emit('close')
}

onMounted(() => document.addEventListener('keydown', onKeydown))
onBeforeUnmount(() => document.removeEventListener('keydown', onKeydown))

watch(toRef(props, 'open'), (open) => {
  document.body.style.overflow = open ? 'hidden' : ''
}, { immediate: true })

onBeforeUnmount(() => {
  document.body.style.overflow = ''
})
</script>

<template>
  <Teleport to="body">
    <div v-if="open" class="fixed inset-0 z-50 flex items-end justify-center p-4 sm:items-center">
      <div
        class="absolute inset-0 bg-black/50 backdrop-blur-sm"
        aria-hidden="true"
        @click="$emit('close')"
      />
      <div
        ref="modalRef"
        role="dialog"
        aria-modal="true"
        :aria-labelledby="title ? titleId : undefined"
        tabindex="-1"
        class="relative z-10 max-h-[calc(100svh-2rem)] w-full max-w-md overflow-y-auto rounded-lg bg-white p-8 shadow-lg dark:bg-gray-800"
      >
        <h2 v-if="title" :id="titleId" class="mb-4 text-lg font-semibold dark:text-white">{{ title }}</h2>
        <slot />
      </div>
    </div>
  </Teleport>
</template>
