import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("Keep both falls back to Dusk (1) for reserved dark filename", WEB, async ({ t3, app, screen, browser }) => {
  await t3.project("demo");
  await t3.open("/settings/appearance");
  const importFile = async (filename: string, accent: string) => {
    await screen.getByRole("button", "Add theme", { exact: true }).tap();
    await browser.evaluate(({filename, accent}) => {
      const input = document.querySelector<HTMLInputElement>('input[type="file"]');
      if (!input) throw new Error("Theme file input missing");
      const files = new DataTransfer();
      files.items.add(new File([JSON.stringify({version: 1, name: "Dusk", appearance: "dark", colors: {accent}})], filename, {type: "application/json"}));
      input.files = files.files;
      input.dispatchEvent(new Event("change", {bubbles: true}));
      return null;
    }, {filename, accent});
    await screen.getByRole("dialog", "Add a theme").getByRole("button", "Add theme", {exact: true}).tap();
  };
  await importFile("dusk.json", "#112233");
  await screen.getByRole("dialog", "Add a theme").waitFor({state: "hidden"});
  await importFile("dark.json", "#336699");
  await screen.getByRole("button", "Keep both").tap();
  try {
    await expect.poll(() => browser.evaluate(() => JSON.parse(localStorage.getItem("t3code:themes:v1") ?? "[]").map((t: {id: string; label: string; colors: unknown}) => ({id: t.id, label: t.label})))).toEqual([{id: "dusk", label: "Dusk"}, {id: "dusk-1", label: "Dusk (1)"}]);
  } finally {
    const copied = await browser.evaluate(() => JSON.parse(localStorage.getItem("t3code:themes:v1") ?? "[]").some((t: {id: string}) => t.id === "dusk-1"));
    if (copied) {
      await screen.getByRole("dialog", "Add a theme").waitFor({state: "hidden"});
      await browser.evaluate(() => {
        const copy = document.querySelector('button[aria-label^="Use Dusk (1) theme"]');
        copy?.scrollIntoView({block: "center"});
        return null;
      });
    }
    await app.screenshot("keep-both-reserved-filename");
  }
});
