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

const files = [" leading.txt", "trailing.txt ", "normal.txt"];
const contents = (name: string, edited = false) => Array.from({ length: 40 }, (_, i) => `${name.trim()} ${edited && i === 29 ? "edited" : "line"} ${i + 1}`).join("\n") + "\n";

test("Whitespace filenames expand unchanged diff context", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("Whitespace filenames", Object.fromEntries(files.map(name => [name, contents(name)])));
  await runPromise(Effect.gen(function* () {
    const fs = yield* FileSystem.FileSystem;
    for (const name of files) yield* fs.writeFileString(`${project}/${name}`, contents(name, true));
  }));
  const thread = await t3.thread({ project, title: "Diff context", messages: ["hello"] });
  await t3.open(thread);
  await screen.getByRole("button", "Toggle right panel").tap();
  await screen.getByText("Diff").tap();
  const expanded: string[] = [];
  for (const name of ["normal.txt", " leading.txt", "trailing.txt "]) {
    await screen.getByRole("button", `Expand ${name}`).tap();
    await expect.poll(() => browser.evaluate(() => {
      for (const host of document.querySelectorAll("*")) {
        const button = host.shadowRoot?.querySelector<HTMLElement>("[data-expand-button]");
        if (button) { button.click(); return true; }
      }
      return false;
    })).toBe(true);
    try {
      await expect.poll(() => browser.evaluate(() => Array.from(document.querySelectorAll("*")).flatMap(host => Array.from(host.shadowRoot?.querySelectorAll("[data-line]") ?? [], line => (line.textContent ?? "").trim())))).toContain(`${name.trim()} line 1`);
      expanded.push(name);
    } catch { /* Collect both filename outcomes before the final assertion. */ }
    await app.screenshot(`${name.trim()}-context-expanded`);
    await screen.getByRole("button", `Collapse ${name}`).tap();
  }
  await expect(expanded).toEqual(["normal.txt", " leading.txt", "trailing.txt "]);
});
