<script lang="ts">
  import {
    AlertCircle,
    ChevronDown,
    ChevronRight,
    Check,
    Download,
    FileText,
    Folder,
    FolderOpen,
    GitBranch,
    GitMerge,
    History,
    LoaderCircle,
    RefreshCw,
    RotateCcw,
    Undo2,
    Upload,
  } from "@lucide/svelte";

  import {
    checkoutBranch,
    commit,
    getStatus,
    listBranches,
    listCommits,
    listFileHistory,
    listRepositoryFiles,
    mergeBranch,
    openRepository,
    pull,
    push,
    restoreFileFromCommit,
    restoreFiles,
    restoreToCommit,
    stageFiles,
    unstageFiles,
  } from "./lib/git";
  import type {
    FileStatusKind,
    GitBranch as GitBranchInfo,
    GitCommit,
    GitCommitFile,
    GitFileStatus,
    GitRepositoryFile,
    GitStatus,
  } from "./lib/types";

  type ExplorerNodeKind = "folder" | "file";

  interface ExplorerNode {
    name: string;
    path: string;
    kind: ExplorerNodeKind;
    status: FileStatusKind | null;
    tracked: boolean;
    depth: number;
    children: ExplorerNode[];
  }

  let repoPath = "";
  let activeRepoPath = "";
  let status: GitStatus | null = null;
  let branches: GitBranchInfo[] = [];
  let commits: GitCommit[] = [];
  let repoFiles: GitRepositoryFile[] = [];
  let selectedExplorerPath = "";
  let selectedExplorerKind: ExplorerNodeKind = "file";
  let expandedExplorerPaths = new Set<string>();
  let fileHistory: GitCommit[] = [];
  let commitMessage = "";
  let errorMessage = "";
  let operation = "";

  $: isBusy = operation.length > 0;
  $: hasRepository = activeRepoPath.length > 0 && status !== null;
  $: changedFiles = status?.files ?? [];
  $: stagedCount = status?.files.filter((file) => file.staged !== null).length ?? 0;
  $: unstagedCount = status?.files.filter((file) => file.unstaged !== null).length ?? 0;
  $: canCommit = hasRepository && stagedCount > 0 && commitMessage.trim().length > 0 && !isBusy;
  $: explorerTree = buildExplorerTree(repoFiles);
  $: visibleExplorerNodes = flattenExplorerTree(explorerTree, expandedExplorerPaths);
  $: selectedExplorerLabel = selectedExplorerPath
    ? `${selectedExplorerKind === "folder" ? "Folder" : "File"} history`
    : "File history";

  function applyStatus(nextStatus: GitStatus) {
    status = nextStatus;
    activeRepoPath = nextStatus.repo_path || activeRepoPath || repoPath.trim();
    repoPath = activeRepoPath;
  }

  function buildExplorerTree(files: GitRepositoryFile[]): ExplorerNode[] {
    const roots: ExplorerNode[] = [];
    const folders = new Map<string, ExplorerNode>();

    for (const file of [...files].sort((left, right) => left.path.localeCompare(right.path))) {
      const parts = file.path.split(/[\\/]+/).filter(Boolean);
      let currentPath = "";
      let siblings = roots;
      let ancestors: ExplorerNode[] = [];

      for (let index = 0; index < parts.length - 1; index += 1) {
        currentPath = currentPath ? `${currentPath}/${parts[index]}` : parts[index];
        let folderNode = folders.get(currentPath);

        if (!folderNode) {
          folderNode = {
            name: parts[index],
            path: currentPath,
            kind: "folder",
            status: null,
            tracked: true,
            depth: index,
            children: [],
          };
          folders.set(currentPath, folderNode);
          siblings.push(folderNode);
        }

        ancestors = [...ancestors, folderNode];
        siblings = folderNode.children;
      }

      const fileNode: ExplorerNode = {
        name: parts[parts.length - 1] ?? file.path,
        path: file.path,
        kind: "file",
        status: file.status,
        tracked: file.tracked,
        depth: Math.max(parts.length - 1, 0),
        children: [],
      };
      siblings.push(fileNode);

      for (const folderNode of ancestors) {
        folderNode.status = mergeExplorerStatus(folderNode.status, file.status);
        folderNode.tracked = folderNode.tracked && file.tracked;
      }
    }

    sortExplorerNodes(roots);
    return roots;
  }

  function mergeExplorerStatus(
    current: FileStatusKind | null,
    next: FileStatusKind | null,
  ): FileStatusKind | null {
    if (!next) {
      return current;
    }

    if (!current) {
      return next;
    }

    const priority: FileStatusKind[] = [
      "conflicted",
      "modified",
      "renamed",
      "deleted",
      "added",
      "untracked",
      "unknown",
    ];

    return priority.indexOf(next) < priority.indexOf(current) ? next : current;
  }

  function sortExplorerNodes(nodes: ExplorerNode[]) {
    nodes.sort((left, right) => {
      if (left.kind !== right.kind) {
        return left.kind === "folder" ? -1 : 1;
      }

      return left.name.localeCompare(right.name);
    });

    for (const node of nodes) {
      sortExplorerNodes(node.children);
    }
  }

  function flattenExplorerTree(nodes: ExplorerNode[], expanded: Set<string>): ExplorerNode[] {
    const visible: ExplorerNode[] = [];

    for (const node of nodes) {
      visible.push(node);

      if (node.kind === "folder" && expanded.has(node.path)) {
        visible.push(...flattenExplorerTree(node.children, expanded));
      }
    }

    return visible;
  }

  function explorerPathExists(files: GitRepositoryFile[], path: string): boolean {
    if (!path) {
      return false;
    }

    const normalizedPath = normalizeExplorerPath(path);
    return files.some((file) => {
      const filePath = normalizeExplorerPath(file.path);
      return filePath === normalizedPath || filePath.startsWith(`${normalizedPath}/`);
    });
  }

  function defaultExpandedExplorerPaths(files: GitRepositoryFile[]): Set<string> {
    const expanded = new Set<string>();

    for (const file of files) {
      const parts = file.path.split(/[\\/]+/).filter(Boolean);
      if (parts.length > 1) {
        expanded.add(parts[0]);
      }
    }

    return expanded;
  }

  function normalizeExplorerPath(path: string): string {
    return path.replace(/\\/g, "/").replace(/^\/+|\/+$/g, "");
  }

  function errorToMessage(error: unknown): string {
    if (error instanceof Error) {
      return error.message;
    }

    if (typeof error === "string") {
      return error;
    }

    try {
      return JSON.stringify(error) ?? "Unknown error";
    } catch {
      return "Unknown error";
    }
  }

  async function runOperation(label: string, task: () => Promise<void>) {
    if (isBusy) {
      return;
    }

    operation = label;
    errorMessage = "";

    try {
      await task();
    } catch (error) {
      errorMessage = errorToMessage(error);
    } finally {
      operation = "";
    }
  }

  async function refreshBranchList(path = activeRepoPath) {
    branches = await listBranches(path);
  }

  async function refreshCommitHistory(path = activeRepoPath) {
    commits = await listCommits(path, 100);
  }

  async function refreshExplorerFiles(path = activeRepoPath) {
    repoFiles = await listRepositoryFiles(path);

    if (expandedExplorerPaths.size === 0) {
      expandedExplorerPaths = defaultExpandedExplorerPaths(repoFiles);
    }

    if (selectedExplorerPath && !explorerPathExists(repoFiles, selectedExplorerPath)) {
      selectedExplorerPath = "";
      selectedExplorerKind = "file";
      fileHistory = [];
    }
  }

  async function refreshFileHistory(path = activeRepoPath, file = selectedExplorerPath) {
    fileHistory = file ? await listFileHistory(path, file, 100) : [];
  }

  async function openRepo() {
    const path = repoPath.trim();

    if (!path) {
      errorMessage = "Enter a repository path.";
      return;
    }

    await runOperation("Opening repository", async () => {
      const nextStatus = await openRepository(path);
      applyStatus(nextStatus);
      branches = [];
      commits = [];
      repoFiles = [];
      selectedExplorerPath = "";
      selectedExplorerKind = "file";
      expandedExplorerPaths = new Set<string>();
      fileHistory = [];
      await refreshBranchList(activeRepoPath);
      await refreshCommitHistory(activeRepoPath);
      await refreshExplorerFiles(activeRepoPath);
    });
  }

  async function refreshRepo() {
    if (!activeRepoPath) {
      await openRepo();
      return;
    }

    await runOperation("Refreshing", async () => {
      applyStatus(await getStatus(activeRepoPath));
      await refreshBranchList(activeRepoPath);
      await refreshCommitHistory(activeRepoPath);
      await refreshExplorerFiles(activeRepoPath);
      await refreshFileHistory(activeRepoPath);
    });
  }

  async function checkout(branch: GitBranchInfo) {
    if (!activeRepoPath || branch.current) {
      return;
    }

    await runOperation(`Checking out ${branch.name}`, async () => {
      applyStatus(await checkoutBranch(activeRepoPath, branch.name));
      await refreshBranchList(activeRepoPath);
      await refreshCommitHistory(activeRepoPath);
      await refreshExplorerFiles(activeRepoPath);
      await refreshFileHistory(activeRepoPath);
    });
  }

  async function merge(branch: GitBranchInfo) {
    if (!activeRepoPath || branch.current) {
      return;
    }

    await runOperation(`Merging ${branch.name}`, async () => {
      applyStatus(await mergeBranch(activeRepoPath, branch.name));
      await refreshBranchList(activeRepoPath);
      await refreshCommitHistory(activeRepoPath);
      await refreshExplorerFiles(activeRepoPath);
      await refreshFileHistory(activeRepoPath);
    });
  }

  async function stageFile(file: GitFileStatus) {
    await runOperation(`Staging ${file.path}`, async () => {
      applyStatus(await stageFiles(activeRepoPath, [file.path]));
      await refreshExplorerFiles(activeRepoPath);
    });
  }

  async function unstageFile(file: GitFileStatus) {
    await runOperation(`Unstaging ${file.path}`, async () => {
      applyStatus(await unstageFiles(activeRepoPath, [file.path]));
      await refreshExplorerFiles(activeRepoPath);
    });
  }

  async function restoreFile(file: GitFileStatus, staged: boolean) {
    await runOperation(`Restoring ${file.path}`, async () => {
      applyStatus(await restoreFiles(activeRepoPath, [file.path], staged));
      await refreshExplorerFiles(activeRepoPath);
      await refreshFileHistory(activeRepoPath);
    });
  }

  async function commitChanges() {
    const message = commitMessage.trim();

    if (!message || !activeRepoPath) {
      return;
    }

    await runOperation("Committing", async () => {
      applyStatus(await commit(activeRepoPath, message));
      commitMessage = "";
      await refreshBranchList(activeRepoPath);
      await refreshCommitHistory(activeRepoPath);
      await refreshExplorerFiles(activeRepoPath);
      await refreshFileHistory(activeRepoPath);
    });
  }

  async function pullRepo() {
    if (!activeRepoPath) {
      return;
    }

    await runOperation("Pulling", async () => {
      applyStatus(await pull(activeRepoPath));
      await refreshBranchList(activeRepoPath);
      await refreshCommitHistory(activeRepoPath);
      await refreshExplorerFiles(activeRepoPath);
      await refreshFileHistory(activeRepoPath);
    });
  }

  async function pushRepo() {
    if (!activeRepoPath) {
      return;
    }

    await runOperation("Pushing", async () => {
      applyStatus(await push(activeRepoPath));
      await refreshBranchList(activeRepoPath);
      await refreshCommitHistory(activeRepoPath);
      await refreshExplorerFiles(activeRepoPath);
      await refreshFileHistory(activeRepoPath);
    });
  }

  async function restoreCommit(target: GitCommit) {
    if (!activeRepoPath) {
      return;
    }

    const confirmed = window.confirm(
      `Reset current branch to ${target.short_hash}?\n\nThis moves the current branch and discards tracked local changes.`,
    );

    if (!confirmed) {
      return;
    }

    await runOperation(`Restoring ${target.short_hash}`, async () => {
      applyStatus(await restoreToCommit(activeRepoPath, target.hash));
      await refreshBranchList(activeRepoPath);
      await refreshCommitHistory(activeRepoPath);
      await refreshExplorerFiles(activeRepoPath);
      await refreshFileHistory(activeRepoPath);
    });
  }

  async function restoreCommitFile(commit: GitCommit, file: GitCommitFile) {
    if (!activeRepoPath) {
      return;
    }

    const confirmed = window.confirm(
      `Restore ${file.path} from ${commit.short_hash}?\n\nThis changes the file in your working tree so you can review and commit it.`,
    );

    if (!confirmed) {
      return;
    }

    await runOperation(`Restoring ${file.path}`, async () => {
      applyStatus(await restoreFileFromCommit(activeRepoPath, commit.hash, file.path));
      await refreshExplorerFiles(activeRepoPath);
      await refreshFileHistory(activeRepoPath);
    });
  }

  function toggleExplorerFolder(node: ExplorerNode) {
    if (node.kind === "folder") {
      const nextExpanded = new Set(expandedExplorerPaths);
      if (nextExpanded.has(node.path)) {
        nextExpanded.delete(node.path);
      } else {
        nextExpanded.add(node.path);
      }
      expandedExplorerPaths = nextExpanded;
    }
  }

  async function selectExplorerNode(node: ExplorerNode) {
    if (!activeRepoPath) {
      return;
    }

    if (selectedExplorerPath === node.path && selectedExplorerKind === node.kind) {
      return;
    }

    selectedExplorerPath = node.path;
    selectedExplorerKind = node.kind;
    await runOperation(`Loading ${node.path} history`, async () => {
      await refreshFileHistory(activeRepoPath, node.path);
    });
  }

  async function restoreSelectedFileFromCommit(commit: GitCommit) {
    if (!activeRepoPath || !selectedExplorerPath) {
      return;
    }

    const targetKind = selectedExplorerKind === "folder" ? "folder" : "file";
    const confirmed = window.confirm(
      `Restore ${targetKind} ${selectedExplorerPath} from ${commit.short_hash}?\n\nThis changes the selected ${targetKind} in your working tree so you can review and commit it.`,
    );

    if (!confirmed) {
      return;
    }

    await runOperation(`Restoring ${selectedExplorerPath}`, async () => {
      applyStatus(await restoreFileFromCommit(activeRepoPath, commit.hash, selectedExplorerPath));
      await refreshExplorerFiles(activeRepoPath);
      await refreshFileHistory(activeRepoPath);
    });
  }

  function submitRepo(event: SubmitEvent) {
    event.preventDefault();
    void openRepo();
  }

  function submitCommit(event: SubmitEvent) {
    event.preventDefault();
    void commitChanges();
  }

  function displayPath(file: GitFileStatus): string {
    if (!file.old_path) {
      return file.path;
    }

    return `${file.old_path} -> ${file.path}`;
  }

  function displayCommitFile(file: GitCommitFile): string {
    if (!file.old_path) {
      return file.path;
    }

    return `${file.old_path} -> ${file.path}`;
  }

  function statusLabel(kind: FileStatusKind | null): string {
    return kind ? kind : "none";
  }

  function formatCommitDate(value: string): string {
    const date = new Date(value);

    if (Number.isNaN(date.getTime())) {
      return value;
    }

    return new Intl.DateTimeFormat(undefined, {
      dateStyle: "medium",
      timeStyle: "short",
    }).format(date);
  }
