import { expect } from "e2e";
import { readFileSync } from "node:fs";
import { test, WEB } from "./t3.ts";

test("Loaded Chronic PR remains after partial-word host searches", WEB, async ({t3,app,screen,browser}) => {
  const project = await t3.project("search-demo", {".git/config": '[core]\nrepositoryformatversion = 0\nbare = false\n[remote "origin"]\nurl = https://github.com/scenario/search-demo.git\nfetch = +refs/heads/*:refs/remotes/origin/*\n'});
  await t3.open();
  await screen.getByRole("button", "Pull requests", {exact:true}).tap();
  await screen.getByText("Chronic reliability improvements", {exact:true}).waitFor({state:"visible"});
  await screen.getByRole("button", "Filter by provider: All").tap();
  await screen.getByRole("menuitemradio", "GitHub", {exact:false}).tap();
  await browser.keyboard.press("Escape");
  await new Promise(resolve => setTimeout(resolve, 1800));
  const capture = async (label: string) => {
    let prior = await app.screenshot(label + "-stability-0");
    for (let attempt = 1; attempt <= 12; attempt++) {
      await new Promise(resolve => setTimeout(resolve, 500));
      const current = await app.screenshot(label + "-stability-" + attempt);
      if (readFileSync(prior).equals(readFileSync(current))) return;
      prior = current;
    }
    throw new Error("Capture did not settle: " + label);
  };
  await capture("baseline");
  const visible: boolean[] = [];
  const search = screen.getByRole("searchbox", "Search pull requests");
  for (const text of ["c", "ch", "chr", "chro"]) {
    await search.fill(text);
    await browser.keyboard.press("Enter");
    await new Promise(resolve => setTimeout(resolve, 1800));
    await capture(`settled-${text}`);
    if (text === "chr" || text === "chro") visible.push(await screen.getByText("Chronic reliability improvements", {exact:true}).isVisible());
  }
  await search.fill("chronic");
  await browser.keyboard.press("Enter");
  await new Promise(resolve => setTimeout(resolve, 1800));
  await capture("whole-word");
  await search.fill("");
  await browser.keyboard.press("Enter");
  await new Promise(resolve => setTimeout(resolve, 1800));
  await capture("cleared");
  expect(visible).toEqual([true, true]);
});
