<template>
  <div class="c-modal" :class="{ 'is-open': isOpen }" @keydown.esc="handleClose" role="dialog" aria-modal="true"
    data-closable="true">
    <div :class="getModifiersClass('c-modal__dialog', modifiers)" ref="modal-dialog-ref" tabindex="-1">
      <div class="c-modal__header">
        <h2 v-if="title" class="c-modal__title text-truncate">{{ title }}</h2>
        <button type="button" class="js-modal-trigger c-modal__close" @click="handleClose" :aria-label="ariaLabelClose">
          <span class="icon-close" :aria-label="ariaLabelClose"></span>
        </button>
      </div>
      <div class="c-modal__body">
        <slot />
      </div>
      <div class="c-modal__footer" v-if="closeButtonText || $slots.footer">
        <button type="button" v-if="closeButtonText" @click="handleClose" :aria-label="ariaLabelClose"
          class="o-button o-button--secondary me-3 js-modal-trigger">
          {{ closeButtonText }}
        </button>
        <slot name="footer" />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import type { ModifierItems } from './modal.config';
import useComponentModifiers from '../../composable/useComponentModifiers';
import { onMounted, useTemplateRef } from 'vue';

const props = defineProps<{
  title?: string;
  closeButtonText?: string;
  ariaLabelClose?: string;
  isOpen?: boolean;
  modifiers?: ModifierItems;
}>();

const emit = defineEmits<{
  (event: 'close', value: Element): void;
}>();

const { getModifiersClass } = useComponentModifiers();
const modalContentRef = useTemplateRef("modal-dialog-ref");
const ariaLabelClose = props.ariaLabelClose || props.closeButtonText + ' modal'

const handleClose = (event: Event) => {
  const modalElement = (event.target as HTMLElement)?.closest('.c-modal');
  if (modalElement) {
    emit('close', modalElement);
  }
};

onMounted(() => {
  // Focus on modal content when modal is opened
  modalContentRef.value && modalContentRef.value.focus();
});
</script>
