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

test("A loaded single-file conflict keeps its Alias filename after a failed batch", 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 input missing");
      const transfer = new DataTransfer();
      for (const name of names) transfer.items.add(new File([name.startsWith("Invalid") ? "not JSON" : JSON.stringify({version:1,name:"Dusk",appearance:"dark",colors:{accent:"#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(["Alias"]);
  await dialog.getByText("Alias.json",{exact:true}).waitFor();
  await choose(["Invalid1","Invalid2"]);
  await dialog.getByText(/Invalid1.json:/).waitFor();
  await app.screenshot("alias-loaded-after-failed-batch");
  await dialog.getByRole("button","Add theme",{exact:true}).tap();
  await dialog.getByRole("button","Keep both",{exact:true}).tap();
  await dialog.waitFor({state:"hidden"});
  await browser.evaluate(() => {
    [...document.querySelectorAll("*")].find(el=>el.textContent==="Alias")?.scrollIntoView({block:"center"});
    return null;
  });
  await app.screenshot("alias-copy-installed");
  const labels=await browser.evaluate(()=>JSON.parse(localStorage.getItem("t3code:themes:v1")??"[]").map((theme:{label:string})=>theme.label));
  expect(labels).toEqual(["Dusk","Alias"]);
});
