/// <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 indexes the visible inline HTML file chip label", WEB, async ({ t3, app, browser, screen }) => {
  const records = [
    { type: "transcript_start", provider: "acpRegistry", protocol: "acp.ndjson-jsonrpc", version: "1", scenario: "inline_html_chip" },
    { type: "expect_outbound", frame: { kind: "request", method: "session/prompt", params: "<any>" } },
    { type: "emit_inbound", frame: { kind: "notification", method: "session/update", params: { sessionId: "dev-replay-session", update: { sessionUpdate: "agent_message_chunk", content: { type: "text", text: "See <code>./src/index.ts:42</code>." } } } } },
    { 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`, records.map(record => JSON.stringify(record)).join("\n") + "\n");
  const project = await t3.project("work", { "src/index.ts": "// line\n".repeat(42) });
  const input = { project, title: "Inline HTML file chip", messages: ["Show the file reference"], model: "command-output" };
  let thread;
  for (let attempt = 0; attempt < 30; attempt++) {
    try { thread = await t3.thread(input); break; }
    catch (error) {
      if (!String(error).includes("not advertised") || attempt === 29) throw error;
    }
  }
  if (!thread) throw new Error("Replay discovery did not complete");
  await t3.open(thread);
  await screen.getByText("index.ts · L42", { exact: true }).waitFor();
  await browser.keyboard.press("Control+f");
  await screen.getByRole("searchbox", "Find in thread").fill("L42");
  try {
    await expect.poll(() => browser.evaluate(() => ({
      count: document.querySelector("[data-thread-find-bar] span[aria-hidden]")?.textContent,
      highlighted: [...(CSS.highlights.get("t3-thread-find-active") ?? [])].some(range => range instanceof Range && range.toString() === "L42"),
    }))).toEqual({ count: "1/1", highlighted: true });
  } finally {
    await app.screenshot("inline-html-chip-L42-find");
  }
});
