/*
 * compare.sr.ht frontend bundle.
 *
 * Consumes the SSR DOM contract:
 *   <script id="compare-data" type="application/json">{...}</script>
 *   <div id="tree-root">   (file tree sidebar)
 *   <div id="diff-root">   (per-file diff sections)
 *   <button data-diff-layout="split">  / <button data-diff-layout="stacked">
 *
 * Rendering uses @pierre/diffs (FileDiff vanilla class) for each file and
 * @pierre/trees (FileTree vanilla class) for the sidebar. Both render on the
 * main thread (no worker pool passed) with the pure-JS Shiki engine, so the
 * bundle is fully self-contained (no wasm / no runtime asset fetches).
 */

import { FileDiff, parsePatchFiles } from "@pierre/diffs";
import type { FileDiffMetadata, FileDiffOptions, ThemesType } from "@pierre/diffs";
import { FileTree } from "@pierre/trees";
import type { GitStatus, GitStatusEntry } from "@pierre/trees";

// ---- DOM contract types (produced by the Go web layer) --------------------

type Layout = "split" | "stacked";

interface FileEntry {
  path: string;
  oldPath: string;
  status: string; // "A" | "M" | "D" | "R" | ...
  additions: number;
  deletions: number;
  binary: boolean;
}

interface CompareData {
  mode: "compare" | "commit";
  patch: string;
  truncated: boolean;
  files: FileEntry[];
  spec: { base: string; head: string; threeDot: boolean };
}

// ---- Constants ------------------------------------------------------------

const LAYOUT_KEY = "compare.layout";
const DEFAULT_LAYOUT: Layout = "stacked";

// Auto light/dark: FileDiff selects the entry matching `themeType`. With
// themeType "system" it follows prefers-color-scheme at runtime.
const THEME: ThemesType = { light: "github-light", dark: "github-dark" };

// ---- Small helpers --------------------------------------------------------

function el<K extends keyof HTMLElementTagNameMap>(
  tag: K,
  className?: string,
  text?: string,
): HTMLElementTagNameMap[K] {
  const node = document.createElement(tag);
  if (className) node.className = className;
  if (text != null) node.textContent = text;
  return node;
}

function readLayout(): Layout {
  try {
    const v = localStorage.getItem(LAYOUT_KEY);
    if (v === "split" || v === "stacked") return v;
  } catch {
    /* localStorage may be unavailable (private mode); fall through */
  }
  return DEFAULT_LAYOUT;
}

function writeLayout(layout: Layout): void {
  try {
    localStorage.setItem(LAYOUT_KEY, layout);
  } catch {
    /* ignore persistence failures */
  }
}

// "stacked" is the user-facing name for the unified diff style.
function diffStyleFor(layout: Layout): "unified" | "split" {
  return layout === "split" ? "split" : "unified";
}

function gitStatusFor(status: string): GitStatus {
  switch (status.toUpperCase()[0]) {
    case "A":
      return "added";
    case "D":
      return "deleted";
    case "R":
      return "renamed";
    case "M":
    default:
      return "modified";
  }
}

function sectionId(index: number): string {
  return `file-${index}`;
}

// ---- Main -----------------------------------------------------------------

function readData(): CompareData | null {
  const script = document.getElementById("compare-data");
  if (!script || !script.textContent) return null;
  try {
    return JSON.parse(script.textContent) as CompareData;
  } catch (err) {
    console.error("compare: failed to parse #compare-data", err);
    return null;
  }
}

function buildFileHeader(index: number, file: FileEntry): HTMLElement {
  const header = el("div", "diff-file-header");

  const path = el("span", "diff-file-path");
  if (file.oldPath && file.oldPath !== file.path) {
    path.append(
      el("span", "diff-file-oldpath", file.oldPath),
      el("span", "diff-file-arrow", " → "),
      el("span", "diff-file-newpath", file.path),
    );
  } else {
    path.textContent = file.path;
  }
  header.append(path);

  const stats = el("span", "diff-file-stats");
  if (file.additions > 0) {
    stats.append(el("span", "diff-file-add", `+${file.additions}`));
  }
  if (file.deletions > 0) {
    stats.append(el("span", "diff-file-del", `-${file.deletions}`));
  }
  header.append(stats);

  if (file.binary) {
    header.append(el("span", "diff-file-badge diff-file-binary", "BIN"));
  }

  header.dataset.fileIndex = String(index);
  return header;
}

