import { mkdir, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect } from "e2e";
import { T3_HOME } from "../e2e.config.ts";
import { test, WEB } from "./t3.ts";

// The published copy deliberately differs from the imported palette and has an unmistakable image.
const imported = { version: 1, name: "Promenade of the Condemned", appearance: "dark", css: '[data-workspace-area="conversation"] { background: var(--theme-background-image, #162327) center / cover no-repeat; }', colors: { canvas: "#162327", accent: "#cc3344", warningForeground: "#0b1a1e" } };

test("an imported theme consistently wins over a published theme with the same id", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("Theme collision demo");
  const thread = await t3.thread({ project, title: "Imported theme collision", messages: ["Show the theme collision demo"] });
  await t3.open("/settings/appearance");
  await screen.getByRole("button", "Add theme", { exact: true }).tap();
  await screen.getByRole("textbox", "Theme JSON").fill(JSON.stringify(imported));
  await screen.getByRole("button", "Add theme", { exact: true }).last().tap();
  const themes = join(T3_HOME, "userdata", "themes");
  await mkdir(themes, { recursive: true });
  await writeFile(join(themes, "promenade-of-the-condemned.json"), JSON.stringify({ ...imported, colors: { ...imported.colors, accent: "#22aa55", warningForeground: "#e2c044" } }));
  // A tiny solid magenta PNG, generated as a fixture rather than copied from private data.
  await writeFile(join(themes, "promenade-of-the-condemned.png"), Buffer.from("iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAIAAAD8GO2jAAAAJ0lEQVR4nO3NMQkAAAwDsPo33anoMQjkT5pORSAQCAQCgUAgEHwJDmDu+GrYQW2TAAAAAElFTkSuQmCC", "base64"));
  await screen.getByRole("button", "Use dark mode").tap();
  await browser.reload();
  await screen.getByRole("button", "Use dark mode").tap();
  await browser.evaluate(() => new Promise<void>((resolve) => setTimeout(resolve, 1500)));
  await screen.getByText("Promenade of the Condemned", { exact: true }).first().scrollIntoView();
  await app.screenshot("imported-theme-palette");
  await t3.open(thread);
  await browser.evaluate(() => new Promise<void>((resolve) => setTimeout(resolve, 2500)));
  await app.screenshot("imported-theme-collision");
  const background = await browser.evaluate(() => document.documentElement.style.getPropertyValue("--theme-background-image"));
  await expect(background).toBe("");
});
