/// <reference lib="dom" />
import * as NodeHttp from "node:http";
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("Long preview titles keep a flag emoji whole", WEB, async ({ t3, app, browser, screen }) => {
  const server = NodeHttp.createServer((request, response) => {
    const control = request.url === "/control.html";
    const count = control ? 508 : 510;
    response.writeHead(200, { "content-type": "text/html; charset=utf-8" });
    response.end(`<!doctype html><meta charset="utf-8"><title>${"a".repeat(count)}🇯🇵END</title><body style="font:20px system-ui;padding:24px"><h1>Preview title boundary</h1><p>${control ? "Control" : "Boundary"}: ${count} ASCII a characters + 🇯🇵 + END</p><p>Hover the Browser tab to inspect the server-reported title.</p></body>`);
  });
  await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
  try {
    const address = server.address();
    if (!address || typeof address === "string") throw new Error("No fixture port");
    const project = await t3.project("flag-title");
    const thread = await t3.thread({ project, title: "Preview title boundary", messages: ["first"] });
    await t3.open(thread);
    await screen.getByRole("button", "Toggle right panel").tap();
    await screen.getByRole("button", "Browser B").tap();
    const input = screen.getByRole("textbox", "Search or enter URL");
    const tab = screen.getByRole("button", /^aaaa/);
    const readTitle = () => browser.evaluate(() => [...document.querySelectorAll('button')].find(el => el.textContent?.startsWith("aaaa"))?.querySelector("span.truncate")?.textContent ?? "");
    const results: string[] = [];
    for (const [path, label] of [["bug.html", "boundary-title"], ["control.html", "control-title"], ["bug.html", "boundary-revisited"]]) {
      await input.fill(`http://127.0.0.1:${address.port}/${path}`);
      await browser.keyboard.press("Enter");
      await tab.waitFor();
      // A changed URL is followed by its title in the real preview navigation state.
      await browser.locator('canvas:has(~ textarea[aria-label="Browser page"])').waitFor();
      await tab.hover();
      await browser.locator('[data-slot="tooltip-popup"]').waitFor();
      await browser.evaluate(async () => {
        await document.fonts.ready;
        const popup = document.querySelector('[data-slot="tooltip-popup"]');
        await Promise.all(popup?.getAnimations({ subtree: true }).map(animation => animation.finished.catch(() => {})) ?? []);
      });
      await app.screenshot(label!);
      results.push(await readTitle());
      await input.tap();
    }
    expect(results).toEqual(["a".repeat(510), "a".repeat(508) + "🇯🇵", "a".repeat(510)]);
  } finally {
    await new Promise<void>((resolve) => server.close(() => resolve()));
  }
});
