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

test("held Escape stops at the command list from file and content search", WEB, async ({ t3, app, browser }) => {
  const project = await t3.project("demo", { "hello.ts": "export const hello = 'world';\n" });
  const thread = await t3.thread({ project, title: "Search demo", messages: ["hello"] });
  const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
  const state = () => browser.evaluate(() => {
    const p = document.querySelector('[data-command-palette]');
    return p && !p.hasAttribute('data-closed') && !p.hasAttribute('data-ending-style') && p.getAttribute('data-state') !== 'closed'
      ? p.getAttribute('data-palette-mode') : 'closed';
  });
  const results: Record<string, string[]> = {};
  for (const [mode, shortcut] of [["files", "Control+p"], ["content", "Control+Shift+f"]]) {
    await t3.open(thread);
    await browser.locator('[data-testid="composer-editor"]').waitFor();
    await browser.keyboard.press(shortcut);
    await browser.locator(`[data-palette-mode="${mode}"]`).waitFor();
    await app.screenshot(`${mode}-search-open`);
    await browser.keyboard.down("Escape");
    await wait(440);
    const seen = [await state()];
    for (let i = 0; i < 6; i++) {
      await browser.keyboard.down("Escape");
      await wait(33);
      seen.push(await state());
    }
    await wait(500);
    await app.screenshot(`${mode}-escape-still-held`);
    seen.push(await state());
    await browser.keyboard.up("Escape");
    await wait(800);
    seen.push(await state());
    await browser.keyboard.press("Escape");
    await wait(500);
    seen.push(await state());
    results[mode] = seen;
  }
  await t3.open(thread);
    await browser.locator('[data-testid="composer-editor"]').waitFor();
  await browser.keyboard.press("Control+p");
  await browser.locator('[data-palette-mode="files"]').waitFor();
  await browser.keyboard.press("Escape");
  await wait(800);
  const tap = await state();
  await app.screenshot("fresh-tap-command-list");
  await browser.keyboard.press("Escape");
  await wait(500);
  results.control = [tap, await state()];
  console.log(JSON.stringify(results));
  expect(results).toEqual({
    files: [...Array(9).fill("command"), "closed"],
    content: [...Array(9).fill("command"), "closed"],
    control: ["command", "closed"],
  });
});
