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

  // html bindings
  let modal: HTMLDialogElement;

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

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

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

  onDestroy(cancel);

  // callbacks
  function onModalClose() {
    $popupState?.onClose?.();
    closeTimeoutId = setTimeout(() => ($popupState = 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">{$popupState?.title}</h3>
      <p class="py-4 whitespace-pre-line">{$popupState?.message}</p>
      <button class="btn" class:btn-error={$popupState?.type === 'error'}>Ok</button>
    </div>
  </form>
  <form method="dialog" class="modal-backdrop bg-[rgba(0,0,0,.3)]">
    <button class="!cursor-default">close</button>
  </form>
</dialog>
