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

test("Settings and Usage restore keyboard focus without a mouse focus ring", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("Focus demo");
  const thread = await t3.thread({ project, title: "Keyboard focus", messages: ["Start"] });
  await browser.emulateMedia({ colorScheme: "dark" });
  await t3.open(thread);
  const composer = screen.getByRole("textbox");
  await composer.fill("Continue typing here after closing the modal");
  await browser.evaluate(() => {
    const output = document.createElement("output");
    output.id = "focus-proof";
    output.style.cssText = "position:fixed;top:3px;left:340px;right:80px;z-index:2147483647;background:#172033;color:#fff;border:2px solid #67e8f9;padding:8px;font:14px monospace;pointer-events:none;white-space:pre-wrap";
    output.setAttribute("aria-hidden", "true");
    document.body.append(output);
  });
  const capture = async (label: string, expected: string) => {
    await browser.evaluate(({ label, expected }) => {
      const active = document.activeElement as HTMLElement | null;
      const name = active?.getAttribute("aria-label") || active?.getAttribute("data-workspace-area") || active?.textContent?.trim().slice(0, 50) || "";
      document.getElementById("focus-proof")!.textContent = `${label}\nExpected: ${expected}\nActual focus: ${active?.tagName}${active?.isContentEditable ? " (composer)" : ""}${active?.tagName === "BODY" ? "" : ` ${name}`} | focus-visible: ${active?.matches(":focus-visible")}\nComposer inside inert content: ${Boolean(document.querySelector('[contenteditable="true"]')?.closest("[inert]"))}`;
    }, { label, expected });
    await app.screenshot(label);
  };
  const close = async () => {
    await browser.keyboard.press("Escape");
    await browser.waitForURL(new RegExp(thread.threadId + "$"));
    await browser.locator("[data-app-modal]").waitFor({ state: "detached" });
  };
  for (const name of ["Usage", "Settings"]) {
    const opener = screen.getByRole("button", name, { exact: true });
    await opener.focus();
    await browser.keyboard.press("Enter");
    await screen.getByRole("dialog", name).waitFor({ state: "visible" });
    await capture(`sidebar-${name}-open`, `${name} dialog`);
    await close();
    await expect.soft(opener).toBeFocused({ timeout: 1500 });
    await capture(`sidebar-${name}-Escape`, `${name} sidebar button`);
  }
  await composer.focus();
  await browser.keyboard.press("Control+u");
  await screen.getByRole("dialog", "Usage").waitFor({ state: "visible" });
  await capture("composer-Usage-open", "Usage dialog; composer behind inert content");
  await close();
  await expect.soft(composer).toBeFocused({ timeout: 1500 });
  await capture("composer-Usage-Escape", "composer");
  for (const name of ["Settings", "Usage"]) {
    await composer.focus();
    await browser.keyboard.press("Control+k");
    const search = screen.getByRole("combobox", "Search commands, projects, and threads...");
    await search.fill(`Open ${name.toLowerCase()}`);
    await capture(`palette-${name}-search`, "command palette search; original opener = composer");
    await screen.getByRole("option", `Open ${name.toLowerCase()}`, { exact: false }).tap();
    await screen.getByRole("dialog", name).waitFor({ state: "visible" });
    await capture(`palette-${name}-open`, `${name} dialog`);
    await close();
    await expect.soft(composer).toBeFocused({ timeout: 1500 });
    await capture(`palette-${name}-Escape`, "composer (before command palette opened)");
  }
  for (const name of ["Settings", "Usage"]) {
    await screen.getByRole("button", name, { exact: true }).tap();
    const modal = screen.getByRole("dialog", name);
    await modal.waitFor({ state: "visible" });
    await modal.getByRole("button", "Close", { exact: true }).tap();
    await browser.waitForURL(new RegExp(thread.threadId + "$"));
    await browser.locator("[data-app-modal]").waitFor({ state: "detached" });
    await capture(`mouse-${name}-Close`, "BODY; no focus ring");
    expect.soft(await browser.evaluate(() => document.activeElement === document.body)).toBe(true);
  }
});
