import { writeFile } from "node:fs/promises";
import { expect } from "e2e";
import { T3_HOME } from "../e2e.config.ts";
import { test, WEB } from "./t3.ts";

test("Project jump shortcuts follow filtered rows", WEB, async ({ t3, app, screen, browser }) => {
  const server = await t3.project("server");
  await t3.project("zulu");
  for (const title of ["sample-a", "sample-b", "sample-c", "sample-d", "sample-e", "sample-f", "sample-g", "sample-h"]) {
    await t3.project(title);
  }
  await t3.project("lima");
  const thread = await t3.thread({ project: server, title: "Picker demonstration", messages: ["hello"] });
  await writeFile(`${T3_HOME}/userdata/keybindings.json`, JSON.stringify(
    Array.from({ length: 9 }, (_, i) => ({ key: `mod+${i + 1}`, command: `thread.jump.${i + 1}` })),
  ));
  await t3.open(thread);
  for (const [query, title] of [["li", "lima"], ["zulu", "zulu"]]) {
    await screen.getByText("first fixture turn complete", { exact: false }).waitFor();
    await browser.keyboard.press("Control+n");
    const input = screen.getByPlaceholder("Search...", { exact: true });
    await input.fill(query);
    await screen.getByRole("option", new RegExp(title)).waitFor();
    await app.screenshot(`${title}-filtered`);
    await expect.soft(screen.getByRole("option", new RegExp(title))).toContainText(/Ctrl\s*\+?\s*1$/);
    await browser.keyboard.press("Control+1");
    await expect.soft(screen.getByRole("dialog")).toBeHidden();
    await expect.soft(screen.getByRole("button", `New thread in ${title}`, { exact: true })).toBeVisible();
    await app.screenshot(`${title}-after-control-1`);
    await browser.keyboard.press("Escape");
    if (title === "lima") await t3.open(thread);
  }
});