function renderDiffs(
  root: HTMLElement,
  data: CompareData,
  metaByPath: Map<string, FileDiffMetadata>,
  layout: Layout,
): FileDiff[] {
  root.textContent = "";
  const instances: FileDiff[] = [];

  if (data.files.length === 0) {
    root.append(el("div", "diff-empty", "No changes to display."));
    return instances;
  }

  const style = diffStyleFor(layout);

  data.files.forEach((file, index) => {
    const section = el("section", "diff-file");
    section.id = sectionId(index);
    section.dataset.path = file.path;
    section.append(buildFileHeader(index, file));

    const body = el("div", "diff-file-body");
    section.append(body);
    root.append(section);

    if (file.binary) {
      body.append(el("div", "diff-file-note", "Binary file not shown."));
      return;
    }

    const meta = metaByPath.get(file.path);
    if (!meta) {
      body.append(el("div", "diff-file-note", "No textual diff available."));
      return;
    }

    const options: FileDiffOptions<undefined> = {
      theme: THEME,
      themeType: "system",
      diffStyle: style,
      // We render our own header row above, so disable the library header.
      disableFileHeader: true,
    };
    const instance = new FileDiff(options);
    instance.render({ fileDiff: meta, containerWrapper: body });
    instances.push(instance);
  });

  return instances;
}

function buildTree(
  root: HTMLElement,
  data: CompareData,
): FileTree | null {
  root.textContent = "";
  if (data.files.length === 0) return null;

  const paths = data.files.map((f) => f.path);
  const gitStatus: GitStatusEntry[] = data.files.map((f) => ({
    path: f.path,
    status: gitStatusFor(f.status),
  }));

  const indexByPath = new Map(data.files.map((f, i) => [f.path, i]));

  const tree = new FileTree({
    paths,
    gitStatus,
    initialExpansion: "open",
    onSelectionChange: (selected) => {
      const path = selected[0];
      if (path == null) return;
      const index = indexByPath.get(String(path));
      if (index == null) return;
      const section = document.getElementById(sectionId(index));
      section?.scrollIntoView({ behavior: "smooth", block: "start" });
    },
  });
  tree.render({ containerWrapper: root });
  return tree;
}

function wireLayoutToggle(
  buttons: HTMLButtonElement[],
  getInstances: () => FileDiff[],
  initial: Layout,
): void {
  let current = initial;

  const apply = (layout: Layout) => {
    current = layout;
    writeLayout(layout);
    for (const btn of buttons) {
      btn.classList.toggle("active", btn.dataset.diffLayout === layout);
    }
    const style = diffStyleFor(layout);
    for (const instance of getInstances()) {
      instance.setOptions({
        theme: THEME,
        themeType: "system",
        diffStyle: style,
        disableFileHeader: true,
      });
      instance.rerender();
    }
  };

  for (const btn of buttons) {
    btn.addEventListener("click", (ev) => {
      ev.preventDefault();
      const layout = btn.dataset.diffLayout;
      if (layout === "split" || layout === "stacked") apply(layout);
    });
  }

  // Reflect the initial (possibly persisted) layout on the buttons.
  for (const btn of buttons) {
    btn.classList.toggle("active", btn.dataset.diffLayout === current);
  }
}

function main(): void {
  const data = readData();
  if (!data) return;

  const diffRoot = document.getElementById("diff-root");
  const treeRoot = document.getElementById("tree-root");
  if (!diffRoot) return;

  const layout = readLayout();

  // parsePatchFiles returns one ParsedPatch per commit; each has a `files`
  // array of FileDiffMetadata. Flatten across patches and index by path.
  const metaByPath = new Map<string, FileDiffMetadata>();
  if (data.patch) {
    try {
      for (const patch of parsePatchFiles(data.patch)) {
        for (const meta of patch.files) {
          metaByPath.set(meta.name, meta);
        }
      }
    } catch (err) {
      console.error("compare: failed to parse patch", err);
    }
  }

  const instances = renderDiffs(diffRoot, data, metaByPath, layout);
  if (treeRoot) buildTree(treeRoot, data);

  const buttons = Array.from(
    document.querySelectorAll<HTMLButtonElement>("button[data-diff-layout]"),
  );
  if (buttons.length > 0) {
    wireLayoutToggle(buttons, () => instances, layout);
  }
}

if (document.readyState === "loading") {
  document.addEventListener("DOMContentLoaded", main);
} else {
  main();
}
