<script setup>
import { onBeforeUnmount, onMounted, ref, watch } from 'vue';
import AppIcon from './AppIcon.vue';

/** Replaces window.confirm() for destructive actions. */
const props = defineProps({
    open: { type: Boolean, default: false },
    title: { type: String, default: 'নিশ্চিত?' },
    message: { type: String, default: '' },
    confirmLabel: { type: String, default: 'হ্যাঁ, মুছে ফেলুন' },
    busy: { type: Boolean, default: false },
});

const emit = defineEmits(['confirm', 'cancel']);

const confirmButton = ref(null);

watch(() => props.open, (open) => {
    document.body.style.overflow = open ? 'hidden' : '';
    if (open) setTimeout(() => confirmButton.value?.focus(), 60);
});

function onKeydown(event) {
    if (props.open && event.key === 'Escape') emit('cancel');
}

onMounted(() => document.addEventListener('keydown', onKeydown));
onBeforeUnmount(() => {
    document.removeEventListener('keydown', onKeydown);
    document.body.style.overflow = '';
});
</script>

<template>
    <div class="modal no-print" :class="{ 'is-open': open }" role="dialog" aria-modal="true"
         @mousedown.self="emit('cancel')">
        <div class="modal-box is-confirm">
            <div class="modal-head">
                <span class="head-icon is-danger"><AppIcon name="alert-triangle" :size="18"/></span>
                <h2>{{ title }}</h2>
            </div>

            <div class="confirm-body">
                <p>{{ message }}</p>
                <p class="confirm-note">এটি আর ফেরানো যাবে না।</p>
            </div>

            <div class="modal-foot">
                <button type="button" class="btn" :disabled="busy" @click="emit('cancel')">বাতিল</button>
                <span class="spacer"></span>
                <button ref="confirmButton" type="button" class="btn btn-danger" :disabled="busy"
                        @click="emit('confirm')">
                    <AppIcon :name="busy ? 'rotate' : 'trash'" :size="16" :class="{ 'is-spinning': busy }"/>
                    {{ busy ? 'মুছে ফেলা হচ্ছে…' : confirmLabel }}
                </button>
            </div>
        </div>
    </div>
</template>
