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

test("Escape dismisses the narrow panel before stopping the waiting turn", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("escape-demo", { "README.md": "Escape panel demonstration\n" });
  await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
    yield* client["server.refreshProviders"]({ instanceId: "devReplay", refreshModels: true });
    yield* client["server.upsertKeybinding"]({ key: "escape", command: "thread.stop" });
  }).pipe(Effect.scoped));
  const thread = await t3.thread({ project, title: "Escape panel demonstration", messages: ["Ask a question"], model: "question" });
  await browser.setViewport({ width: 900, height: 800 });
  await t3.open(thread);
  const question = browser.locator('[data-chat-composer-form="true"] [data-pending-user-input-toggle]');
  await question.waitFor();
  await screen.getByRole("button", "Toggle right panel", { exact: true }).tap();
  await screen.getByRole("button", "Files F", { exact: true }).tap();
  await screen.getByRole("treeitem", "README.md", { exact: true }).waitFor();
  await browser.evaluate(() => {
    const close = document.querySelector<HTMLButtonElement>('button[aria-label="Close Files"]');
    if (!close) throw new Error("Close Files is missing");
    close.focus();
    return null;
  });
  await app.screenshot("before-first-escape");
  await browser.keyboard.press("Escape");
  await Promise.race([
    question.waitFor({ state: "hidden" }),
    screen.getByRole("dialog", "Workspace panel", { exact: true }).waitFor({ state: "hidden" }),
  ]);
  await app.screenshot("after-first-escape");
  await expect(screen.getByRole("dialog", "Workspace panel", { exact: true })).not.toBeVisible();
  await expect(question).toBeVisible();
  await browser.keyboard.press("Escape");
  await question.waitFor({ state: "hidden" });
  await screen.getByText("Stopped by user", { exact: false }).waitFor();
  await app.screenshot("after-second-escape");
  await expect(screen.getByText("Stopped by user", { exact: false })).toBeVisible();
});
