/// <reference lib="dom" />
import { expect } from "e2e";

import { run } from "./shell.ts";
import { runPromise, test, WEB } from "./t3.ts";

test("GitCafe keeps plain and trailing-space report patches distinct", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("Two reports");
  await runPromise(run("git", ["remote", "add", "origin", "https://git.cafe/juliusmarminge/factory-pr-45715-proof.git"], { cwd: project }));
  await browser.setViewport({ width: 1440, height: 1000 });
  await t3.open(`/pull-requests?${new URLSearchParams({ repository: "juliusmarminge/factory-pr-45715-proof", host: "git.cafe",  })}`);
  await screen.getByRole("button", /^Open #1 Two reports/).tap();
  await screen.getByRole("button", "Code", { exact: true }).waitFor({ timeout: 60_000 });
  await screen.getByRole("button", "Code", { exact: true }).tap();
  await expect.poll(() => browser.evaluate(() =>
    document.body.textContent?.includes("Couldn't load the changes") ||
    !!document.querySelector('button[aria-label="Expand all files"], button[aria-label="Collapse all files"]')
  ), { timeout: 60_000 }).toBe(true);
  const unavailable = screen.getByText("Couldn't load the changes", { exact: true });
  if (!(await unavailable.isVisible())) {
    await screen.getByRole("button", "Expand diff", { exact: true }).nth(3).tap();
    await screen.getByRole("button", "Expand diff", { exact: true }).nth(3).tap();
    await expect.poll(() => browser.evaluate(() =>
      Array.from(document.querySelectorAll("*")).flatMap(host =>
        Array.from(host.shadowRoot?.querySelectorAll("[data-line]") ?? [], line => line.textContent ?? "")
      ).join("\n")
    )).toContain("second line belongs to trailing name");
  }
  await app.screenshot("gitcafe-two-reports");
  await expect(unavailable).not.toBeVisible();
  const lines = await browser.evaluate(() =>
    Array.from(document.querySelectorAll("*")).flatMap(host =>
      Array.from(host.shadowRoot?.querySelectorAll("[data-line]") ?? [], line => line.textContent ?? "")
    )
  );
  expect(lines).toContain("plain name");
  expect(lines).toContain("trailing space name");
  expect(lines).toContain("second line belongs to trailing name");
});
