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

test("Pending move keeps focus in its dialog and returns it to Thread actions", WEB, async ({t3, app, browser, screen}) => {
  const project = await t3.project("Source project");
  await t3.project("Destination project");
  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));
  const thread = await t3.thread({project, title: "Keyboard focus example", messages: ["Hello"], model: "multi-turn"});
  await browser.addInitScript(() => {
    // Delay real network frames, preserving their content and order, to expose remote-link recovery.
    const send = WebSocket.prototype.send;
    WebSocket.prototype.send = function(data) { setTimeout(() => send.call(this, data), 300); };
    const listen = WebSocket.prototype.addEventListener;
    WebSocket.prototype.addEventListener = function(type, listener, options) {
      if (type !== "message" || typeof listener !== "function") return listen.call(this, type, listener, options);
      return listen.call(this, type, (event) => { setTimeout(() => listener.call(this, event), 300); }, options);
    } as typeof WebSocket.prototype.addEventListener;
    document.addEventListener("DOMContentLoaded", () => {
      const style = document.createElement("style");
      style.textContent = '[role="dialog"] code, [role="dialog"] .font-mono {font-size:0!important} [role="dialog"] code::after, [role="dialog"] .font-mono::after {content:"Synthetic workspace";font-size:12px}';
      document.head.append(style);
      const indicator = document.createElement("div");
      indicator.setAttribute("aria-hidden", "true");
      indicator.style.cssText = "position:fixed;top:4px;right:4px;z-index:2147483647;background:#13243a;color:white;padding:8px 12px;border-radius:6px;font:13px monospace;pointer-events:none";
      document.body.append(indicator);
      const showFocus = () => {
        const active = document.activeElement;
        const modal = active?.closest('[role="dialog"]');
        const name = active?.getAttribute("aria-label") ?? (modal ? "Move thread to project" : active?.tagName);
        indicator.textContent = `Focus: ${name}`;
      };
      document.addEventListener("focusin", showFocus);
      document.addEventListener("focusout", () => requestAnimationFrame(showFocus));
      showFocus();
    });
  });
  await t3.open(thread);
  await browser.locator('button[aria-label^="Thread actions for"]').waitFor();
  await browser.evaluate(() => { (document.querySelector('button[aria-label^="Thread actions for"]') as HTMLElement).focus(); return null; });
  await browser.keyboard.press("Enter");
  await screen.getByRole("menuitem", "Move to project…").waitFor();
  for (let i=0; i<20; i++) {
    if (await browser.evaluate(() => document.activeElement?.textContent?.includes("Move to project") ?? false)) break;
    await browser.keyboard.press("ArrowDown");
  }
  await browser.keyboard.press("Enter");
  const dialog = screen.getByRole("dialog", "Move thread to project");
  await dialog.waitFor();
  await browser.keyboard.press("Space");
  await browser.keyboard.press("Tab");
  await browser.keyboard.press("Tab");
  await browser.keyboard.press("Enter");
  await screen.getByRole("button", "Saving…").waitFor();
  // Observe the recovery frame while the genuine move RPC is still pending.
  const pending = await browser.evaluate(async () => {
    await new Promise(resolve => setTimeout(resolve, 160));
    const active = document.activeElement;
    return { inside: !!active?.closest('[role="dialog"]'), open: !!document.querySelector('[role="dialog"]'), active: active?.getAttribute("aria-label") ?? active?.tagName };
  });
  await app.screenshot("pending-move-focus");
  await dialog.waitFor({state:"hidden"});
  await screen.getByText("Thread workspace updated", {exact:true}).waitFor({state:"hidden"});
  await screen.getByText("Syncing messages…", {exact:true}).waitFor({state:"hidden"});
  await app.screenshot("closed-move-focus");
  const restored = await browser.evaluate(() => document.activeElement?.getAttribute("aria-label") ?.startsWith("Thread actions for") === true);
  expect(pending.open).toBe(true);
  expect(pending.inside).toBe(true);
  expect(restored).toBe(true);
});
