<script lang="ts">
  import { AlertTriangle, LoaderCircle, RotateCcw, X } from "@lucide/svelte";
  import type { GitFileStatus } from "../types";

  interface Props {
    file: GitFileStatus;
    staged: boolean;
    scope: "file" | "hunk";
    isBusy: boolean;
    onConfirm: () => void | Promise<void>;
    onClose: () => void;
  }

  let {
    file,
    staged = false,
    scope = "file",
    isBusy = false,
    onConfirm = () => {},
    onClose = () => {},
  }: Props = $props();

  let targetPath = $derived(file.old_path ? `${file.old_path} -> ${file.path}` : file.path);
  let title = $derived(scope === "hunk" ? "Discard hunk?" : "Discard file changes?");
  let scopeLabel = $derived(scope === "hunk" ? "Selected hunk" : "File changes");
  let sourceLabel = $derived(staged ? "staged changes" : "unstaged changes");

  function closeFromBackdrop(event: MouseEvent) {
    if (isBusy || event.target !== event.currentTarget) return;
    onClose();
  }
</script>

<div class="dialog-backdrop" role="presentation" onclick={closeFromBackdrop}>
  <div class="dialog discard-confirm-dialog" role="dialog" aria-modal="true" aria-label={title}>
    <header class="dialog-header">
      <div>
        <span class="eyebrow">Confirm discard</span>
        <p class="dialog-title">{title}</p>
      </div>
      <button class="btn-sm dialog-close" type="button" onclick={onClose} disabled={isBusy} aria-label="Close">
        <X size={16} aria-hidden="true" />
      </button>
    </header>

    <div class="discard-confirm-body">
      <div class="discard-warning-icon" aria-hidden="true">
        <AlertTriangle size={22} />
      </div>

      <div class="discard-confirm-copy">
        <p>
          This will reset the {sourceLabel} for the {scopeLabel.toLowerCase()} below.
        </p>
        <code class="discard-target" title={targetPath}>{targetPath}</code>
        <p class="discard-warning-text">
          This cannot be undone. If the file only exists in your working tree, it can be deleted entirely.
        </p>
      </div>
    </div>

    <footer class="discard-confirm-actions">
      <button class="btn-secondary" type="button" onclick={onClose} disabled={isBusy}>Cancel</button>
      <button class="btn-danger" type="button" onclick={onConfirm} disabled={isBusy}>
        {#if isBusy}
          <LoaderCircle class="spin" size={15} aria-hidden="true" />
        {:else}
          <RotateCcw size={15} aria-hidden="true" />
        {/if}
        Discard
      </button>
    </footer>
  </div>
</div>
