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

test("Escape clears spaces and a held Escape keeps Settings open until a fresh press", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("escape-demo");
  const thread = await t3.thread({ project, title: "Settings Escape demonstration", messages: ["Hello"] });
  await t3.open(thread);
  await t3.open("/settings/general");
  const search = screen.getByRole("combobox", "Search settings");
  const pause = (ms: number) => browser.evaluate(async (duration) => {
    await new Promise((resolve) => setTimeout(resolve, duration));
    return null;
  }, ms);
  const state = () => browser.evaluate(() => {
    const input = document.querySelector<HTMLInputElement>('[aria-label="Search settings"]');
    return { open: location.pathname.includes("/settings/"), value: input?.value ?? null, focused: input === document.activeElement };
  });
  await search.tap();
  await browser.keyboard.type("   ");
  await app.screenshot("spaces-before-escape");
  await browser.keyboard.press("Escape");
  await pause(700);
  const spaces = await state();
  await app.screenshot("spaces-after-escape");

  await t3.open("/settings/general");
  await search.tap();
  await browser.keyboard.type("theme");
  await app.screenshot("theme-before-held-escape");
  await browser.keyboard.down("Escape");
  await pause(500);
  const first = await state();
  for (let i = 0; i < 5; i++) {
    await browser.keyboard.down("Escape");
    await pause(40);
  }
  await pause(700);
  const held = await state();
  await app.screenshot("while-escape-held");
  await browser.keyboard.up("Escape");
  await pause(500);
  const released = await state();
  await app.screenshot("after-escape-release");
  await browser.keyboard.press("Escape");
  await pause(700);
  const fresh = await state();
  await app.screenshot("fresh-escape-closes-settings");
  await expect({ spaces, first, held, released, fresh: fresh.open }).toEqual({
    spaces: { open: true, value: "", focused: true },
    first: { open: true, value: "", focused: true },
    held: { open: true, value: "", focused: true },
    released: { open: true, value: "", focused: true },
    fresh: false,
  });
});
