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

test("Warmup content search checks full lines before displaying a prefix", WEB, async ({ t3, app, screen, browser }) => {
  const files: Record<string, string> = { "longlines.txt": " ".repeat(600) + "token\n" + " ".repeat(507) + "tokenized\n" + "é token" + "d".repeat(600) + " token\n" };
  // Keep the initial content scan active, as in the reported large repository.
  for (let index = 0; index < 12000; index++) files[`padding/file-${index}.txt`] = "unrelated content ".repeat(512);
  const observed = [];
  for (const [title, query, wholeWord, regex] of [
    ["Literal whole word", "token", true, false],
    ["Regex whole word", "tok+en", true, true],
    ["Regex complete ranges", "tok+en\\w*", false, true],
  ] as const) {
    const project = await t3.project(title, files);
    const thread = await t3.thread({ project, title, messages: ["Start"] });
    await t3.open(thread);
    await screen.getByText("first fixture turn complete", { exact: true }).waitFor();
    await browser.keyboard.press("Control+Shift+f");
    await screen.getByPlaceholder(`Search in ${title}`).waitFor();
    if (wholeWord) await screen.getByRole("button", "Match whole word", { exact: true }).tap();
    if (regex) await screen.getByRole("button", "Use regular expression", { exact: true }).tap();
    await screen.getByPlaceholder(`Search in ${title}`).fill(query);
    await screen.getByText(/\d+ results in \d+ files/).waitFor();
    observed.push(await browser.evaluate(() => Array.from(document.querySelectorAll('[data-testid="project-content-search"] section button')).map(row => ({ line: row.firstElementChild?.textContent?.trim(), highlights: Array.from(row.querySelectorAll('mark')).map(mark => mark.textContent) }))));
    await app.screenshot(title.toLowerCase().replaceAll(" ", "-"));
    await browser.keyboard.press("Escape");
  }
  expect(observed).toEqual([
    [{ line: "1", highlights: [] }, { line: "3", highlights: [] }],
    [{ line: "1", highlights: [] }, { line: "3", highlights: [] }],
    [{ line: "1", highlights: [] }, { line: "2", highlights: [] }, { line: "3", highlights: [] }],
  ]);
});
