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

test("Closing the empty panel ignores F during its exit", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("panel-shortcuts", { "example.txt": "Synthetic evidence fixture\n" });
  const draft = () => runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl);
    const snapshot = yield* client["orchestration.subscribeShell"]({}).pipe(Stream.runHead);
    if (snapshot._tag !== "Some" || snapshot.value.kind !== "snapshot") throw new Error("Missing shell");
    const item = snapshot.value.snapshot.projects.find((p) => p.workspaceRoot === project);
    if (!item) throw new Error("Missing project");
    const threadId = ThreadId.make(crypto.randomUUID());
    yield* client["orchestration.dispatchCommand"]({
      type: "thread.create", createdBy: "user", creationSource: "web",
      commandId: CommandId.make(crypto.randomUUID()), threadId, projectId: item.id,
      title: "Panel shortcut evidence", modelSelection: { instanceId: "devReplay", model: "default" },
      runtimeMode: "full-access", interactionMode: "default", branch: null, worktreePath: null,
    });
    return { threadId };
  }).pipe(Effect.scoped));
  await browser.setViewport({ width: 1440, height: 900 });
  await browser.emulateMedia({ colorScheme: "dark", reducedMotion: "no-preference" });
  await t3.open("/settings/appearance");
  await screen.getByRole("button", "Advanced", { exact: true }).first().tap();
  await screen.getByRole("slider", "Panel animation duration", { exact: true }).press("End");
  await screen.getByText("400 ms", { exact: true }).waitFor();
  const results: Array<{ width: number; open: boolean }> = [];
  for (const width of [1440, 900]) {
    await browser.setViewport({ width, height: 900 });
    const thread = await draft();
    await t3.open(thread);
    await screen.getByText("Send a message to start the conversation.", { exact: true }).waitFor();
    await browser.mouse.move(400, 300);
    const focusToggle = () => browser.evaluate(() => {
      const buttons = [...document.querySelectorAll<HTMLButtonElement>('button[aria-label="Toggle right panel"]')]
        .filter((button) => button.getClientRects().length > 0);
      const button = buttons.at(-1);
      if (!button) throw new Error("Missing right panel toggle");
      button.focus();
    });
    await focusToggle();
    await browser.keyboard.press("Enter");
    await browser.locator('[data-surface-launcher-keys="BTFDMS"]').waitFor();
    await browser.evaluate(() => new Promise<void>((resolve) => setTimeout(resolve, 600)));
    await app.screenshot(`${width}-empty-panel-open`);
    await focusToggle();
    await browser.keyboard.press("Enter");
    await browser.evaluate(() => new Promise<void>((resolve) => setTimeout(resolve, 60)));
    await browser.keyboard.press("f");
    await browser.evaluate(() => new Promise<void>((resolve) => setTimeout(resolve, 1000)));
    results.push({ width, open: await browser.evaluate(() =>
      [...document.querySelectorAll('button[aria-label="Toggle right panel"]')]
        .some((button) => button.getAttribute("aria-pressed") === "true")) });
    await browser.evaluate(() => (document.activeElement as HTMLElement)?.blur());
    await browser.mouse.move(400, 300);
    await browser.evaluate(() => new Promise<void>((resolve) => setTimeout(resolve, 600)));
    await app.screenshot(`${width}-after-F-during-exit`);
  }
  expect(results).toEqual([{ width: 1440, open: false }, { width: 900, open: false }]);
});
