/// <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("Returning to a running thread keeps existing paragraphs visible and new blocks fade", WEB, async ({ t3, app, screen, browser }) => {
  const recording = `${APP_DIR}/apps/server/scripts/dev-replay/showcase_transcript.ndjson`;
  const original = await readFile(recording, "utf8");
  const prose = "Lighthouses have guided sailors along dangerous coastlines for centuries. Ancient keepers tended fires above rocky shores, watching vessels approach through darkness and changing weather. Their work connected distant harbors with the people who depended on safe passage. Over time, builders raised taller towers and developed brighter lamps, while mariners learned to recognize each station by its distinctive light. These landmarks became part of coastal communities, preserving stories of patient service and difficult rescues. Even as navigation changed, the steady beam remained a familiar promise of land nearby. The history of these towers follows the history of trade, engineering, and the enduring care required to travel safely across the sea.";
  const frames: unknown[] = [
    { 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: "Ready to discuss lighthouse history." } } } } },
    { type: "emit_inbound", frame: { kind: "response", method: "session/prompt", result: { stopReason: "end_turn" } } },
{ type: "expect_outbound", frame: { kind: "request", method: "session/prompt", params: "<any>" } }];
  for (let i = 1; i <= 15; i++) frames.push({ type: "emit_inbound", afterMs: 2000, frame: { kind: "notification", method: "session/update", params: { sessionId: "dev-replay-session", update: { sessionUpdate: "agent_message_chunk", content: { type: "text", text: `Paragraph ${i}. ${prose}\n\n` } } } } });
  frames.push({ type: "emit_inbound", frame: { kind: "response", method: "session/prompt", result: { stopReason: "end_turn" } } });
  await writeFile(recording, frames.map(x => JSON.stringify(x)).join("\n"));
  try {
    const project = await t3.project("Lighthouse history");
    const thread = await t3.thread({ project, title: "History of lighthouses", messages: ["Start"], model: "showcase" });
    await browser.setViewport({ width: 1600, height: 1200 });
    await t3.open(thread);
    await screen.getByRole("textbox").fill("Without using any tools, write a 15-paragraph essay on the history of lighthouses. Each paragraph should be about 120 words. Plain prose, no headings.");
    await screen.getByRole("textbox").press("Enter");
    await browser.evaluate(async () => {
      await new Promise<void>(resolve => {
        const ready = () => {
          const roots = document.querySelectorAll('.chat-markdown[data-streaming]');
          const ps = roots[roots.length - 1]?.querySelectorAll(':scope > p');
          return ps && ps.length >= 4 && Array.from(ps).slice(0,4).every(p => getComputedStyle(p).opacity === '1');
        };
        if (ready()) return resolve();
        const timer = setInterval(() => { if (ready()) { clearInterval(timer); resolve(); } }, 20);
      });
      return null;
    });
    await app.screenshot("four-paragraphs-before-navigation");
    await screen.getByRole("button", "New thread", { exact: true }).tap();
    await browser.evaluate(async () => { await new Promise(r => setTimeout(r, 1500)); return null; });
    const opacity = await browser.evaluate(async () => {
      const mounted = new Promise<number[]>(resolve => {
        const observer = new MutationObserver(() => {
          const roots = Array.from(document.querySelectorAll('.chat-markdown'));
          const root = roots.findLast(r => r.textContent?.startsWith('Paragraph 1.'));
          if (!root) return;
          observer.disconnect();
          requestAnimationFrame(() => requestAnimationFrame(() => resolve(Array.from(root.querySelectorAll(':scope > p')).slice(0,4).map(p => Number(getComputedStyle(p).opacity)))));
        });
        observer.observe(document.body, { childList: true, subtree: true });
      });
      history.back();
      return await mounted;
    });
    await app.screenshot("existing-text-immediately-after-back");
    expect(opacity).toEqual([1,1,1,1]);
    const newBlockFaded = await browser.evaluate(async () => {
      const root = Array.from(document.querySelectorAll('.chat-markdown')).findLast(r => r.textContent?.startsWith('Paragraph 1.'))!;
      const existing = new Set(root.querySelectorAll(':scope > p'));
      return await new Promise<boolean>(resolve => {
        const observer = new MutationObserver(() => {
          const fresh = Array.from(root.querySelectorAll(':scope > p')).find(p => !existing.has(p));
          if (!fresh) return;
          observer.disconnect();
          requestAnimationFrame(() => requestAnimationFrame(() => resolve(Number(getComputedStyle(fresh).opacity) < 1)));
        });
        observer.observe(root, { childList: true, subtree: true });
      });
    });
    await app.screenshot("new-paragraph-fades-in");
    expect(newBlockFaded).toBe(true);
  } finally { await writeFile(recording, original); }
});
