<script lang="ts">
    import * as m from "$lib/paraglide/messages";
    import { KvButton } from "$lib/components/kuldvillak/ui";
    import { trapFocus } from "$lib/utils/focusTrap";

    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"
        use:trapFocus
    >
        <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">
            <KvButton
                variant="primary"
                onclick={handleCancel}
                size="md"
                class="flex-1"
            >
                {cancelText}
            </KvButton>
            <KvButton
                variant="secondary"
                onclick={handleConfirm}
                size="md"
                class="flex-1"
            >
                {confirmText}
            </KvButton>
        </div>
    </div>
{/if}
