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

test("A batch conflict keeps its theme name after an unrelated file selection", WEB, async ({ t3, app, browser, screen }) => {
  await t3.project("demo");
  await t3.open("/settings/appearance");
  const choose = async (names: string[]) => {
    await browser.evaluate((names) => {
      const input = document.querySelector<HTMLInputElement>('input[type="file"]');
      if (!input) throw new Error("Theme file input missing");
      const transfer = new DataTransfer();
      for (const name of names) transfer.items.add(new File([JSON.stringify({version: 1, name, appearance: "dark", colors: {accent: name === "Dawn" ? "#e39045" : "#734ee4"}})], `${name}.json`, {type: "application/json"}));
      input.files = transfer.files;
      input.dispatchEvent(new Event("change", { bubbles: true }));
      return null;
    }, names);
  };
  await screen.getByRole("button", "Add theme", {exact:true}).tap();
  const dialog = screen.getByRole("dialog", "Add a theme");
  await choose(["Dusk"]);
  await dialog.getByText("Dusk.json", {exact:true}).waitFor();
  await dialog.getByRole("button", "Add theme", {exact:true}).tap();
  await dialog.waitFor({state:"hidden"});
  await screen.getByRole("button", "Add theme", {exact:true}).tap();
  await choose(["Unrelated"]);
  await dialog.getByText("Unrelated.json", {exact:true}).waitFor();
  await choose(["Dawn", "Dusk"]);
  await dialog.getByRole("button", "Keep both", {exact:true}).waitFor();
  await app.screenshot("batch-conflict-before-keep-both");
  await dialog.getByRole("button", "Keep both", {exact:true}).tap();
  await dialog.waitFor({state:"hidden"});
  await app.screenshot("themes-after-keep-both");
  await browser.evaluate(() => {
    const label = [...document.querySelectorAll("*")].find((el) => el.textContent === "Dawn");
    label?.scrollIntoView({block: "center"});
    return null;
  });
  await app.screenshot("installed-theme-labels");
  const labels = await browser.evaluate(() => JSON.parse(localStorage.getItem("t3code:themes:v1") ?? "[]").map((theme: {label:string}) => theme.label));
  expect(labels).toEqual(["Dusk", "Dawn", "Dusk (1)"]);
});
