import { createServer } from "node:http";
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("Adopted popup inherits the opener's explicit Dark appearance", WEB, async ({ t3, app, screen, browser }) => {
  let darkReady!: () => void;
  let latestChildScheme = "";
  let childReady!: (scheme: string) => void;
  const dark = new Promise<void>(resolve => { darkReady = resolve; });
  const child = new Promise<string>(resolve => { childReady = resolve; });
  const server = createServer((req, res) => {
    const url = new URL(req.url!, "http://127.0.0.1:47123");
    if (url.pathname === "/report") {
      if (url.searchParams.get("page") === "child") { latestChildScheme = url.searchParams.get("scheme")!; childReady(latestChildScheme); }
      else if (url.searchParams.get("scheme") === "DARK") darkReady();
      res.end("ok"); return;
    }
    const isChild = url.pathname === "/child.html";
    res.setHeader("Content-Type", "text/html");
    res.end(`<!doctype html><html><head><title>${isChild ? "Child popup" : "Opener"}</title><style>html{color-scheme:light dark}body{margin:0;padding:28px;font:24px system-ui;background:#fff;color:#111}button{width:100%;height:150px;font:28px system-ui}@media(prefers-color-scheme:dark){body{background:#151515;color:#fff}}</style></head><body>${isChild ? "<h1 style=margin-top:220px;font-size:32px>Child popup</h1>" : '<button onclick="window.open(\'/child.html\',\'_blank\')">Open popup</button><h1>Opener</h1>'}<p id="scheme"></p><script>const m=matchMedia('(prefers-color-scheme:dark)');function report(){const s=m.matches?'DARK':'LIGHT';document.querySelector('#scheme').textContent='prefers-color-scheme: '+s;fetch('/report?page=${isChild ? "child" : "opener"}&scheme='+s)}m.addEventListener('change',report);report();</script></body></html>`);
  });
  await new Promise<void>(resolve => server.listen(47123, "127.0.0.1", resolve));
  try {
    await browser.setViewport({ width: 1440, height: 1000 });
    const project = await t3.project("Appearance demo");
    const thread = await t3.thread({ project, title: "Popup appearance", messages: ["first"] });
    await t3.open(thread);
    await screen.getByRole("button", "Toggle right panel").tap();
    await screen.getByRole("button", "Add panel surface").tap();
    await screen.getByRole("menuitem", /^Browser/).tap();
    await screen.getByRole("textbox", "Search or enter URL").fill("http://127.0.0.1:47123/index.html");
    await browser.keyboard.press("Enter");
    await screen.getByRole("button", "Preview menu").tap();
    await screen.getByRole("menuitem", "Appearance", { exact: true }).tap();
    await screen.getByRole("menuitemradio", "Dark", { exact: true }).tap();
    await dark;
    await browser.keyboard.press("Escape");
    await browser.keyboard.press("Escape");
    await app.screenshot("opener-dark");
    const point = await browser.evaluate(() => {
      const c = document.querySelector('canvas') as HTMLCanvasElement;
      const r = c.getBoundingClientRect();
      const fit = Math.min(r.width / c.width, r.height / c.height);
      return { x: r.x + r.width / 2, y: r.y + (r.height - c.height * fit) / 2 + 90 * fit };
    });
    await browser.mouse.move(point.x, point.y);
    await browser.mouse.down();
    await browser.mouse.up();
    await child;
    await screen.getByRole("button", /^(Child popup|127\.0\.0\.1:47123)$/).tap();
    await screen.getByRole("button", "Preview menu").tap();
    await screen.getByRole("menuitem", "Appearance", { exact: true }).tap();
    await screen.getByRole("menuitemradio", "System", { exact: true }).waitFor();
    await app.screenshot("adopted-child-appearance");
    await browser.keyboard.press("Escape");
    await browser.keyboard.press("Escape");
    await screen.getByRole("button", "Opener", { exact: true }).tap();
    await app.screenshot("opener-still-dark");
    await screen.getByRole("button", /^(Child popup|127\.0\.0\.1:47123)$/).tap();
    await screen.getByRole("button", "Preview menu").tap();
    await screen.getByRole("menuitem", "Appearance", { exact: true }).tap();
    await expect(screen.getByRole("menuitemradio", "Dark", { exact: true })).toBeChecked();
    expect(latestChildScheme).toBe("DARK");
  } finally {
    await new Promise<void>(resolve => server.close(() => resolve()));
  }
});
