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

test("An open font preview follows appearance and palette changes", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("font-demo", { "sample.ttf": new Uint8Array(await readFile("/usr/share/fonts/truetype/lato/Lato-Medium.ttf")) });
  const thread = await t3.thread({ project, title: "Font preview", messages: ["Start"] });
  await t3.open(thread);
  await screen.getByText("first fixture turn complete", { exact: false }).waitFor();
  const choose = async (menu: string, item: string) => {
    await browser.keyboard.press("Control+k");
    const palette = screen.getByRole("dialog", "Command palette");
    await palette.getByRole("combobox").fill(`> ${menu}`);
    await palette.getByRole("option", new RegExp(`^${menu}(?: |$)`)).tap();
    await screen.getByRole("option", new RegExp(`^${item}(?: Current)?$`)).tap();
  };
  await choose("Change appearance", "Light");
  await browser.keyboard.press("Control+p");
  await screen.getByPlaceholder("Search files…").fill("sample.ttf");
  await screen.getByRole("option", "sample.ttf", { exact: false }).tap();
  await browser.frameLocator('iframe[title="sample.ttf"]').getByRole("heading", "Font preview").waitFor();
  await app.screenshot("light-initial");
  const colors = () => browser.evaluate(() => {
    const root = getComputedStyle(document.documentElement);
    const src = document.querySelector<HTMLIFrameElement>('iframe[title="sample.ttf"]')?.srcdoc ?? "";
    return {
      background: src.match(/background:([^;}]+)/)?.[1]?.trim(),
      foreground: src.match(/;color:([^;}]+)/)?.[1]?.trim(),
      expectedBackground: root.getPropertyValue("--background").trim(),
      expectedForeground: root.getPropertyValue("--foreground").trim(),
    };
  });
  await choose("Change appearance", "Dark");
  await app.screenshot("dark-preview");
  const dark = await colors();
  await choose("Change theme", "Ocean");
  await app.screenshot("ocean-preview");
  const ocean = await colors();
  expect({ background: dark.background, foreground: dark.foreground }).toEqual({ background: dark.expectedBackground, foreground: dark.expectedForeground });
  expect({ background: ocean.background, foreground: ocean.foreground }).toEqual({ background: ocean.expectedBackground, foreground: ocean.expectedForeground });
});
