<script lang="ts">
  import { confirmPopupState } from '@components/popup/ConfirmPopup.ts';
  import { onDestroy } from 'svelte';

  // html bindings
  let modal: HTMLDialogElement;

  // state
  let closeTimeoutId = $state(-1);

  // lifecycle
  const cancel = confirmPopupState.subscribe((value) => {
    if (!value) return;

    clearTimeout(closeTimeoutId);
    modal.show();
  });

  onDestroy(cancel);

  // callbacks
  function onModalClose() {
    closeTimeoutId = setTimeout(() => ($confirmPopupState = null), 300);
  }
</script>

<dialog class="modal" bind:this={modal} onclose={onModalClose}>
  <form method="dialog" class="modal-box">
    <button class="btn btn-sm btn-circle btn-ghost absolute right-2 top-2">✕</button>
    <div>
      <h3 class="text-lg font-geist">{$confirmPopupState?.title}</h3>
      <p class="py-4 whitespace-pre-line">{$confirmPopupState?.message}</p>
      <button class="btn" onclick={() => $confirmPopupState?.onConfirm()}>Ok</button>
      <button class="btn">Abbrechen</button>
    </div>
  </form>
  <form method="dialog" class="modal-backdrop bg-[rgba(0,0,0,.3)]">
    <button class="!cursor-default">close</button>
  </form>
</dialog>
