/// <reference lib="dom" />
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { T3_HOME } from "../e2e.config.ts";
import { rpcClient, runPromise, test, WEB } from "./t3.ts";

test("Enter and Space activate Cancel despite matching app shortcuts", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("demo");
  const thread = await t3.thread({ project, title: "New thread", messages: ["Start"] });
  await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl);
    yield* client["server.upsertKeybinding"]({ key: "enter", command: "commandPalette.toggle" });
    yield* client["server.upsertKeybinding"]({ key: "space", command: "commandPalette.toggle" });
  }).pipe(Effect.scoped));
  await t3.open(thread);
  await browser.locator("[data-thread-item]").first().waitFor();
  const results = [];
  for (const key of ["Enter", "Space"]) {
    await browser.evaluate(() => {
      const row = document.querySelector('[data-sidebar-row]');
      if (!row) throw new Error("Thread row missing");
      row.dispatchEvent(new MouseEvent("contextmenu", { bubbles: true, cancelable: true, button: 2 }));
      return null;
    });
    await screen.getByRole("menuitem", "Delete", { exact: true }).tap();
    const dialog = screen.getByRole("alertdialog");
    const cancel = dialog.getByRole("button", "Cancel", { exact: true });
    await cancel.waitFor();
    await cancel.focus();
    await browser.keyboard.press(key);
    await browser.evaluate(async () => {
      await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
      await Promise.allSettled(document.getAnimations().map((animation) => animation.finished));
      return null;
    });
    await app.screenshot(`after-${key.toLowerCase()}-on-cancel`);
    results.push(await browser.evaluate(() => ({
      dialogClosed: !document.querySelector('[role="alertdialog"]'),
      paletteClosed: !document.querySelector('[cmdk-root]'),
    })));
    // Reset with a pointer so both native keyboard paths are captured even on the broken base.
    if (!results.at(-1)!.dialogClosed) await cancel.tap();
  }
  expect(results).toEqual([
    { dialogClosed: true, paletteClosed: true },
    { dialogClosed: true, paletteClosed: true },
  ]);
});
