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

test("Held overlay and Usage shortcuts act once per physical press", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("Shortcut demo", { "hello.ts": "export const hello = 'world';\n" });
  const thread = await t3.thread({ project, title: "Held shortcut demonstration", messages: ["hello"] });
  await t3.open(thread);
    await screen.getByRole("button", "Toggle terminal drawer").waitFor();
  await screen.getByRole("button", "Toggle terminal drawer").waitFor();
  const results: { shortcut: string; states: boolean[]; consumed: boolean[] }[] = [];
  for (const spec of [
    { key: "k", code: "KeyK", label: "Command palette", shiftKey: false, altKey: false },
    { key: "p", code: "KeyP", label: "File picker", shiftKey: false, altKey: false },
    { key: "F", code: "KeyF", label: "Search project contents", shiftKey: true, altKey: false },
    { key: "T", code: "KeyT", label: "Create theme", shiftKey: true, altKey: true },
  ]) {
    await t3.open(thread);
    await screen.getByRole("button", "Toggle terminal drawer").waitFor();
    const states: boolean[] = [];
    const consumed: boolean[] = [];
    for (let i = 0; i < 5; i++) {
      consumed.push(await browser.evaluate(({ spec, repeat }) => {
        const event = new KeyboardEvent("keydown", { key: spec.key, code: spec.code, ctrlKey: true, shiftKey: spec.shiftKey, altKey: spec.altKey, repeat, bubbles: true, cancelable: true });
        (document.activeElement ?? document.body).dispatchEvent(event);
        return event.defaultPrevented;
      }, { spec, repeat: i > 0 }));
      await browser.evaluate(async () => { await new Promise(resolve => setTimeout(resolve, 550)); return null; });
      states.push(await browser.evaluate(label => [...document.querySelectorAll('[role="dialog"]')].some(el => (el.getAttribute("aria-label") === label) && el.getAttribute("data-state") !== "closed" && !el.hasAttribute("data-ending-style")), spec.label));
      if (i === 0 || i === 1 || i === 4) await app.screenshot(`${spec.code}-${i === 0 ? "initial" : `repeat-${i}`}`);
    }
    await browser.evaluate(spec => { (document.activeElement ?? document.body).dispatchEvent(new KeyboardEvent("keyup", { ...spec, ctrlKey: true, bubbles: true })); return null; }, spec);
    results.push({ shortcut: spec.label, states, consumed });
    // Close through a fresh press if still open, then return to the chat.
    if (states.at(-1)) {
      await browser.evaluate(spec => { (document.activeElement ?? document.body).dispatchEvent(new KeyboardEvent("keydown", { ...spec, ctrlKey: true, bubbles: true, cancelable: true })); return null; }, spec);
      await browser.evaluate(async () => { await new Promise(resolve => setTimeout(resolve, 550)); return null; });
    }
  }
  await t3.open(thread);
    await screen.getByRole("button", "Toggle terminal drawer").waitFor();
  await browser.keyboard.press("Control+u");
  await browser.evaluate(async () => { await new Promise(resolve => setTimeout(resolve, 550)); return null; });
  await app.screenshot("usage-open-before-hold");
  const usageStates: boolean[] = [];
  const usageConsumed: boolean[] = [];
  for (let i = 0; i < 5; i++) {
    usageConsumed.push(await browser.evaluate(repeat => {
      const event = new KeyboardEvent("keydown", { key: "u", code: "KeyU", ctrlKey: true, repeat, bubbles: true, cancelable: true });
      (document.activeElement ?? document.body).dispatchEvent(event);
      return event.defaultPrevented;
    }, i > 0));
    await browser.evaluate(async () => { await new Promise(resolve => setTimeout(resolve, 550)); return null; });
    usageStates.push(await browser.evaluate(() => location.pathname === "/usage"));
    if (i === 0 || i === 1 || i === 4) await app.screenshot(`usage-close-${i === 0 ? "initial" : `repeat-${i}`}`);
  }
  results.push({ shortcut: "Usage stays closed", states: usageStates.map(open => !open), consumed: usageConsumed });
  await expect(results).toEqual(results.map(result => ({ ...result, states: [true, true, true, true, true], consumed: [true, true, true, true, true] })));
});
