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

test("Find counts and highlights the displayed file-chip line range", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("file-range-demo", {
    "src/notes.ts": Array.from({ length: 80 }, (_, i) => `export const note${i + 1} = ${i + 1};`).join("\n"),
  });
  const recording = `${APP_DIR}/apps/server/scripts/dev-replay/showcase_transcript.ndjson`;
  const original = await readFile(recording, "utf8");
  const response = "Here are the requested notes:\n\n[src/notes.ts](src/notes.ts#L42-L64)";
  const seed = async (title: string, text: string) => {
    const transcript = [
      { 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 } } } } },
      { type: "emit_inbound", frame: { kind: "response", method: "session/prompt", result: { stopReason: "end_turn" } } },
    ].map((frame) => JSON.stringify(frame)).join("\n") + "\n";
    await writeFile(recording, transcript);
    try {
      return await t3.thread({ project, title, model: "showcase", messages: ["Reply with a link to lines 42 through 64 of src/notes.ts."] });
    } finally {
      await writeFile(recording, original);
    }
  };
  const thread = await seed("Find displayed line range", response);
  const imageThread = await seed("Image syntax file chip", "Image syntax renders this source file as a chip:\n\n![notes](src/notes.ts#L42-L64)");
  const pictureThread = await seed("Theme dependent file chip", 'The displayed source changes with appearance:\n\n<picture><source media="(prefers-color-scheme: dark)" srcset="src/notes.ts#L42-L64"><img src="src/notes.ts#L12-L24" alt="notes"></picture>');
  const errors: unknown[] = [];
  const check = async (label: string, count: string, highlighted: string) => {
    try {
      await expect.poll(() => browser.evaluate(() => {
        const bar = document.querySelector("[data-thread-find-bar]");
        const active = CSS.highlights.get("t3-thread-find-active");
        return {
          count: bar?.querySelector('[aria-hidden="true"]')?.textContent?.trim(),
          highlighted: active ? [...active].map((range) => range.toString()).join("|") : "",
        };
      }), { timeout: 20_000 }).toEqual({ count, highlighted });
    } catch (error) {
      errors.push(error);
    } finally {
      await app.screenshot(label);
    }
  };
  await t3.open(thread);
  await screen.getByText("Here are the requested notes:", { exact: false }).waitFor({ timeout: 120_000 });
  await browser.keyboard.press("Control+f");
  await screen.getByRole("searchbox", "Find in thread").fill("L42–64");
  await check("file-chip-range-search", "1/1", "L42–64");

  await t3.open(imageThread);
  await screen.getByText("Image syntax renders this source file as a chip:").waitFor();
  await browser.keyboard.press("Control+f");
  await screen.getByRole("searchbox", "Find in thread").fill("L42–64");
  await check("image-syntax-range-search", "1/1", "L42–64");

  await t3.open(pictureThread);
  await screen.getByText("The displayed source changes with appearance:").waitFor();
  // The normal appearance shortcut cycles System -> Light -> Dark.
  const appearance = async (mode: "Light" | "Dark") => {
    for (let i = 0; i < 3; i++) {
      const current = await browser.evaluate(() => localStorage.getItem("t3code:theme-appearance-mode"));
      if (current === mode.toLowerCase()) return;
      const next = current === "light" ? "Dark" : current === "dark" ? "System" : "Light";
      await browser.keyboard.press("Control+Alt+Shift+a");
      await screen.getByText(`Appearance: ${next}`, { exact: true }).waitFor();
      await screen.getByText(`Appearance: ${next}`, { exact: true }).waitFor({ state: "hidden" });
    }
  };
  await appearance("Light");
  await browser.keyboard.press("Control+f");
  await screen.getByRole("searchbox", "Find in thread").fill("L42–64");
  await check("theme-light-no-range", "0/0", "");
  await appearance("Dark");
  await check("theme-dark-range-search", "1/1", "L42–64");
  await appearance("Light");
  await check("theme-light-range-removed", "0/0", "");
  await appearance("Dark");
  await check("theme-dark-range-restored", "1/1", "L42–64");
  expect(errors).toEqual([]);
});
