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

test("Cached Labels and Assignee keyboard openings focus searchable inputs", WEB, async ({t3, app, screen, browser}) => {
  const project = await t3.project("Keyboard filters");
  await runPromise(run("git", ["remote", "add", "origin", "https://github.com/pingdotgg/t3code.git"], {cwd: project}));
  await t3.open("/issues");
  const filters = screen.getByRole("button", "Filters", {exact:true});
  await filters.waitFor({timeout: 120000});
  const key = (value: string) => browser.keyboard.press(value);
  const open = async (name: string, opening: string) => {
    await browser.evaluate(() => (Array.from(document.querySelectorAll('button')).find(el => el.textContent?.trim().startsWith('Filters')) as HTMLElement)?.focus());
    await key("Enter");
    await screen.getByRole("menuitem", /^State/).waitFor();
    await key("Home");
    for (let i=0; i<(name === "Labels" ? 3 : 4); i++) await key("ArrowDown");
    await key(opening);
  };
  // Load both real GitHub candidate lists before testing the cached opening path.
  await open("Labels", "ArrowRight");
  await screen.getByRole("menuitemcheckbox", "documentation", {exact:true}).waitFor({timeout:120000});
  await key("Escape"); await key("Escape");
  await open("Assignee", "Enter");
  await screen.getByRole("menuitemradio", /juliusmarminge/).waitFor({timeout:120000});
  await key("Escape"); await key("Escape");
  const results = [];
  for (const name of ["Labels", "Assignee"]) {
    for (const opening of ["ArrowRight", "Enter"]) {
      await open(name, opening);
      const search = browser.locator(name === "Labels" ? 'input[aria-label="Search labels"]' : 'input[aria-label="Search people"]');
      await search.waitFor();
      const focused = await browser.evaluate(() => document.activeElement?.getAttribute("aria-label"));
      for (const letter of (name === "Labels" ? "docu" : "jul")) await key(letter);
      await app.screenshot(`${name.toLowerCase()}-${opening.toLowerCase()}-typed`);
      results.push({name, opening, focused, value:await search.inputValue()});
      await key("ArrowDown");
      if (name === "Assignee") await key("ArrowDown");
      await key("Enter");
      await key("Escape"); await key("Escape");
    }
  }
  expect(results).toEqual([
    {name:"Labels", opening:"ArrowRight", focused:"Search labels", value:"docu"},
    {name:"Labels", opening:"Enter", focused:"Search labels", value:"docu"},
    {name:"Assignee", opening:"ArrowRight", focused:"Search people", value:"jul"},
    {name:"Assignee", opening:"Enter", focused:"Search people", value:"jul"},
  ]);
});
