/// <reference lib="dom" />
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("Imported var() background shorthands cannot request remote images", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("Theme probe");
  const thread = await t3.thread({ project, title: "Theme resource probe", messages: ["Show a short greeting"], model: "multi-turn" });
  const requests: string[] = [];
  await browser.route("https://example.com/theme-shorthand-probe-*", async (route) => {
    requests.push(route.request.url);
    await route.fulfill({ contentType: "image/svg+xml", body: '<svg xmlns="http://www.w3.org/2000/svg" width="900" height="600"><rect width="900" height="600" fill="#8b1425"/><text x="40" y="280" fill="white" font-size="36">REMOTE IMAGE REQUESTED</text></svg>' });
  });
  const results: { variant: string; image: string; requests: number }[] = [];
  for (const variant of ["override", "intact"]) {
    await t3.open("/settings/appearance");
    await screen.getByRole("button", "Use dark mode", { exact: true }).tap();
    await screen.getByRole("button", "Add theme", { exact: true }).tap();
    const css = `[data-workspace-area="conversation"] { background: var(--screen-missing, url(https://example.com/theme-shorthand-probe-${variant})); ${variant === "override" ? "background-color: red;" : ""} }`;
    await browser.evaluate(({ css, variant }) => {
      const files = new DataTransfer();
      files.items.add(new File([JSON.stringify({ version: 1, id: `probe-${variant}`, name: `Probe ${variant}`, appearance: "dark", colors: { canvas: "#18181b", accent: "#8b5cf6" }, css })], `probe-${variant}.json`, { type: "application/json" }));
      const target = document.querySelector('input[type="file"]')?.parentElement;
      if (!target) throw new Error("No theme file drop target");
      target.dispatchEvent(new DragEvent("drop", { dataTransfer: files, bubbles: true, cancelable: true }));
      return null;
    }, { css, variant });
    const dialog = screen.getByRole("dialog", "Add a theme");
    await dialog.getByRole("button", "Add theme", { exact: true }).tap();
    await dialog.waitFor({ state: "hidden" });
    await screen.getByRole("button", `Use Probe ${variant} theme`, { exact: true }).tap();
    await t3.open(thread);
    await screen.getByRole("textbox").first().waitFor({ state: "visible" });
    await screen.getByText("Publish repository", { exact: true }).waitFor({ state: "visible" });
    await screen.getByText("Syncing messages...", { exact: true }).waitFor({ state: "hidden" });
    const image = await browser.evaluate(async () => {
      await document.fonts.ready;
      await new Promise<void>(resolve => requestAnimationFrame(() => requestAnimationFrame(() => resolve())));
      const area = document.querySelector('[data-workspace-area="conversation"]');
      if (!area) throw new Error("No conversation area");
      return getComputedStyle(area).backgroundImage;
    });
    results.push({ variant, image, requests: requests.filter(url => url.endsWith(variant)).length });
    await browser.evaluate((result) => {
      document.getElementById("resource-probe-report")?.remove();
      const panel = document.createElement("aside");
      panel.id = "resource-probe-report";
      panel.style.cssText = "position:fixed;bottom:80px;right:30px;z-index:2147483647;width:560px;padding:20px;background:#111827;color:white;border:3px solid #94a3b8;border-radius:8px;font:16px/1.6 monospace;white-space:pre-wrap;pointer-events:none";
      panel.textContent = `Browser resource probe (instrumentation)\nCase: ${result.variant}\nRemote image requests: ${result.requests}\nComputed background-image:\n${result.image}`;
      document.body.append(panel);
      return null;
    }, results[results.length - 1]);
    await app.screenshot(`shorthand-${variant}`);
  }
  await expect(results.map(result => ({ variant: result.variant, image: result.image, requests: result.requests }))).toEqual([
    { variant: "override", image: "none", requests: 0 },
    { variant: "intact", image: "none", requests: 0 },
  ]);
});
