/// <reference lib="dom" />
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as Stream from "effect/Stream";
import { T3_HOME } from "../e2e.config.ts";
import { run } from "./shell.ts";
import { rpcClient, runPromise, test, WEB } from "./t3.ts";

test("Closing the issue thread picker returns keyboard focus", WEB, async ({ t3, app, browser, screen }) => {
  const workspaceRoot = await t3.project("focus-proof");
  await runPromise(run("git", ["remote", "add", "origin", "https://github.com/pingdotgg/t3code.git"], { cwd: workspaceRoot }));
  await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl);
    yield* client.subscribeServerConfig({}).pipe(
      Stream.filter((event) => {
        const providers = event.type === "snapshot" ? event.config.providers : event.type === "providerStatuses" ? event.payload.providers : [];
        return providers.some((provider) => provider.instanceId === "devReplay" && provider.models.some((model) => model.slug === "multi-turn"));
      }),
      Stream.runHead,
    );
  }).pipe(Effect.scoped));
  await t3.thread({ project: workspaceRoot, title: "go", messages: ["Start"] });
  const projectId = await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl);
    const item = yield* client["orchestration.subscribeShell"]({}).pipe(Stream.runHead);
    if (item._tag !== "Some" || item.value.kind !== "snapshot") throw new Error("No snapshot");
    const project = item.value.snapshot.projects.find((entry) => entry.workspaceRoot === workspaceRoot);
    if (!project) throw new Error("No project");
    return project.id;
  }).pipe(Effect.scoped));
  await t3.open(`/issues?selectedProjectId=${projectId}&tracker=github&scope=pingdotgg/t3code&key=47339`);
  const trigger = screen.getByRole("button", "Link to thread", { exact: true });
  await trigger.waitFor({ timeout: 60000 });
  const focused: boolean[] = [];
  for (const close of ["Escape", "Enter"]) {
    await browser.locator('button[aria-label="Link to thread"]').focus();
    await browser.keyboard.press("Shift+Tab");
    await browser.keyboard.press("Tab");
    await browser.keyboard.press("Enter");
    const search = screen.getByRole("combobox", "Search threads or projects...");
    await search.waitFor();
    await browser.keyboard.press(close);
    await screen.getByRole("dialog", "Link issue to a thread").waitFor({ state: "hidden" });
    await app.screenshot(`after-${close.toLowerCase()}`);
    focused.push(await browser.evaluate(() => document.activeElement?.getAttribute("aria-label") === "Link to thread"));
  }
  expect(focused).toEqual([true, true]);
});
