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

const lines = Array.from({ length: 80 }, (_, i) => `line ${i + 1}`);
test("Diff context expands from a nested project in a trailing-space repository", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("repo /app", { "notes.txt": lines.join("\n") + "\n" });
  const repo = project.slice(0, -4);
  await runPromise(Effect.gen(function* () {
    const fs = yield* FileSystem.FileSystem;
    yield* fs.rename(`${project}/.git`, `${repo}/.git`);
    yield* run("git", ["add", "--all"], { cwd: repo });
    yield* run("git", ["-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid", "commit", "--quiet", "-m", "Move notes into app"], { cwd: repo });
    yield* fs.writeFileString(`${project}/notes.txt`, lines.map((line, i) => i === 39 ? "line 40 CHANGED" : line).join("\n") + "\n");
  }));
  const thread = await t3.thread({ project, title: "Review notes", messages: ["first"] });
  await browser.setViewport({ width: 1440, height: 1080 });
  await t3.open(thread);
  await screen.getByText("first fixture turn complete", { exact: false }).waitFor();
  await screen.getByRole("button", "Toggle right panel").tap();
  await screen.getByText("Diff", { exact: true }).tap();
  const results: Record<string, boolean> = {};
  for (const scope of ["Changes", "Uncommitted"]) {
    await screen.getByRole("button", /^Diff scope:/).tap();
    await screen.getByRole("menuitemradio", scope, { exact: true }).tap();
    await screen.getByRole("button", "Expand app/notes.txt", { exact: true }).tap();
    await browser.evaluate(async () => {
      for (let attempt = 0; attempt < 200; attempt++) {
        for (const host of document.querySelectorAll("*")) {
          const button = host.shadowRoot?.querySelector<HTMLElement>("[data-expand-button]");
          if (button) { button.click(); return; }
        }
        await new Promise(resolve => setTimeout(resolve, 50));
      }
      throw new Error("No collapsed context control");
    });
    try {
      await expect.poll(() => browser.evaluate(() => Array.from(document.querySelectorAll("*")).flatMap(host => Array.from(host.shadowRoot?.querySelectorAll("[data-line]") ?? [], line => line.textContent?.trim())).includes("line 1"))).toBe(true);
      results[scope] = true;
    } catch { results[scope] = false; }
    await app.screenshot(`${scope.toLowerCase()}-expanded-context`);
    await screen.getByRole("button", "Collapse app/notes.txt", { exact: true }).tap();
  }
  expect(results).toEqual({ Changes: true, Uncommitted: true });
});
