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

test("Held, modified, and composing Backspace stay in a submenu", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("demo");
  const thread = await t3.thread({ project, title: "Palette keyboard proof", messages: ["hello"] });
  await t3.open(thread);
  await screen.getByTestId("composer-editor").waitFor();
  const openTheme = async () => {
    await t3.open(thread);
    await screen.getByTestId("composer-editor").waitFor();
    await browser.keyboard.press("Control+k");
    await screen.getByPlaceholder("Search commands, projects, and threads...", { exact: true }).waitFor();
    await screen.getByPlaceholder("Search commands, projects, and threads...", { exact: true }).fill("Change theme");
    await screen.getByRole("option", "Change theme", { exact: false }).waitFor();
    await browser.keyboard.press("Enter");
    await screen.getByPlaceholder("Search...", { exact: true }).waitFor();
  };
  const state = () => browser.evaluate(() => {
    const input = document.querySelector('[role="dialog"] input') as HTMLInputElement;
    return { placeholder: input?.placeholder, query: input?.value };
  });
  const results = [];
  await openTheme();
  await browser.keyboard.type("dar");
  await browser.keyboard.down("Backspace");
  await browser.keyboard.down("Backspace");
  await browser.keyboard.down("Backspace");
  await app.screenshot("held-query-emptied");
  await browser.keyboard.down("Backspace");
  await browser.keyboard.up("Backspace");
  await app.screenshot("held-extra-repeat");
  results.push(await state());
  for (const modifier of ["Control", "Alt", "Shift", "Meta"]) {
    await openTheme();
    await browser.keyboard.press(`${modifier}+Backspace`);
    await app.screenshot(`${modifier.toLowerCase()}-backspace`);
    results.push(await state());
  }
  await openTheme();
  await browser.evaluate(() => {
    document.activeElement?.dispatchEvent(new KeyboardEvent("keydown", {
      key: "Backspace", code: "Backspace", isComposing: true, bubbles: true, cancelable: true,
    }));
    return null;
  });
  await app.screenshot("composing-backspace");
  results.push(await state());
  await openTheme();
  await browser.keyboard.press("Backspace");
  await app.screenshot("fresh-plain-backspace");
  const plain = await state();
  expect({ protectedKeys: results, plain }).toEqual({
    protectedKeys: Array.from({ length: 6 }, () => ({ placeholder: "Search...", query: "" })),
    plain: { placeholder: "Search commands, projects, and threads...", query: "Change theme" },
  });
});
