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

test("Escape closes only the open theme variant picker before Settings", WEB, async ({t3, app, screen, browser}) => {
  await t3.project("Theme keyboard demo");
  await browser.emulateMedia({colorScheme: "light"});
  await t3.open("/settings/appearance");
  await screen.getByRole("button", "Add theme", {exact:true}).tap();
  await browser.evaluate(() => {
    const input = document.querySelector<HTMLInputElement>('input[type="file"]');
    if (!input) throw new Error("Missing theme input");
    const files = new DataTransfer();
    for (const name of ["Dawn", "Dusk", "Midnight"]) {
      files.items.add(new File([JSON.stringify({version:1, name, appearance: name === "Dawn" ? "light" : "dark", collection:{id:"sky",label:"Sky"}, colors:{canvas:name === "Dawn" ? "#fafafa" : "#101014",accent:"#6d5ae6"}})], `${name}.json`, {type:"application/json"}));
    }
    input.files = files.files;
    input.dispatchEvent(new Event("change", {bubbles:true}));
    return null;
  });
  const light = screen.getByRole("button", "Use light variant, currently Dawn", {exact:true});
  const settle = () => browser.evaluate(async () => {
    await new Promise<void>(r => requestAnimationFrame(() => requestAnimationFrame(() => r())));
    await Promise.all(document.getAnimations().filter(a => a.effect?.getComputedTiming().iterations !== Infinity).map(a => a.finished.catch(() => {})));
    return null;
  });
  const secondEscapes: boolean[] = [];
  const results: Array<{settings:boolean, focus:string, open:boolean}> = [];
  const read = () => browser.evaluate(() => {
    const option = document.querySelector('[aria-label="Use Dusk for dark mode"]');
    return {settings:!!document.querySelector('[data-settings-page-scroll]'),focus:document.activeElement?.getAttribute("aria-label") ?? "",open:!!option && getComputedStyle(option).pointerEvents !== "none"};
  });
  for (const fromOption of [false,true]) {
    await t3.open("/settings/appearance");
    await settle();
    await browser.evaluate(() => { document.querySelector('[aria-label="Use light variant, currently Dawn"]')?.closest('[data-theme-library-card]')?.scrollIntoView({block:"center"}); return null; });
    await browser.mouse.move(1200, 100);
    await light.focus();
    await browser.keyboard.press("Tab");
    await settle();
    if (fromOption) {
      await browser.keyboard.press("Tab");
      await settle();
    }
    await browser.evaluate(() => { const scroller = document.querySelector<HTMLElement>('[data-settings-page-scroll]'); if(scroller) scroller.scrollTop = 330; return null; });
    await settle();
    const focused = await browser.evaluate(() => document.activeElement?.getAttribute("aria-label"));
    if (focused !== (fromOption ? "Use Dusk for dark mode" : "Choose dark variant, 2 options, currently Dusk")) throw new Error(`Wrong starting focus: ${focused}`);
    await app.screenshot(fromOption ? "option-before-escape" : "trigger-before-escape");
    await browser.keyboard.press("Escape");
    await settle();
    await app.screenshot(fromOption ? "option-after-first-escape" : "trigger-after-first-escape");
    results.push(await read());
    await browser.keyboard.press("Escape");
    await settle();
    await app.screenshot(fromOption ? "option-after-second-escape" : "trigger-after-second-escape");
    secondEscapes.push((await read()).settings);
  }
  await t3.open("/settings/appearance");
  await settle();
  await light.focus();
  await settle();
  await browser.keyboard.press("Escape");
  await settle();
  await app.screenshot("single-variant-after-escape");
  const single = await read();
  expect(results).toEqual([false,true].map(() => ({settings:true,focus:"Choose dark variant, 2 options, currently Dusk",open:false})));
  expect(secondEscapes).toEqual([false,false]);
  expect(single.settings).toBe(false);
});
