/// <reference lib="dom" />
import { execFileSync } from "node:child_process";
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("Canonical title searches rank the real accented title above body-only matches", WEB, async ({t3, app, browser, screen}) => {
  for (const [name, repository] of [["Unicode search", "pingdotgg/t3code"], ["Accented PR title", "moregeo-it/ceos-ard-testing"]]) {
    const project = await t3.project(name);
    execFileSync("git", ["remote", "add", "origin", `https://github.com/${repository}.git`], {cwd: project});
  }
  const settle = async () => {
    await browser.evaluate(() => new Promise<void>((resolve, reject) => {
      let stable: ReturnType<typeof setTimeout>;
      const timeout = setTimeout(() => {observer.disconnect(); reject(new Error("PR page did not settle"));}, 60000);
      const check = () => {
        clearTimeout(stable);
        if(document.querySelector('svg[aria-label="Loading"]') || document.body.textContent?.includes("Loading pull requests…")) return;
        stable = setTimeout(() => {observer.disconnect(); clearTimeout(timeout); resolve();}, 1000);
      };
      const observer = new MutationObserver(check);
      observer.observe(document.body, {subtree:true, childList:true, characterData:true});
      setTimeout(check, 500);
    }));
    await browser.mouse.move(1200, 50);
  };
  const rows = () => browser.evaluate(() => {
    const all = [...document.querySelectorAll('[data-pull-request-key]')];
    const title = all.find(el => el.textContent?.includes("Größe Café"));
    const group = title?.parentElement;
    const peers = group ? [...group.querySelectorAll('[data-pull-request-key]')] : [];
    return {keys: all.map(el => el.getAttribute('data-pull-request-key')), title: title?.textContent ?? "", firstInGroup: peers[0]?.textContent ?? ""};
  });
  await t3.open(`/pull-requests?${new URLSearchParams({q:"Café", state:"all"})}`);
  await screen.getByRole("searchbox").first().waitFor({timeout:60000});
  await screen.getByText("Größe Café", {exact:true}).waitFor({timeout:60000});
  await settle();
  const nfc = await rows();
  await browser.evaluate(() => [...document.querySelectorAll('[data-pull-request-key]')].find(el => el.textContent?.includes("Größe Café"))?.scrollIntoView({block:"center"}));
  await app.screenshot("001-title-ranking-nfc");
  await t3.open(`/pull-requests?${new URLSearchParams({q:"Cafe\u0301", state:"all"})}`);
  await screen.getByRole("searchbox").first().waitFor({timeout:60000});
  await settle();
  const nfd = await rows();
  await browser.evaluate(() => [...document.querySelectorAll('[data-pull-request-key]')].find(el => el.textContent?.includes("Größe Café"))?.scrollIntoView({block:"center"}));
  await app.screenshot("002-title-ranking-nfd");
  expect(nfc.firstInGroup).toContain("Größe Café");
  expect(nfd.keys).toEqual(nfc.keys);
  expect(nfd.firstInGroup).toContain("Größe Café");
  expect(nfd.firstInGroup).not.toContain("matched in the description");
});