</script>

<svelte:head>
  <title>Tauri Git Lite</title>
</svelte:head>

<main class="shell">
  <header class="topbar">
    <form class="repo-form" onsubmit={submitRepo}>
      <label for="repo-path">Repository</label>
      <input
        id="repo-path"
        bind:value={repoPath}
        autocomplete="off"
        spellcheck="false"
        placeholder="C:\path\to\repository"
        disabled={isBusy}
      />
      <button class="primary-button" type="submit" disabled={isBusy || repoPath.trim().length === 0}>
        {#if operation === "Opening repository"}
          <LoaderCircle class="spin" size={16} aria-hidden="true" />
        {:else}
          <Check size={16} aria-hidden="true" />
        {/if}
        Open
      </button>
    </form>

    <div class="toolbar" aria-label="Repository actions">
      <button type="button" title="Pull" onclick={pullRepo} disabled={!hasRepository || isBusy}>
        <Download size={16} aria-hidden="true" />
        Pull
      </button>
      <button type="button" title="Push" onclick={pushRepo} disabled={!hasRepository || isBusy}>
        <Upload size={16} aria-hidden="true" />
        Push
      </button>
      <button type="button" title="Refresh" onclick={refreshRepo} disabled={isBusy || repoPath.trim().length === 0}>
        <RefreshCw class={operation === "Refreshing" ? "spin" : ""} size={16} aria-hidden="true" />
        Refresh
      </button>
    </div>
  </header>

  {#if errorMessage}
    <section class="notice error" role="alert">
      <AlertCircle size={17} aria-hidden="true" />
      <span>{errorMessage}</span>
    </section>
  {/if}

  {#if operation && operation !== "Opening repository"}
    <section class="notice busy" aria-live="polite">
      <LoaderCircle class="spin" size={17} aria-hidden="true" />
      <span>{operation}</span>
    </section>
  {/if}

  <section class="workspace" aria-label="Git workspace">
    <aside class="left-sidebar" aria-label="Repository navigation">
      <section class="branches" aria-label="Branches">
        <div class="section-heading">
          <div>
            <span class="eyebrow">Branches</span>
            <h2>Refs</h2>
          </div>
          <span class="counter">{branches.length}</span>
        </div>

        {#if !hasRepository}
          <p class="empty-note">Open a repository to list branches.</p>
        {:else if branches.length === 0}
          <p class="empty-note">No branches returned.</p>
        {:else}
          <div class="branch-list">
            {#each branches as branch (branch.name)}
              <article class:current={branch.current} class="branch-row">
                <div class="branch-info">
                  <GitBranch size={16} aria-hidden="true" />
                  <div>
                    <strong>{branch.name}</strong>
                    <span>{branch.remote ? "remote" : "local"}</span>
                  </div>
                </div>

                {#if branch.current}
                  <span class="active-pill">Current</span>
                {:else}
                  <div class="branch-actions">
                    <button type="button" onclick={() => checkout(branch)} disabled={isBusy}>Checkout</button>
                    <button
                      type="button"
                      onclick={() => merge(branch)}
                      disabled={isBusy}
                      title="Merge branch into current branch"
                    >
                      <GitMerge size={15} aria-hidden="true" />
                      Merge
                    </button>
                  </div>
                {/if}
              </article>
            {/each}
          </div>
        {/if}
      </section>

      <section class="explorer-panel" aria-label="File explorer">
        <div class="section-heading">
          <div>
            <span class="eyebrow">Explorer</span>
            <h2>Files</h2>
          </div>
          <span class="counter">{repoFiles.length}</span>
        </div>

        {#if !hasRepository}
          <p class="empty-note">Open a repository to browse files.</p>
        {:else if repoFiles.length === 0}
          <p class="empty-note">No files returned.</p>
        {:else}
          <div class="explorer-list">
            {#each visibleExplorerNodes as node (`${node.kind}:${node.path}`)}
              <div
                class:active={selectedExplorerPath === node.path && selectedExplorerKind === node.kind}
                class:folder={node.kind === "folder"}
                class="explorer-row"
                style={`--depth: ${node.depth}`}
                title={node.path}
              >
                {#if node.kind === "folder"}
                  <button
                    type="button"
                    class="tree-toggle"
                    onclick={() => toggleExplorerFolder(node)}
                    disabled={isBusy}
                    title={expandedExplorerPaths.has(node.path) ? "Collapse folder" : "Expand folder"}
                  >
                    {#if expandedExplorerPaths.has(node.path)}
                      <ChevronDown size={14} aria-hidden="true" />
                    {:else}
                      <ChevronRight size={14} aria-hidden="true" />
                    {/if}
                  </button>
                  {#if expandedExplorerPaths.has(node.path)}
                    <FolderOpen size={15} aria-hidden="true" />
                  {:else}
                    <Folder size={15} aria-hidden="true" />
                  {/if}
                {:else}
                  <span class="tree-spacer"></span>
                  <FileText size={15} aria-hidden="true" />
                {/if}
                <button
                  type="button"
                  class="explorer-select"
                  onclick={() => selectExplorerNode(node)}
                  disabled={isBusy}
                  title={`Show history for ${node.path}`}
                >
                  <span>{node.name}</span>
                </button>
                {#if node.status}
                  <small class={`status-badge ${node.status}`}>{statusLabel(node.status)}</small>
                {:else if !node.tracked}
                  <small class="status-badge untracked">untracked</small>
                {/if}
              </div>
            {/each}
          </div>
        {/if}
      </section>
    </aside>

    <section class="main-panel" aria-label="Repository status">
      <div class="repo-summary">
        <div>
          <span class="eyebrow">Current repo</span>
          <h1>{status?.current_branch ?? "No repository"}</h1>
          <p>{activeRepoPath || "Enter a path and open a repository."}</p>
        </div>

        <div class="sync-stats" aria-label="Sync state">
          <span title="Upstream">{status?.upstream ?? "No upstream"}</span>
          <strong>{status?.ahead ?? 0} ahead</strong>
          <strong>{status?.behind ?? 0} behind</strong>
        </div>
      </div>

      <div class="status-grid">
        <section class="status-panel">
          <div class="section-heading">
            <div>
              <span class="eyebrow">Working tree</span>
              <h2>Status</h2>
            </div>
            <div class="status-counts">
              <span>{stagedCount} staged</span>
              <span>{unstagedCount} unstaged</span>
            </div>
          </div>

          {#if !hasRepository}
            <div class="blank-state">No repository loaded.</div>
          {:else if status?.clean}
            <div class="blank-state">Working tree is clean.</div>
          {:else if changedFiles.length === 0}
            <div class="blank-state">No file changes returned.</div>
          {:else}
            <div class="file-list">
              {#each changedFiles as file (`${file.old_path ?? ""}:${file.path}`)}
                <article class="file-row">
                  <div class="file-title">
                    <strong title={displayPath(file)}>{displayPath(file)}</strong>
                  </div>

                  <div class="change-lanes">
                    <div class:inactive={!file.staged} class="change-lane">
                      <span class="lane-name">Staged</span>
                      <span class={`status-badge ${file.staged ?? "none"}`}>{statusLabel(file.staged)}</span>
                      <div class="lane-actions">
                        {#if file.staged}
                          <button type="button" onclick={() => unstageFile(file)} disabled={isBusy} title="Unstage file">
                            <Undo2 size={15} aria-hidden="true" />
                            Unstage
                          </button>
                          <button
                            type="button"
                            onclick={() => restoreFile(file, true)}
                            disabled={isBusy}
                            title="Restore staged changes"
                          >
                            <RotateCcw size={15} aria-hidden="true" />
                            Restore
                          </button>
                        {:else}
                          <span class="quiet">No staged change</span>
                        {/if}
                      </div>
                    </div>

                    <div class:inactive={!file.unstaged} class="change-lane">
                      <span class="lane-name">Unstaged</span>
                      <span class={`status-badge ${file.unstaged ?? "none"}`}>{statusLabel(file.unstaged)}</span>
                      <div class="lane-actions">
                        {#if file.unstaged}
                          <button type="button" onclick={() => stageFile(file)} disabled={isBusy} title="Stage file">
                            <Check size={15} aria-hidden="true" />
                            Stage
                          </button>
                          <button
                            type="button"
                            onclick={() => restoreFile(file, false)}
                            disabled={isBusy}
                            title="Restore unstaged changes"
                          >
                            <RotateCcw size={15} aria-hidden="true" />
                            Restore
                          </button>
                        {:else}
                          <span class="quiet">No unstaged change</span>
                        {/if}
                      </div>
                    </div>
                  </div>
                </article>
              {/each}
            </div>
          {/if}
        </section>

        <aside class="side-stack" aria-label="Commit and history">
          <section class="commit-panel" aria-label="Commit">
            <div class="section-heading">
              <div>
                <span class="eyebrow">Commit</span>
                <h2>Message</h2>
              </div>
            </div>

            <form class="commit-form" onsubmit={submitCommit}>
              <textarea
                bind:value={commitMessage}
                placeholder="Commit message"
                rows="7"
                disabled={!hasRepository || isBusy}
              ></textarea>
              <button class="primary-button" type="submit" disabled={!canCommit}>
                {#if operation === "Committing"}
                  <LoaderCircle class="spin" size={16} aria-hidden="true" />
                {:else}
                  <Check size={16} aria-hidden="true" />
                {/if}
                Commit
              </button>
            </form>

            <div class="commit-hint">
              <strong>{stagedCount}</strong>
              <span>files staged</span>
            </div>
          </section>

          <section class="file-history-panel" aria-label="Selected file history">
            <div class="section-heading">
              <div>
                <span class="eyebrow">{selectedExplorerLabel}</span>
                <h2>{selectedExplorerPath || "No file"}</h2>
              </div>
              <span class="counter">{fileHistory.length}</span>
            </div>

            {#if !hasRepository}
              <div class="blank-state">No repository loaded.</div>
            {:else if !selectedExplorerPath}
              <div class="blank-state">Select a file in Explorer.</div>
            {:else if fileHistory.length === 0}
              <div class="blank-state">No history returned for this selection.</div>
            {:else}
              <div class="history-list">
                {#each fileHistory as item (item.hash)}
                  <article class="commit-row compact">
                    <div class="commit-line">
                      <History size={16} aria-hidden="true" />
                      <div>
                        <strong title={item.summary}>{item.summary}</strong>
                        <span>{item.short_hash} - {item.author_name}</span>
                      </div>
                    </div>

                    <div class="commit-actions">
                      <time datetime={item.date}>{formatCommitDate(item.date)}</time>
                      <button
                        type="button"
                        onclick={() => restoreSelectedFileFromCommit(item)}
                        disabled={isBusy}
                        title="Restore selected file from this commit"
                      >
                        <RotateCcw size={15} aria-hidden="true" />
                        Restore
                      </button>
                    </div>
                  </article>
                {/each}
              </div>
            {/if}
          </section>

          <section class="history-panel" aria-label="Commit history">
            <div class="section-heading">
              <div>
                <span class="eyebrow">History</span>
                <h2>Commits</h2>
              </div>
              <span class="counter">{commits.length}</span>
            </div>

            {#if !hasRepository}
              <div class="blank-state">No repository loaded.</div>
            {:else if commits.length === 0}
              <div class="blank-state">No commits returned.</div>
            {:else}
              <div class="history-list">
                {#each commits as item (item.hash)}
                  <article class="commit-row">
                    <div class="commit-line">
                      <History size={16} aria-hidden="true" />
                      <div>
                        <strong title={item.summary}>{item.summary}</strong>
                        <span>{item.short_hash} - {item.author_name}</span>
                      </div>
                    </div>

                    {#if item.refs.length > 0}
                      <div class="ref-list" aria-label="Commit refs">
                        {#each item.refs as ref}
                          <span>{ref}</span>
                        {/each}
                      </div>
                    {/if}

                    {#if item.files.length > 0}
                      <div class="commit-file-list" aria-label="Changed files">
                        {#each item.files as file (`${item.hash}:${file.old_path ?? ""}:${file.path}`)}
                          <button
                            type="button"
                            class="commit-file-button"
                            onclick={() => restoreCommitFile(item, file)}
                            disabled={isBusy}
                            title="Restore this file from this commit"
                          >
                            <span class={`status-badge ${file.status}`}>{statusLabel(file.status)}</span>
                            <strong>{displayCommitFile(file)}</strong>
                          </button>
                        {/each}
                      </div>
                    {/if}

                    <div class="commit-actions">
                      <time datetime={item.date}>{formatCommitDate(item.date)}</time>
                      <button
                        type="button"
                        onclick={() => restoreCommit(item)}
                        disabled={isBusy}
                        title="Reset current branch to this commit"
                      >
                        <RotateCcw size={15} aria-hidden="true" />
                        Restore
                      </button>
                    </div>
                  </article>
                {/each}
              </div>
            {/if}
          </section>
        </aside>
      </div>
    </section>
  </section>
</main>
