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("External link keeps its leading emoji in one text node", WEB, async ({ t3, app, screen, browser }) => {
  const transcriptPath = `${APP_DIR}/apps/server/scripts/dev-replay/showcase_transcript.ndjson`;
  const original = await readFile(transcriptPath, "utf8");
  const markdown = "[😀 Read the documentation](https://example.com)";
  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: markdown } } } } },
    { type: "emit_inbound", frame: { kind: "response", method: "session/prompt", result: { stopReason: "end_turn" } } },
  ].map(value => JSON.stringify(value)).join("\n");
  try {
    await writeFile(transcriptPath, transcript);
    const project = await t3.project("Markdown links");
    await t3.thread({ project, title: "Leading emoji link", messages: [`Output exactly ${markdown} as Markdown prose.`], model: "showcase" });
  } finally {
    await writeFile(transcriptPath, original);
  }
  await t3.open();
  await screen.getByTestId("sidebar-row-card").press("Enter");
  await screen.getByRole("link", "😀 Read the documentation").waitFor({ state: "visible" });
  await app.screenshot("rendered-link");
  const inspection = await browser.evaluate(() => {
    const link = document.querySelector('a[href="https://example.com"]');
    if (!link) throw new Error("Rendered external link missing");
    const walker = document.createTreeWalker(link, NodeFilter.SHOW_TEXT);
    const nodes: string[] = [];
    while (walker.nextNode()) nodes.push(walker.currentNode.nodeValue ?? "");
    const loneSurrogates = nodes.filter(node => /\p{Surrogate}/u.test(node));
    const panel = document.createElement("pre");
    panel.textContent = "Live DOM inspection — external link text nodes\n\n" + nodes.map((node, i) => `node ${i + 1}: ${JSON.stringify(node)}${i < 2 ? "   " + Array.from(node, ch => 'U+' + ch.codePointAt(0)!.toString(16).toUpperCase()).join(' ') : ""}`).join("\n") + `\n\nLone-surrogate text nodes: ${loneSurrogates.length}`;
    panel.style.cssText = "position:fixed;bottom:24px;right:24px;z-index:99999;background:#101820;color:#fff;border:2px solid #90cdf4;padding:20px;font:16px/1.5 monospace;width:650px;max-width:80vw;white-space:pre-wrap";
    document.body.append(panel);
    return { nodes, loneSurrogates };
  });
  await app.screenshot("text-node-inspection");
  expect(inspection.loneSurrogates).toEqual([]);
});
