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

const body = `★ Insight\n\n## Centered image pair\n\n<p align="center">\n  <img src="/proof-image.svg" alt="Preview Dark" width="49%" />\n  <img src="/proof-image.svg" alt="Preview Light" width="49%" />\n</p>\n\n## Single centered image\n\n<p align="center">\n  <img src="/proof-image.svg" alt="Single Preview" width="160" />\n</p>\n\n## Badge and link row\n\n<p align="center">\n<a href="https://example.com/one"><img src="/proof-image.svg" alt="Build badge" width="80" />Build passing</a>\n<a href="https://example.com/two"><img src="/proof-image.svg" alt="License badge" width="80" />MIT license</a>\n</p>\n\n## Raw HTML list\n\n<ul><li>one\ntwo</li></ul>\n\n## Known gap: paragraph without attributes\n\n<p>plain one\nplain two</p>`;

test("Raw HTML keeps HTML whitespace with line breaks enabled", WEB, async ({t3, app, browser, screen}) => {
  const fixture = `${APP_DIR}/apps/server/scripts/dev-replay/showcase_transcript.ndjson`;
  const image = `${APP_DIR}/apps/web/public/proof-image.svg`;
  const original = await readFile(fixture, "utf8");
  await writeFile(image, '<svg xmlns="http://www.w3.org/2000/svg" width="240" height="60"><rect width="240" height="60" fill="#286d96"/><text x="120" y="37" text-anchor="middle" fill="white" font-size="20">Image preview</text></svg>');
  const entries = [
    {type:"expect_outbound", frame:{kind:"request",method:"session/prompt",params:"<any>"}},
    {type:"emit_inbound",frame:{kind:"notification",method:"session/update",params:{sessionId:"replay",update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:body.replaceAll("/proof-image.svg", `${app.baseUrl}/proof-image.svg`)}}}}},
    {type:"emit_inbound",frame:{kind:"response",method:"session/prompt",result:{stopReason:"end_turn"}}},
  ];
  await writeFile(fixture, entries.map(x=>JSON.stringify(x)).join("\n"));
  try {
    const project = await t3.project("html-demo");
    const thread = await t3.thread({project,title:"HTML whitespace",messages:["Show the HTML examples"],model:"showcase"});
    await browser.setViewport({width:1280,height:1100});
    await t3.open(thread);
    await screen.getByText("Raw HTML list", {exact:true}).waitFor();
    await browser.locator('img[alt="Single Preview"]').waitFor();
    await screen.getByText(/^Syncing messages/).waitFor({state:"hidden", timeout:60_000});
    await expect.poll(() => browser.evaluate(() => document.querySelector('img[alt="Preview Dark"]')?.getAttribute("src"))).toContain("proof-image.svg");
    await browser.evaluate(async () => {
      await Promise.all([...document.images].map(i => i.decode().catch(()=>{})));
      document.querySelector('img[alt="Preview Dark"]')?.scrollIntoView({block:"start"});
      return null;
    });
    await app.screenshot("raw-html-all-cases");
    const observed = await browser.evaluate(() => {
      const pair = document.querySelector('img[alt="Preview Dark"]')!;
      const other = document.querySelector('img[alt="Preview Light"]')!;
      const single = document.querySelector('img[alt="Single Preview"]')!;
      const links = [...document.querySelectorAll('a')].filter(a => a.textContent === "Build passing" || a.textContent === "MIT license");
      const li = [...document.querySelectorAll('li')].find(e=>e.textContent?.replace(/\s/g,"") === "onetwo")!;
      return {
        pairBreaks:pair.parentElement!.querySelectorAll("br").length,
        pairSameRow:Math.abs(pair.getBoundingClientRect().top-other.getBoundingClientRect().top)<2,
        singleStandalone:single.hasAttribute("data-standalone"),
        singleBreaks:single.parentElement!.querySelectorAll("br").length,
        badgesSameRow:Math.abs(document.querySelector('img[alt="Build badge"]')!.getBoundingClientRect().top-document.querySelector('img[alt="License badge"]')!.getBoundingClientRect().top)<2,
        linksSameRow:Math.abs(links[0]!.getBoundingClientRect().top-links[1]!.getBoundingClientRect().top)<2,
        listBreaks:li.querySelectorAll("br").length,
      };
    });
    expect(observed).toEqual({pairBreaks:0,pairSameRow:true,singleStandalone:true,singleBreaks:0,linksSameRow:true,badgesSameRow:true,listBreaks:0});
  } finally {
    await writeFile(fixture,original);
    await unlink(image);
  }
});
