/// <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 { makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";

test("Escape dismisses a focused completion toast without reaching lower layers", WEB, async ({t3, app, browser, screen}) => {
  const project = await t3.project("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 === "showcase"));
      }), Stream.runHead);
  }).pipe(Effect.scoped, Effect.timeout("30 seconds")));
  const thread = await t3.thread({project, title: "Toast Escape demo", messages: ["Give me a tour"], model: "showcase"});
  await t3.open("/settings/general");
  await screen.getByRole("switch", "In-app notifications").check();
  await t3.open(thread);
  await screen.getByRole("button", "Pull requests", {exact: true}).click();
  const search = screen.getByPlaceholder("Search pull requests, or label:bug");
  await search.fill("toast-escape-demo");
  const state = makeState(T3_HOME);
  const toast = browser.locator('[data-slot="toast-description"]:has-text("Toast Escape demo")');
  await runPromise(state.cli(["thread", "send", thread.threadId, "Show me more", "--wait", "--json"]));
  await toast.waitFor();
  await toast.click();
  await browser.locator('[data-slot="toast-root"]:focus, [role="dialog"]:focus').waitFor();
  await app.screenshot("focused-toast-over-pull-requests");
  await browser.keyboard.press("Escape");
  await toast.waitFor({state: "hidden"});
  await app.screenshot("after-one-escape-page");
  const pageKept = await search.isVisible();
  const queryKept = await browser.evaluate(() => new URL(location.href).searchParams.get("q"));
  // Continue to capture the palette case even when the base leaks the first Escape.
  if (!pageKept) {
    await screen.getByRole("button", "Pull requests", {exact: true}).click();
    await search.fill("toast-escape-demo");
  }
  await browser.keyboard.press("ControlOrMeta+k");
  const palette = screen.getByPlaceholder("Search commands, projects, and threads...");
  await palette.waitFor();
  await runPromise(state.cli(["thread", "send", thread.threadId, "One more tour", "--wait", "--json"]));
  await toast.waitFor();
  await toast.click();
  await app.screenshot("focused-toast-over-palette");
  await browser.keyboard.press("Escape");
  await toast.waitFor({state: "hidden"});
  await app.screenshot("after-one-escape-palette");
  const paletteKept = await palette.isVisible();
  if (!paletteKept) await browser.keyboard.press("ControlOrMeta+k");
  await palette.waitFor();
  await browser.keyboard.press("Escape");
  await palette.waitFor({state: "hidden"});
  await app.screenshot("control-escape-without-toast");
  expect({pageKept, queryKept, paletteKept}).toEqual({pageKept: true, queryKept: "toast-escape-demo", paletteKept: true});
});
