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

test("Context menus block right-panel launcher keys until dismissed", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("demo");
  const go = await t3.thread({ project, title: "go", messages: ["Hello"] });
  await t3.thread({ project, title: "second", messages: ["Hello"] });
  await t3.open(go);
  await screen.getByRole("button", "Toggle right panel").tap();
  await screen.getByText("Open a surface", { exact: true }).waitFor();
  const context = async (selector: string) => {
    await browser.evaluate((selector) => {
      const element = document.querySelector(selector)!;
      const rect = element.getBoundingClientRect();
      element.dispatchEvent(new MouseEvent("contextmenu", { bubbles: true, cancelable: true, button: 2, clientX: rect.x + rect.width / 2, clientY: rect.y + rect.height / 2 }));
      return null;
    }, selector);
    await browser.locator('[data-context-menu="true"]').waitFor();
  };
  const row = await browser.evaluate(() => {
    const title = [...document.querySelectorAll('*')].find(e => e.textContent === 'second' && e.children.length === 0)!;
    title.setAttribute('data-proof-second', 'true');
    return '[data-proof-second="true"]';
  });
  await context(row);
  await app.screenshot("thread-menu-before-F");
  await browser.keyboard.press("f");
  if (await browser.evaluate(() => !document.querySelector("[data-surface-launcher-keys]"))) {
    await browser.locator('input[placeholder="Search files"]').waitFor();
  }
  await app.screenshot("thread-menu-after-F");
  const letterBlocked = await browser.evaluate(() => !!document.querySelector('[data-context-menu="true"]') && !!document.querySelector('[data-surface-launcher-keys]'));
  await browser.keyboard.press("Escape");
  const empty = await browser.evaluate(() => !!document.querySelector('[data-surface-launcher-keys]'));
  if (empty) {
    await browser.locator('[data-surface-launcher-keys]').click();
    await browser.keyboard.press("f");
  }
  await browser.locator('[data-active-tab="true"]').waitFor();
  await context('[data-active-tab="true"]');
  await app.screenshot("tab-menu-before-Mod-T");
  await browser.keyboard.press("ControlOrMeta+t");
  await app.screenshot("tab-menu-after-Mod-T");
  const modBlocked = await browser.evaluate(() => !!document.querySelector('[data-context-menu="true"]') && !document.querySelector('[data-slot="menu-popup"]'));
  await browser.keyboard.press("Escape");
  await browser.locator('[data-active-tab="true"]').click();
  await browser.keyboard.press("ControlOrMeta+t");
  await browser.locator('[data-slot="menu-popup"]').waitFor();
  await app.screenshot("add-surface-after-dismissal");
  await expect(browser.locator('[data-slot="menu-popup"]')).toBeVisible();
  await expect(letterBlocked).toBe(true);
  await expect(modBlocked).toBe(true);
});
