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

test("Closing Usage restores focus after its popup opener disappears", WEB, async ({t3, app, browser, screen}) => {
  const project = await t3.project("demo", {"t3.json": JSON.stringify({defaultThreadEnvMode:"local"})});
  const thread = await t3.thread({project, title:"Focus restoration", messages:["Hello"], model:"default"});
  await t3.open(thread);
  await browser.locator('[data-slot="combobox-trigger"][aria-label^="Branch:"]:visible').first().click();
  await browser.locator('input[placeholder="Search refs..."]:visible').click();
  const results: boolean[] = [];
  for (const close of ["ControlOrMeta+u", "Escape"]) {
    if (close === "Escape") {
      await browser.locator('[data-slot="combobox-trigger"][aria-label^="Branch:"]:visible').first().click();
      await browser.locator('input[placeholder="Search refs..."]:visible').click();
    }
    await browser.keyboard.press("ControlOrMeta+u");
    const usage = screen.getByRole("dialog", "Usage");
    await usage.waitFor();
    await browser.keyboard.press(close);
    await usage.waitFor({state:"hidden"});
    results.push(await browser.evaluate(() => !!document.activeElement?.closest('[data-workspace-area="composer"]')));
    await app.screenshot(close === "Escape" ? "branch-after-escape" : "branch-after-shortcut");
    await browser.keyboard.press("Tab");
    await app.screenshot(close === "Escape" ? "branch-tab-after-escape" : "branch-tab-after-shortcut");
  }
  await t3.open("/issues");
  await browser.locator('button[aria-label^="Sort issues:"]').click();
  await browser.keyboard.press("ArrowDown");
  await browser.locator('[role="menuitemradio"]:focus').waitFor();
  await browser.keyboard.press("ControlOrMeta+u");
  const usage = screen.getByRole("dialog", "Usage");
  await usage.waitFor();
  await browser.keyboard.press("ControlOrMeta+u");
  await usage.waitFor({state:"hidden"});
  results.push(await browser.evaluate(() => !!document.querySelector('main:focus, main :focus')));
  await app.screenshot("issues-after-shortcut");
  await browser.keyboard.press("Tab");
  await app.screenshot("issues-tab-after-shortcut");
  expect(results).toEqual([true, true, true]);
});
