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

test("Settings sections remain reachable by Tab and expose named headings", WEB, async ({ t3, app, screen, browser }) => {
  await t3.project("Settings demo");
  await browser.emulateMedia({ colorScheme: "dark", reducedMotion: "reduce" });
  await t3.open();
  await browser.waitForURL(/\/$/);
  await app.open("/settings/worktrees");
  const observations: Array<{width: number; expected: string[]; tabbed: string[]; headings: number[]; buttons: number}> = [];
  for (const width of [1280, 600]) {
    await browser.setViewport({ width, height: 900 });
    if (width === 600) await screen.getByRole("button", "Search settings", { exact: true }).tap();
    await screen.getByRole("combobox", "Search settings", { exact: true }).fill("");
    const expected = await browser.evaluate(() => Array.from(document.querySelectorAll<HTMLElement>("[data-settings-section]")).map(e => e.textContent?.trim() ?? ""));
    const tabbed: string[] = [];
    for (let i = 0; i < expected.length; i++) {
      await browser.keyboard.press("Tab");
      tabbed.push(await browser.evaluate(() => document.activeElement?.closest("[data-settings-section]")?.textContent?.trim() ?? "<outside sections>"));
      if ([0, 1, 7, 14].includes(i)) await app.screenshot(`${width}-tab-${i + 1}`);
    }
    const headings = [];
    for (const name of ["Agents", "Code", "Connections"]) headings.push(await screen.getByRole("heading", name, { exact: true }).count());
    const buttons = await browser.locator("button[data-settings-section]:not([role=treeitem])").count();
    observations.push({width, expected, tabbed, headings, buttons});
    await browser.locator('[data-settings-section="/settings/worktrees"]').tap();
    for (const key of ["ArrowUp", "ArrowDown", "Home", "End"]) {
      await browser.keyboard.press(key);
      await app.screenshot(`${width}-${key}`);
    }
    if (width === 600) {
      await browser.keyboard.press("Escape");
      await app.screenshot("600-compact-rail");
    }
  }
  for (const observation of observations) {
    expect.soft(observation.tabbed).toEqual(observation.expected);
    expect.soft(observation.headings).toEqual([1, 1, 1]);
    expect.soft(observation.buttons).toBe(observation.expected.length);
  }
});
