<script lang="ts">
  import { GitBranch, LoaderCircle, X } from "@lucide/svelte";
  import type { GitBranch as GitBranchInfo } from "../types";

  interface Props {
    branch: GitBranchInfo;
    isBusy: boolean;
    onRename: (name: string) => void;
    onClose: () => void;
  }

  let {
    branch,
    isBusy = false,
    onRename = () => {},
    onClose = () => {},
  }: Props = $props();

  let name = $state("");

  $effect(() => {
    name = branch.name;
  });

  function submit(event: SubmitEvent) {
    event.preventDefault();
    const value = name.trim();
    if (!value || value === branch.name) return;
    onRename(value);
  }
</script>

<div
  class="dialog-backdrop"
  role="presentation"
  onclick={(e) => { if (e.target === e.currentTarget) onClose(); }}
>
  <div class="dialog rename-branch-dialog" role="dialog" aria-modal="true" aria-label="Rename branch" tabindex="-1">
    <header class="dialog-header">
      <div>
        <span class="eyebrow">Rename branch</span>
        <h2 class="mt-0.5 text-ink text-base font-bold leading-tight">{branch.name}</h2>
      </div>
      <button class="dialog-close" type="button" onclick={onClose} title="Close">
        <X size={18} aria-hidden="true" />
      </button>
    </header>

    <form class="rename-branch-form" onsubmit={submit}>
      <label class="new-branch-field">
        <span>Branch name</span>
        <!-- svelte-ignore a11y_autofocus -->
        <input
          bind:value={name}
          autocomplete="off"
          spellcheck="false"
          disabled={isBusy}
          autofocus
        />
      </label>

      <div class="new-branch-actions">
        <button class="btn-secondary" type="button" onclick={onClose} disabled={isBusy}>
          Cancel
        </button>
        <button class="btn-primary" type="submit" disabled={isBusy || name.trim().length === 0 || name.trim() === branch.name}>
          {#if isBusy}
            <LoaderCircle class="spin" size={16} aria-hidden="true" />
          {:else}
            <GitBranch size={16} aria-hidden="true" />
          {/if}
          Rename
        </button>
      </div>
    </form>
  </div>
</div>
