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

const reply = "Files:\n\n-       /Users/me/app.ts:42\n\nControl:\n\n- /Users/me/other.ts:7\n";

test("Find matches a displayed file chip in an over-indented list", WEB, async ({ t3, app, screen, browser }) => {
  await browser.emulateMedia({ colorScheme: "dark" });
  const fixture = path.join(APP_DIR, "apps/server/scripts/dev-replay/showcase_transcript.ndjson");
  const original = await fs.readFile(fixture, "utf8");
  const transcript = [
    { type: "expect_outbound", frame: { kind: "request", method: "session/prompt" } },
    { type: "emit_inbound", frame: { kind: "notification", method: "session/update", params: { sessionId: "fixture", update: { sessionUpdate: "agent_message_chunk", content: { type: "text", text: reply } } } } },
    { type: "emit_inbound", frame: { kind: "response", method: "session/prompt", result: { stopReason: "end_turn" } } },
  ].map((entry) => JSON.stringify(entry)).join("\n");
  const project = await t3.project("file-chip-search");
  let thread;
  try {
    await fs.writeFile(fixture, transcript);
    thread = await t3.thread({ project, title: "File chip search", model: "showcase", messages: ["List the files."] });
  } finally {
    await fs.writeFile(fixture, original);
  }
  await t3.open(thread);
  await screen.getByText("app.ts · L42", { exact: true }).waitFor();
  await screen.getByText("other.ts · L7", { exact: true }).waitFor();
  await browser.keyboard.press("Control+f");
  const find = screen.getByRole("searchbox", "Find in thread");
  const counter = () => browser.evaluate<string>('document.querySelector("[data-thread-find-bar] span[aria-hidden]")?.textContent ?? ""');
  await find.fill("other.ts · L7");
  await browser.locator('[data-thread-find-bar]').getByText("1/1", { exact: true }).last().waitFor();
  await app.screenshot("normal-indentation-control");
  await find.fill("app.ts · L42");
  try {
    await expect.poll(counter).toBe("1/1");
    await expect.poll(() => browser.evaluate(() => {
      const ranges = CSS.highlights.get("t3-thread-find-active");
      return ranges ? [...ranges].map((range) => range.toString()).join("") : "";
    })).toBe("app.ts · L42");
  } finally {
    await app.screenshot("displayed-file-chip-search");
  }
});
