/// <reference lib="dom" />
import { writeFile } from "node:fs/promises";
import { expect } from "e2e";
import { APP_DIR } from "../e2e.config.ts";
import { test, WEB } from "./t3.ts";

test("Find highlights and navigates 300,000 matches in one rendered row", WEB, async ({t3, app, screen, browser}) => {
  const frames = [
    {type: "expect_outbound", frame: {kind: "request", method: "session/prompt", params: "<any>"}},
    ...Array.from({length: 6}, () => ({type: "emit_inbound", afterMs: 20, frame: {kind: "notification", method: "session/update", params: {sessionId: "replay", update: {sessionUpdate: "agent_message_chunk", content: {type: "text", text: "=".repeat(50_000)}}}}})),
    {type: "emit_inbound", frame: {kind: "response", method: "session/prompt", result: {stopReason: "end_turn"}}},
  ];
  await writeFile(`${APP_DIR}/apps/server/scripts/dev-replay/command_output_transcript.ndjson`, frames.map(frame => JSON.stringify(frame)).join("\n"));
  const project = await t3.project("Find demonstration");
  const thread = await t3.thread({project, title: "300,000 matches in one row", messages: ["Render the large find sample"], model: "command-output"});
  await t3.open(thread);
  await screen.getByText("Render the large find sample", {exact: true}).tap();
  await browser.keyboard.press("Control+f");
  await screen.getByRole("searchbox", "Find in thread").fill("=");
  // Capture either the completed highlight paint or the error boundary, before asserting.
  await expect.poll(() => browser.evaluate(() => document.body.textContent?.includes("Something went wrong") || (((CSS as any).highlights.get("t3-thread-find")?.size ?? 0) + ((CSS as any).highlights.get("t3-thread-find-active")?.size ?? 0)) === 300000)).toBe(true);
  await app.screenshot("find-large-row");
  await expect.poll(() => browser.evaluate(() => (((CSS as any).highlights.get("t3-thread-find")?.size ?? 0) + ((CSS as any).highlights.get("t3-thread-find-active")?.size ?? 0)))).toBe(300000);
  await screen.getByRole("button", "Next match").tap();
  await expect(screen.getByText("2/300000", {exact: true})).toBeVisible();
  await app.screenshot("next-match");
});
