<template>
  <Teleport to="body">
    <div class="modal fade" :id="id" tabindex="-1" aria-hidden="true" ref="modalRef">
      <div class="modal-dialog modal-dialog-centered" :class="sizeClass">
        <div class="modal-content">
          <div class="modal-header border-0 pb-0">
             <slot name="header">
                <h5 class="modal-title fw-bold" style="color: var(--text-heading);">{{ title }}</h5>
             </slot>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
          </div>
          <div class="modal-body">
            <slot name="body"></slot>
          </div>
          <div class="modal-footer border-0 pt-0" v-if="$slots.footer">
            <slot name="footer"></slot>
          </div>
        </div>
      </div>
    </div>
  </Teleport>
</template>

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

const props = defineProps({
  id: {
    type: String,
    required: true
  },
  title: {
    type: String,
    default: ''
  },
  size: {
      type: String,
      default: '' // 'modal-sm', 'modal-lg', 'modal-xl'
  }
});

const emit = defineEmits(['close', 'opened', 'closed']);

const modalRef = ref(null);
let bsModal = null;
const sizeClass = props.size || '';

const show = () => {
    bsModal?.show();
};

const hide = () => {
    bsModal?.hide();
};

onMounted(() => {
    bsModal = new Modal(modalRef.value);
    
    modalRef.value.addEventListener('shown.bs.modal', () => {
        emit('opened');
    });

    modalRef.value.addEventListener('hidden.bs.modal', () => {
        emit('closed');
        emit('close');
    });
});

onUnmounted(() => {
    bsModal?.dispose();
});

defineExpose({ show, hide });
</script>

