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

test("Background activity dialog returns focus to the available control", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("demo");
  const thread = await t3.thread({ project, title: "Focus demonstration", messages: ["Hello"] });
  await t3.open(thread);
  await t3.open("/settings/maintenance");
  await screen.getByRole("button", /^Environment scope/).click();
  await browser.locator('[role="menuitemradio"]').last().click();
  await browser.locator('[role="menu"]').waitFor({ state: "hidden" });
  const profile = screen.getByRole("combobox", "Background activity profile");
  const dialog = screen.getByRole("dialog", "Background Activity", { exact: true });
  const results: string[] = [];
  const openAdvanced = async () => {
    await profile.focus();
    await profile.press("Space");
    await screen.getByRole("option", "Advanced", { exact: true }).waitFor();
    await browser.keyboard.press("End");
    await browser.keyboard.press("Enter");
    await dialog.waitFor();
  };
  const capture = async (label: string) => {
    await dialog.waitFor({ state: "hidden" });
    await app.screenshot(label);
    const focused = await browser.evaluate(() => document.activeElement?.getAttribute("aria-label") ?? document.activeElement?.tagName ?? "none");
    results.push(focused);
  };
  await openAdvanced();
  await browser.keyboard.press("Escape");
  await capture("escape-from-advanced");
  await openAdvanced();
  await screen.getByRole("button", "Done", { exact: true }).focus();
  await browser.keyboard.press("Enter");
  await capture("done-from-advanced");
  await openAdvanced();
  await screen.getByRole("switch", "Pause on battery", { exact: true }).focus();
  await browser.keyboard.press(" ");
  await browser.keyboard.press("Escape");
  await capture("custom-settings-create-configure-button");
  const gear = screen.getByRole("button", "Configure advanced background activity", { exact: true });
  await gear.focus();
  await browser.keyboard.press("Enter");
  await dialog.waitFor();
  await browser.keyboard.press("Escape");
  await capture("existing-configure-button-control");
  await gear.focus();
  await browser.keyboard.press("Enter");
  await dialog.waitFor();
  await screen.getByRole("button", "Reset all", { exact: true }).focus();
  await browser.keyboard.press("Enter");
  await browser.keyboard.press("Escape");
  await capture("reset-all-removes-configure-button");
  await expect(results).toEqual([
    "Background activity profile", "Background activity profile",
    "Configure advanced background activity", "Configure advanced background activity",
    "Background activity profile",
  ]);
});
