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

const markdown = "Done:\n\n- **Cache**: warm on start.\n- Run `vp test`, then [ship](https://example.com/ship).";
const expected = "Done: Cache: warm on start. Run vp test, then ship.";

test("Minimap keeps tight list inline punctuation together", WEB, async ({ t3, app, browser, screen }) => {
  // Supply the exact reported replies through the real replay adapter on both commits.
  const fixture = `${APP_DIR}/apps/server/src/orchestration-v2/testkit/fixtures/multi_turn/registry_transcript.ndjson`;
  const original = await readFile(fixture, "utf8");
  const frames = [markdown, "OK"].flatMap(text => [
    { type: "expect_outbound", frame: { kind: "request", method: "session/prompt" } },
    { type: "emit_inbound", frame: { kind: "notification", method: "session/update", params: { sessionId: "replay", update: { sessionUpdate: "agent_message_chunk", content: { type: "text", text } } } } },
    { type: "emit_inbound", frame: { kind: "response", method: "session/prompt", result: { stopReason: "end_turn" } } },
  ]);
  const runtimeFile = `${T3_HOME}/userdata/server-runtime.json`;
  const beforeRuntime = await readFile(runtimeFile, "utf8");
  const changes = watch(`${T3_HOME}/userdata`, { signal: AbortSignal.timeout(30000) });
  const restarted = (async () => {
    for await (const event of changes) {
      if (event.filename !== "server-runtime.json") continue;
      try {
        const current = await readFile(runtimeFile, "utf8");
        if (current !== beforeRuntime && JSON.parse(current).startedAt) break;
      } catch {}
    }
    await changes.return();
  })();
  await writeFile(fixture, frames.map(frame => JSON.stringify(frame)).join("\n") + "\n");
  await restarted;
  try {
    const project = await t3.project("minimap-demo");
    const thread = await t3.thread({ project, title: "Tight list preview", messages: ["Reply with the requested Done list.", "Reply with just: OK"] });
    await t3.open(thread);
    await screen.getByText("warm on start.", { exact: false }).waitFor();
    await screen.getByRole("button", /^Jump to message:/).waitFor();
    const point = await browser.evaluate(() => {
      const button = document.querySelector('[data-testid="timeline-minimap"] button[aria-label^="Jump to message:"]');
      const box = button?.getBoundingClientRect();
      if (!box) throw new Error("Minimap button missing");
      return { x: box.x + box.width / 2, y: box.y + 1 };
    });
    await browser.mouse.move(point.x, point.y);
    await screen.getByText(/^Done: Cache/).waitFor();
    await app.screenshot("tight-list-preview");
    const preview = await browser.evaluate(() => document.querySelector('[data-testid="timeline-minimap"] button[aria-label^="Jump to message:"] span[style*="-webkit-box"]')?.textContent);
    expect(preview, "The minimap reply keeps inline punctuation tight and list items separated").toBe(expected);
  } finally {
    await writeFile(fixture, original);
  }
});
