<script lang="ts">
    import * as m from "$lib/paraglide/messages";

    interface ConfirmDialogProps {
        open?: boolean;
        title?: string;
        message?: string;
        confirmText?: string;
        cancelText?: string;
        onconfirm?: () => void;
        oncancel?: () => void;
    }

    let {
        open = $bindable(false),
        title = m.kv_confirm_close_title(),
        message = m.kv_confirm_close_message(),
        confirmText = m.kv_confirm_discard(),
        cancelText = m.kv_confirm_cancel(),
        onconfirm,
        oncancel,
    }: ConfirmDialogProps = $props();

    function handleConfirm() {
        open = false;
        onconfirm?.();
    }

    function handleCancel() {
        open = false;
        oncancel?.();
    }

    function handleKeydown(e: KeyboardEvent) {
        if (e.key === "Escape") handleCancel();
    }
</script>

<svelte:window onkeydown={open ? handleKeydown : undefined} />

{#if open}
    <!-- Backdrop -->
    <div
        class="fixed inset-0 bg-kv-background/50 z-[100]"
        onclick={handleCancel}
        role="button"
        tabindex="-1"
        onkeydown={(e) => e.key === "Enter" && handleCancel()}
    ></div>

    <!-- Dialog -->
    <div
        class="fixed top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 z-[110]
               bg-kv-blue border-4 md:border-8 border-kv-black
               p-4 md:p-6 w-[90vw] max-w-[380px]
               flex flex-col gap-4 items-center text-center"
    >
        <h3
            class="text-xl md:text-2xl text-kv-white uppercase font-kv-body kv-shadow-text"
        >
            {title}
        </h3>
        <p
            class="text-sm md:text-base text-kv-white font-kv-body uppercase kv-shadow-text"
        >
            {message}
        </p>
        <div class="flex gap-3 w-full">
            <button
                onclick={handleCancel}
                class="flex-1 bg-kv-blue border-4 border-black font-kv-body text-kv-white uppercase px-4 py-3 cursor-pointer hover:opacity-80 kv-shadow-button"
            >
                <span class="kv-shadow-text">{cancelText}</span>
            </button>
            <button
                onclick={handleConfirm}
                class="flex-1 bg-kv-yellow border-4 border-black font-kv-body text-black uppercase px-4 py-3 cursor-pointer hover:opacity-80 kv-shadow-button"
            >
                {confirmText}
            </button>
        </div>
    </div>
{/if}
