import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as Stream from "effect/Stream";
import { T3_HOME } from "../e2e.config.ts";
import { test, WEB, rpcClient, runPromise } from "./t3.ts";

test("Escape dismisses the keyboard-focused minimap preview and preserves focus", WEB, async ({ t3, app, browser }) => {
  const project = await t3.project("Minimap demo");
  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, Effect.timeout("30 seconds")));
  const thread = await t3.thread({ project, title: "Minimap demo thread", messages: ["First question: explain the change", "Second question: add tests too", "Third question: summarize the change"] });
  await t3.open(thread);
  const jump = browser.locator('[data-testid="timeline-minimap"] button[aria-label^="Jump to message:"]');
  await jump.waitFor();
  await browser.keyboard.press("Tab");
  await jump.focus();
  await browser.keyboard.press("End");
  await browser.keyboard.press("ArrowUp");
  const preview = browser.locator('[data-testid="timeline-minimap"] .dropdown-glass');
  await preview.waitFor();
  await app.screenshot("keyboard-preview-before-escape");
  await browser.keyboard.press("Escape");
  await app.screenshot("keyboard-preview-after-escape");
  await expect(preview).toHaveCount(0);
  await expect(browser.locator('[data-testid="timeline-minimap"] button:focus-visible')).toHaveCount(1);
  await browser.keyboard.press("ArrowDown");
  await preview.waitFor();
  await app.screenshot("navigation-reopens-preview");
});
