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

test("PR Summary retains comment order and reading position across outer tabs", WEB, async ({t3, app, browser, screen}) => {
  const project = await t3.project("review-demo", {"README.md": "# Review notes\n\nSwitch back to the pull request to continue reading comments.\n"});
  await runPromise(run("git", ["remote", "add", "origin", "https://github.com/pingdotgg/t3code.git"], {cwd: project}));
  const thread = await t3.thread({project, title: "Review pull request", messages: ['Review https://github.com/pingdotgg/t3code/pull/41804 and :codex-file-citation{path="README.md" line_range_start="1"}']});
  await browser.setViewport({width:1440,height:1000});
  await t3.open(thread);
  await screen.getByRole("button", /^Agent Review/).tap();
  await screen.getByRole("link", /^README.md/).tap();
  await browser.locator('a[href="https://github.com/pingdotgg/t3code/pull/41804"]').first().click();
  await screen.getByRole("button", "Show oldest comments first", {exact:true}).waitFor({timeout:60000});
  await browser.locator("[data-pull-request-summary-scroll] article").first().waitFor({timeout:60000});
  await screen.getByRole("button", "Show oldest comments first", {exact:true}).tap();
  await browser.evaluate(() => { const s = document.querySelector<HTMLElement>('[data-pull-request-summary-scroll]')!; s.scrollTop = 1906; });
  await app.screenshot("summary-before-switch");
  const before = await browser.evaluate(() => document.querySelector<HTMLElement>('[data-pull-request-summary-scroll]')!.scrollTop);
  await screen.getByRole("button", "README.md", {exact:true}).tap();
  await screen.getByRole("button", "#41804", {exact:true}).tap();
  await browser.locator('[data-pull-request-summary-scroll]').waitFor();
  await screen.getByRole("button", /^Show (newest|oldest) comments first$/).waitFor();
  await browser.locator("[data-pull-request-summary-scroll] article").first().waitFor({timeout:60000});
  await app.screenshot("summary-after-switch");
  const after = await browser.evaluate(() => document.querySelector<HTMLElement>('[data-pull-request-summary-scroll]')!.scrollTop);
  const order = await browser.locator("[data-pull-request-summary-scroll] button[aria-label*=\"comments first\"]").textContent();
  expect({order: order?.trim(), scrollTop: after}, `Summary state after switch (initial scrollTop ${before})`).toEqual({order: "Oldest first", scrollTop: before});
});
