<script lang="ts">
  import Button from "./Button.svelte";

  type AppError = {
    message: string;
    stack?: string;
  };

  const { error, onclose } = $props<{
    error: AppError | null;
    onclose: () => void;
  }>();

  let dialogEl: HTMLDialogElement | undefined;

  $effect(() => {
    if (error && !dialogEl?.open) {
      dialogEl?.showModal();
    } else if (!error && dialogEl?.open) {
      dialogEl?.close();
    }
  });
</script>

<dialog bind:this={dialogEl} {onclose}>
  {#if error}
    <div class="modal-box">
      <h3 class="font-bold text-lg text-error">An Error Occurred</h3>
      <div class="py-4">
        <p class="font-semibold">Message:</p>
        <p class="bg-base-200 p-2 rounded">{error.message}</p>
      </div>
      {#if error.stack}
        <div class="mb-4">
          <p class="font-semibold">Stack Trace:</p>
          <pre
            class="bg-base-200 p-2 rounded text-sm overflow-auto max-h-60"><code
              >{error.stack}</code
            ></pre>
        </div>
      {/if}
      <div class="modal-action">
        <Button onclick={onclose} class="btn-primary">OK</Button>
      </div>
    </div>
  {/if}
</dialog>
