import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("Configured Usage shortcuts win over selected composer formatting", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("Shortcut demo");
  await t3.thread({ project, title: "Shortcut evidence", messages: ["Hello"] });
  await t3.open();
  await screen.getByRole("button", "Shortcut evidence, Done, Shortcut demo").tap();
  const chatUrl = await browser.evaluate(() => location.pathname);
  await app.open("/settings/chat");
  const rich = screen.getByRole("switch", "Rich text composer");
  if (await rich.getAttribute("aria-checked") !== "true") await rich.tap();
  const outcomes: Array<{ chord: string; opened: boolean; plain: boolean; control: boolean }> = [];
  for (const key of ["e", "i"]) {
    await app.open("/settings/keybindings");
    await screen.getByRole("button", /^Edit shortcut for Usage: Open:/).tap();
    await screen.getByRole("textbox", "Keybinding for Usage: Open").press(`Control+${key}`);
    await screen.getByRole("button", "Save", { exact: true }).tap();
    await app.open(chatUrl);
    const editor = browser.locator('[data-composer-rich-text="true"][contenteditable="true"]');
    await editor.fill("hello");
    await editor.press("Control+a");
    await editor.press(`Control+${key}`);
    await screen.getByRole("heading", "Usage", { exact: true }).waitFor({ timeout: 2000 }).catch(() => {});
    await app.screenshot(`mod-${key}-composer`);
    const opened = await browser.evaluate(() => location.pathname === "/usage");
    if (opened) {
      await browser.keyboard.press("Escape");
      await screen.getByRole("heading", "Usage", { exact: true }).waitFor({ state: "hidden" });
      await editor.waitFor();
    }
    await app.screenshot(`mod-${key}-retained-text`);
    const plain = await browser.evaluate(() => {
      const editor = document.querySelector('[data-composer-rich-text="true"][contenteditable="true"]');
      return editor?.textContent === "hello" && !editor.querySelector("code, em, strong");
    });
    await app.open(chatUrl);
    await editor.waitFor();
    await browser.evaluate(() => { (document.activeElement as HTMLElement)?.blur(); });
    await browser.keyboard.press(`Control+${key}`);
    await screen.getByRole("heading", "Usage", { exact: true }).waitFor();
    await app.screenshot(`mod-${key}-outside-control`);
    const control = await browser.evaluate(() => location.pathname === "/usage");
    outcomes.push({ chord: key, opened, plain, control });
  }
  expect(outcomes).toEqual([
    { chord: "e", opened: true, plain: true, control: true },
    { chord: "i", opened: true, plain: true, control: true },
  ]);
});
