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

test("Keep both stops before an emoji crossing the theme name limit", WEB, async ({ t3, app, screen, browser }) => {
  await t3.project("demo");
  await t3.open("/settings/appearance");
  const upload = async (filename: string) => {
    await screen.getByRole("button", "Add theme", { exact: true }).tap();
    await browser.evaluate((name) => {
      const target = document.querySelector('input[type="file"]')?.parentElement;
      if (!target) throw new Error("No theme file drop target");
      const json = JSON.stringify({version:1,name:"Dusk",appearance:"dark",colors:{accent:"#3b82f6"}});
      const transfer = new DataTransfer();
      transfer.items.add(new File([json], name, {type:"application/json"}));
      target.dispatchEvent(new DragEvent("drop", {dataTransfer:transfer,bubbles:true,cancelable:true}));
      return null;
    }, filename);
    const dialog = screen.getByRole("dialog", "Add a theme");
    await dialog.getByRole("button", "Add theme", {exact:true}).tap();
    return dialog;
  };
  const first = await upload("Dusk.json");
  await first.waitFor({state:"hidden"});
  const conflict = await upload(`${"a".repeat(47)}🌙.json`);
  await conflict.getByText("Already installed").waitFor();
  await conflict.getByRole("button", "Keep both").tap();
  await conflict.waitFor({state:"hidden"});
  await screen.getByRole("button", /^Edit a{47}/).tap();
  const name = screen.getByRole("textbox", "Theme name", {exact:true});
  await name.waitFor();
  await browser.evaluate(() => {
    const input = document.querySelector<HTMLInputElement>('input[placeholder="Theme name"]')!;
    input.focus();
    input.setSelectionRange(input.value.length, input.value.length);
    input.scrollLeft = input.scrollWidth;
    return null;
  });
  await app.screenshot("kept-copy-theme-name");
  await expect(name).toHaveValue("a".repeat(47));
});
