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

test("Settings search shortcuts respect a focused archive context menu", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("demo");
  const thread = await t3.thread({ project, title: "go", model: "default", messages: ["go"] });
  await t3.open(thread);
  const context = async (inSettings: boolean) => {
    await browser.evaluate((settings) => {
      const root = settings ? document.querySelector('[role="dialog"]')! : document;
      const el = [...root.querySelectorAll('*')].find(el => el.textContent === 'go' && el.children.length === 0)!;
      const r = el.getBoundingClientRect();
      el.dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, cancelable: true, button: 2, clientX: r.x + r.width / 2, clientY: r.y + r.height / 2 }));
      return null;
    }, inSettings);
    await browser.locator('[data-context-menu="true"]').waitFor();
  };
  await screen.getByText("go", { exact: true }).first().waitFor();
  await context(false);
  await screen.getByRole("menuitem", "Archive thread", { exact: true }).tap();
  await t3.open("/settings/archived");
  await screen.getByRole("button", "Unarchive go", { exact: true }).waitFor();
  await context(true);
  await browser.keyboard.press("/");
  await app.screenshot("slash-with-context-menu");
  const slash = await browser.evaluate(() => Boolean(document.activeElement?.closest('[data-context-menu="true"]')));
  await screen.getByRole("heading", "demo", { exact: true }).tap();
  await context(true);
  await browser.keyboard.press("ArrowDown");
  await browser.evaluate(() => {
    window.addEventListener('keydown', event => {
      if (event.key.toLowerCase() === 'f' && (event.ctrlKey || event.metaKey)) document.documentElement.dataset.findPrevented = String(event.defaultPrevented);
    });
    return null;
  });
  await browser.keyboard.press("Control+f");
  await app.screenshot("ctrl-f-with-context-menu");
  const find = await browser.evaluate(() => ({ prevented: document.documentElement.dataset.findPrevented, menuFocused: Boolean(document.activeElement?.closest('[data-context-menu="true"]')) }));
  await screen.getByRole("heading", "demo", { exact: true }).tap();
  await context(true);
  await browser.keyboard.press("Escape");
  await browser.keyboard.press("/");
  await app.screenshot("slash-after-dismissal");
  const control = await browser.evaluate(() => document.activeElement?.getAttribute('role') === 'combobox');
  expect({ slash, find, control }).toEqual({ slash: true, find: { prevented: 'false', menuFocused: true }, control: true });
});
