/// <reference lib="dom" />
import { expect } from "e2e";
import { chromium } from "playwright-core";
import { writeFile, mkdir } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { test, WEB } from "./t3.ts";

test("Diff announces removed and added lines", WEB, async ({ t3, app, screen, browser }) => {
  await browser.setViewport({ width: 1440, height: 900 });
  await browser.emulateMedia({ colorScheme: "dark" });
  const project = await t3.project("Diff accessibility", {
    "limits.ts": "export const name = 1;\nconst limit = 10;\nexport default limit;\n",
  });
  const thread = await t3.thread({ project, title: "Review limits", messages: ["Review the limit change"] });
  await writeFile(`${project}/limits.ts`, "export const name = 1;\nconst limit = 20;\nexport default limit;\n");
  await t3.open(thread);
  await screen.getByRole("button", "Toggle right panel", { exact: true }).tap();
  await screen.getByRole("button", "Diff D", { exact: true }).tap();
  await screen.getByRole("button", "Stacked diff view").tap();
  await screen.getByRole("button", "Expand limits.ts", { exact: true }).tap();
  const connection = await chromium.connectOverCDP("http://127.0.0.1:19451");
  const page = connection.contexts().flatMap(c => c.pages()).find(p => p.url().includes(thread.threadId))!;
  await page.locator('[data-line][data-line-type="change-deletion"]').waitFor({ state: "visible" });
  await page.bringToFront();
  await page.screenshot({ animations: "disabled" });
  await app.screenshot("expanded-stacked-diff");
  const cdp = await page.context().newCDPSession(page);
  const tree = await cdp.send("Accessibility.getFullAXTree");
  const text = tree.nodes.filter(n => !n.ignored && n.role?.value === "StaticText").map(n => String(n.name?.value ?? ""));
  const lines = await page.locator('[data-line-type^="change-"][data-line]').evaluateAll(rows => rows.map(row => ({ type: row.getAttribute("data-line-type"), text: row.textContent, before: getComputedStyle(row, "::before").content })));
  const side = text.some(t => t.includes("Removed")) ? "head" : "base";
  const artifacts = join(tmpdir(), "diff-accessibility-proof");
  await mkdir(artifacts, { recursive: true });
  await writeFile(join(artifacts, `${side}.json`), JSON.stringify({ browser: await page.context().browser()?.version(), viewport: page.viewportSize(), staticTextInReadingOrder: text, changedLines: lines }, null, 2));
  await cdp.detach();
  await connection.close();
  expect(text.join("\n")).toContain("Removed");
  expect(text.join("\n")).toContain("Added");
});
