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

test("Context menu keeps typing and paste out of the composer", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("demo");
  const thread = await t3.thread({ project, title: "New thread", messages: ["Hello"] });
  await t3.open(thread);
  const composer = screen.getByRole("textbox");
  await composer.waitFor();
  const openMenu = async () => {
    await browser.evaluate((id) => {
      const row = document.querySelector(`[data-sidebar-row$="${id}"]`)!;
      const box = row.getBoundingClientRect();
      row.dispatchEvent(new MouseEvent("contextmenu", { bubbles: true, cancelable: true, button: 2, clientX: box.x + 100, clientY: box.y + box.height / 2 }));
      return null;
    }, thread.threadId);
    await browser.locator('[data-context-menu="true"]').waitFor();
  };
  const state = () => browser.evaluate(() => ({
    composer: document.querySelector('[data-testid="composer-editor"]')?.textContent ?? "",
    menuOpen: document.querySelector('[data-context-menu="true"]') !== null,
  }));
  await openMenu();
  await app.screenshot("menu-before-input");
  await browser.keyboard.press("a");
  await app.screenshot("menu-after-printable-key");
  const typed = await state();
  await browser.keyboard.press("Escape");
  await composer.press("ControlOrMeta+a");
  await composer.press("Backspace");
  await browser.evaluate(async () => { await navigator.clipboard.writeText("pasted-from-clipboard"); return null; });
  await openMenu();
  await browser.keyboard.press("ControlOrMeta+V");
  await app.screenshot("menu-after-paste");
  const pasted = await state();
  await browser.keyboard.press("Escape");
  await composer.press("ControlOrMeta+a");
  await composer.press("Backspace");
  await browser.evaluate(() => { (document.activeElement as HTMLElement)?.blur(); return null; });
  await browser.keyboard.press("b");
  await app.screenshot("normal-type-to-focus-after-dismissal");
  const resumed = await state();
  expect(typed).toEqual({ composer: "", menuOpen: true });
  expect(pasted).toEqual({ composer: "", menuOpen: true });
  expect(resumed).toEqual({ composer: "b", menuOpen: false });
});
