/// <reference lib="dom" />
import { expect } from "e2e";
import { run } from "./shell.ts";
import { runPromise, test, WEB } from "./t3.ts";

test("Clicking the leading-space filename folds only that PR diff", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("Diff header proof");
  const remote = process.env.REPRO_REMOTE!;
  const git = (args: string[]) => runPromise(run("git", args, { cwd: project }));
  await git(["remote", "add", "origin", remote]);
  await git(["-c", 'credential.helper=!f() { echo username=pat; echo "password=$AZURE_DEVOPS_EXT_PAT"; }; f', "fetch", "origin", "main"]);
  await git(["reset", "--hard", "origin/main"]);
  const thread = await t3.thread({ project, title: "Diff header proof", messages: ["first"] });
  await t3.open(thread);
  await screen.getByText("first fixture turn complete", { exact: false }).waitFor();
  await t3.open("/pull-requests");
  await screen.getByText("Diff header folding proof", { exact: true }).waitFor({ timeout: 90_000 });
  await screen.getByText("Diff header folding proof", { exact: true }).tap();
  await screen.getByRole("button", "Code", { exact: true }).tap();
  await screen.getByRole("button", "Expand all files", { exact: true }).waitFor({ timeout: 90_000 });
  await screen.getByRole("button", "Expand all files", { exact: true }).tap();
  const states = () => browser.evaluate(() => Array.from(document.querySelectorAll('diffs-container')).flatMap(host => {
    const title = host.shadowRoot?.querySelector('[data-title]');
    if (!title) return [];
    const toggle = host.querySelector('button[aria-expanded]') ?? host.shadowRoot?.querySelector('button[aria-expanded]');
    return [{ title: title.textContent, expanded: toggle?.getAttribute('aria-expanded') }];
  }));
  // Wait for both loaded headers without asserting anything unrelated to the defect.
  await screen.getByRole("button", "Collapse diff", { exact: true }).nth(1).waitFor();
  await app.screenshot("both-files-expanded");
  await browser.evaluate(() => {
    const title = Array.from(document.querySelectorAll('diffs-container')).map(host => host.shadowRoot?.querySelector<HTMLElement>('[data-title]')).find(title => title?.textContent === ' note.txt');
    if (!title) throw new Error("Leading-space diff title not found");
    title.click();
  });
  try {
    await expect.poll(states).toEqual([{ title: " note.txt", expanded: "false" }, { title: "note.txt", expanded: "true" }]);
  } finally {
    await app.screenshot("after-click-leading-space-filename");
  }
});
