<script lang="ts">
    import type { Snippet } from "svelte";

    interface Props {
        showModal: boolean;
        header: Snippet;
        children: Snippet;
        actionButtons?: Snippet;
        cancelFn?: () => void;
        okFn: () => Promise<boolean>;
        oncloseFn?: () => void;
        okButtonText?: string;
        [key: string]: unknown;
        width?: string;
        height?: string;
    }

    let {
        showModal = $bindable(),
        header,
        children,
        cancelFn,
        okFn,
        oncloseFn,
        actionButtons,
        okButtonText = "Ok",
        width,
        height
    }: Props = $props();

    let dialog: HTMLDialogElement | undefined = $state(); // HTMLDialogElement

    $effect(() => {
        if (showModal) dialog?.showModal();
    });
</script>

<!-- svelte-ignore a11y_click_events_have_key_events, a11y_no_noninteractive_element_interactions -->
<dialog
    bind:this={dialog}
    onclose={() => {
        showModal = false;
        if (oncloseFn) oncloseFn();
    }}
    onclick={(e) => {
        if (e.target === dialog) dialog.close();
    }}
    class="rounded-md"
    style:width
    style:height
>
    <div class="flex h-full flex-col gap-4 p-4">
        {@render header?.()}
        <div class="grow overflow-y-auto">
            {@render children?.()}
        </div>
        <!-- <div class="grow"></div> -->
        <!-- svelte-ignore a11y_autofocus -->
        <div class="flex justify-end gap-4">
            {@render actionButtons?.()}
            <button
                autofocus
                onclick={() => {
                    dialog?.close();
                    if (cancelFn) cancelFn();
                }}
                class="btn">Abbrechen</button
            >
            <button
                autofocus
                onclick={async () => {
                    if (await okFn()) {
                        dialog?.close();
                    }
                }}
                class="btn min-w-[64px]">{okButtonText}</button
            >
        </div>
    </div>
</dialog>

<style>
    dialog {
        position: fixed;
        top: 50%;
        left: 50%;
        /* Move it back 50% relative to self */
        -webkit-transform: translateX(-50%) translateY(-50%);
        -moz-transform: translateX(-50%) translateY(-50%);
        -ms-transform: translateX(-50%) translateY(-50%);
        transform: translateX(-50%) translateY(-50%);
    }
    dialog::backdrop {
        background: rgba(0, 0, 0, 0.5);
    }
</style>
