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

test("PR line link reveals a file further down an expanded diff", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("PR line navigation");
  await runPromise(run("git", ["remote", "add", "origin", "https://github.com/pingdotgg/t3code.git"], { cwd: project }));
  const link = "https://github.com/pingdotgg/t3code/pull/33989/files#diff-f69351bf94f54011e7f99234f2462e5313903b815cd6cab140937bb17fd4774bR12-R20";
  const thread = await t3.thread({ project, title: "Jump to PR lines", messages: [`[pullRequestAnchor.ts lines 12-20](${link})`] });
  await t3.open("/settings/diffs");
  await screen.getByRole("combobox", "Default diff file state").tap();
  await screen.getByRole("option", "Expanded", { exact: true }).tap();
  await t3.open(thread);
  await screen.getByRole("button", /^Agent \[pullRequestAnchor/).tap();
  await screen.getByRole("link", "pullRequestAnchor.ts lines 12-20", { exact: true }).tap();
  await screen.getByRole("button", "Maximize panel", { exact: true }).tap();
  await browser.locator(".diff-render-surface").waitFor();
  const selected = () => browser.evaluate(() => {
    const surface = document.querySelector<HTMLElement>(".diff-render-surface");
    const hosts = Array.from(surface?.querySelectorAll("*") ?? []);
    return { top: surface?.scrollTop ?? 0, selected: hosts.reduce((n, x) => n + (x.shadowRoot?.querySelectorAll("[data-selected-line]").length ?? 0), 0) };
  });
  try {
    await expect.poll(async () => (await selected()).top, { timeout: 25000 }).toBeGreaterThan(1000);
    await expect.poll(async () => (await selected()).selected).toBeGreaterThan(0);
  } finally {
    await app.screenshot("pr-line-link-result");
  }
});
