import { expect } from "e2e";
import { writeFile, readFile } from "node:fs/promises";
import { setTimeout as delay } from "node:timers/promises";
import { execFileSync } from "node:child_process";
import { test, WEB } from "./t3.ts";

test("Changes row matches the selected comparison and whitespace setting", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("comparison-demo", { "example.txt": "First line\nSecond line\n" });
  const git = (...args: string[]) => execFileSync("git", args, { cwd: project });
  git("checkout", "-b", "feature");
  await writeFile(`${project}/example.txt`, "First  line\nSecond line\nAdded line\n");
  git("add", "example.txt");
  git("-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid", "commit", "-m", "Whitespace edit and added line");
  git("update-ref", "refs/remotes/origin/feature", "HEAD");
  await t3.thread({ project, title: "Compare committed changes", messages: ["Ready"] });
  await browser.setViewport({ width: 1920, height: 1080 });
  await t3.open();
  await screen.getByRole("button", /^Compare committed changes,/).tap();
  const row = screen.getByRole("button", /^Changes/);
  await row.tap();
  await screen.getByRole("button", "Show whitespace changes", { exact: true }).waitFor();
  const capture = async (label: string) => {
    let previous = await app.screenshot(`${label}-settling`);
    for (let attempt = 0; attempt < 10; attempt++) {
      await delay(500);
      const current = await app.screenshot(label);
      if ((await readFile(previous)).equals(await readFile(current))) return;
      previous = current;
    }
    throw new Error(`Capture did not settle: ${label}`);
  };
  await screen.getByRole("group", "1 additions, 0 deletions", { exact: true }).first().waitFor();
  await expect.soft(row).toContainText(/\+1\s*-0/);
  await capture("hidden-whitespace");
  await screen.getByRole("button", "Show whitespace changes", { exact: true }).tap();
  await screen.getByRole("group", "2 additions, 1 deletions", { exact: true }).first().waitFor();
  await expect.soft(row).toContainText(/\+2\s*-1/);
  await capture("shown-whitespace");
  await screen.getByRole("combobox", /^Change comparison target/).tap();
  await screen.getByPlaceholder("Search refs...").fill("feature");
  await screen.getByRole("option", /feature/).tap();
  await screen.getByText("No net changes in this selection.", { exact: true }).first().waitFor();
  await expect.soft(row).toContainText(/\+0\s*-0/);
  await capture("same-branch-base");
});
