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

test("Long PR lines keep exact-limit CRLF and whole emoji at the cut", WEB, async ({ t3, app, browser, screen }) => {
  await browser.setViewport({ width: 1920, height: 1080 });
  const project = await t3.project("Long lines");
  await runPromise(run("git", ["remote", "add", "origin", "https://gitlab.com/julius54/t3-long-lines-proof-43856.git"], { cwd: project }));
  await t3.open("/pull-requests");
  await screen.getByRole("button", /repro long lines/).tap();
  await screen.getByRole("button", "Code", { exact: true }).tap();
  await screen.getByRole("button", "Expand all files", { exact: true }).tap();
  await screen.getByRole("button", "Load diff", { exact: true }).tap();
  await screen.getByText(/more characters/).first().waitFor({ timeout: 60_000 });
  await app.screenshot("wrapped-long-diff-lines");
  await screen.getByRole("button", "Disable diff line wrapping", { exact: true }).tap();
  await browser.evaluate(() => {
    const scroll = (root: Document | ShadowRoot) => {
      for (const element of root.querySelectorAll("*")) {
        if (element instanceof HTMLElement && element.scrollWidth > element.clientWidth + 200 && element.clientWidth > 200) element.scrollLeft = element.scrollWidth;
        if (element.shadowRoot) scroll(element.shadowRoot);
      }
    };
    scroll(document);
    return null;
  });
  await app.screenshot("long-diff-line-endings");
  const rendered = await browser.evaluate(() => {
    const texts: string[] = [];
    const visit = (node: Node) => {
      if (node.nodeType === Node.TEXT_NODE) texts.push(node.textContent ?? "");
      for (const child of node.childNodes) visit(child);
      if (node instanceof Element && node.shadowRoot) visit(node.shadowRoot);
    };
    visit(document.body);
    return texts.join("");
  });
  expect(rendered.includes("A".repeat(1000))).toBe(true);
  expect(rendered.includes("b".repeat(999) + " …[3 more characters]")).toBe(true);
  expect(rendered.includes("c".repeat(999) + " …[3 more characters]")).toBe(true);
  expect(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])/.test(rendered)).toBe(false);
});
