import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("Load more traverses 200 pull requests sharing one update time", WEB, async ({ t3, app, screen, browser }) => {
  await t3.project("web", { ".git/config": '[remote "origin"]\nurl = https://127.0.0.1/acme/web.git\nfetch = +refs/heads/*:refs/remotes/origin/*\n' });
  await t3.open("/pull-requests?involvement=all&state=open");
  const more = screen.getByRole("button", "Load more pull requests");
  await more.waitFor();
  await screen.getByText("Fixture PR99", { exact: true }).waitFor({ state: "attached" });
  await screen.getByText("Fixture PR99", { exact: true }).scrollIntoView();
  await more.scrollIntoView();
  await app.screenshot("first-page");
  for (let page = 0; page < 3; page++) {
    if (await more.count() === 0) break;
    await more.tap();
    // Wait for the actual list request to complete, including replacement of its loading label.
    await screen.getByText("Loading more", { exact: true }).waitFor({ state: "hidden" });
    await browser.evaluate(async () => {
      await new Promise<void>((resolve) => {
        let timer: ReturnType<typeof setTimeout>;
        const done = () => { observer.disconnect(); resolve(); };
        const observer = new MutationObserver(() => { clearTimeout(timer); timer = setTimeout(done, 800); });
        observer.observe(document.body, { subtree: true, childList: true, attributes: true });
        timer = setTimeout(done, 800);
      });
    });
    if (await more.count()) await more.scrollIntoView();
    else await screen.getByText("Fixture PR230", { exact: true }).scrollIntoView();
    await app.screenshot(`after-load-${page + 1}`);
  }
  await app.screenshot("pagination-result");
  await expect(screen.getByText(/^Fixture PR\d+$/, { exact: true })).toHaveCount(230);
  await expect(screen.getByText("Fixture PR230", { exact: true })).toBeVisible();
  await expect(more).toHaveCount(0);
});
