/// <reference lib="dom" />
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("Wheel over subagent lists continues into the details panel", WEB, async ({ t3, app, screen, browser }) => {
  await browser.addInitScript(() => {
    const send = WebSocket.prototype.send;
    let next = 900000;
    Object.assign(window, { scenarioRpc: (tag: string, payload: unknown) => new Promise((resolve, reject) => {
      const socket = (window as any).scenarioSocket as WebSocket;
      const id = String(next++);
      const listener = (event: MessageEvent) => {
        for (const msg of [JSON.parse(event.data)].flat()) {
          if (msg._tag === "Exit" && String(msg.requestId) === id) {
            socket.removeEventListener("message", listener);
            if (msg.exit._tag === "Success") resolve(msg.exit.value);
            else reject(new Error(JSON.stringify(msg.exit)));
          }
        }
      };
      socket.addEventListener("message", listener);
      send.call(socket, JSON.stringify({ _tag: "Request", id, tag, payload, headers: [], traceId: "00000000000000000000000000000001", spanId: "0000000000000001", sampled: false }));
    }) });
    WebSocket.prototype.send = function(data) {
      (window as any).scenarioSocket = this;
      return send.call(this, data);
    };
  });
  const project = await t3.project("Scroll demonstration");
  const parent = await t3.thread({ project, title: "Parent with 18 subagents", messages: ["Review the workspace"], model: "question" });
  await t3.open(parent);
  await screen.getByRole("button", "Toggle thread details panel").tap();
  await browser.evaluate(async (threadId) => {
    const rpc = (window as any).scenarioRpc;
    const result = await rpc("orchestration.getThreadProjection", { threadId });
    (window as any).seedProjection = result;
    const projection = result.projection ?? result;
    const run = projection.runs.find((r: any) => r.status === "running" || r.status === "waiting" || r.status === "waiting_for_input") ?? projection.runs.at(-1);
    for (let i = 1; i <= 18; i++) {
      const commandId = crypto.randomUUID();
      // The web dispatch path reads the empty child before committing its lineage.
      await rpc("orchestration.dispatchCommand", { type: "thread.create", commandId: crypto.randomUUID(), createdBy: "user", creationSource: "web", threadId: `thread:delegated-task:${commandId}`, projectId: projection.thread.projectId, title: `Review agent ${String(i).padStart(2, "0")}`, modelSelection: { instanceId: "devReplay", model: "multi-turn" }, runtimeMode: "full-access", interactionMode: "default", branch: "main", worktreePath: null });
      await rpc("orchestration.dispatchCommand", { type: "delegated_task.request", createdBy: "agent", creationSource: "mcp", commandId, parentThreadId: threadId, parentRunId: run.id, parentNodeId: run.rootNodeId, task: "Summarize the workspace", title: `Review agent ${String(i).padStart(2, "0")}`, modelSelection: { instanceId: "devReplay", model: "multi-turn" }, runtimeMode: "full-access", interactionMode: "default" });
    }
    for (let attempt = 0; attempt < 120; attempt++) {
      const state = await rpc("orchestration.getThreadProjection", { threadId });
      const p = state.projection ?? state;
      if (p.subagents.length === 18 && p.subagents.every((a: any) => ["completed", "failed", "cancelled"].includes(a.status))) return;
      await new Promise(r => setTimeout(r, 500));
    }
    throw new Error("Replay children did not settle");
  }, parent.threadId);
  await browser.setViewport({ width: 1280, height: 460 });

  if (!await browser.evaluate(() => !!document.querySelector("[data-thread-details-card]"))) await screen.getByRole("button", "Toggle thread details panel").tap();
  await screen.getByRole("button", /Previous agents/).tap();
  const setup = () => browser.evaluate(() => {
    const list = document.querySelector<HTMLElement>('ul[aria-label="Related threads"]')!;
    const panel = list.closest('[data-thread-details-card]')!.querySelector<HTMLElement>('[data-slot="scroll-area-viewport"]')!;
    panel.scrollTop = 0;
    const rect = list.getBoundingClientRect();
    const pr = panel.getBoundingClientRect();
    return { x: rect.x + 70, y: Math.min(rect.y + 35, pr.bottom - 20), max: panel.scrollHeight - panel.clientHeight, listMax: list.scrollHeight - list.clientHeight };
  });
  const read = () => browser.evaluate(() => {
    const list = document.querySelector<HTMLElement>('ul[aria-label="Related threads"]')!;
    const panel = list.closest('[data-thread-details-card]')!.querySelector<HTMLElement>('[data-slot="scroll-area-viewport"]')!;
    return panel.scrollTop;
  });
  let point = await setup();
  await app.screenshot("short-list-before-wheel");
  await browser.mouse.move(point.x, point.y);
  for (let i = 0; i < 3; i++) await browser.mouse.wheel(0, 120);
  await new Promise(r => setTimeout(r, 700));
  const shortScroll = await read();
  await app.screenshot("short-list-after-wheel");
  await screen.getByRole("button", "Show 12 more").tap();
  await browser.evaluate(() => { const list = document.querySelector<HTMLElement>('ul[aria-label="Related threads"]')!; list.scrollTop = list.scrollHeight; });
  point = await setup();
  await app.screenshot("expanded-list-at-bottom-before-wheel");
  await browser.mouse.move(point.x, point.y);
  for (let i = 0; i < 3; i++) await browser.mouse.wheel(0, 120);
  await new Promise(r => setTimeout(r, 700));
  const expandedScroll = await read();
  await app.screenshot("expanded-list-at-bottom-after-wheel");
  console.log(JSON.stringify({ shortScroll, expandedScroll, panelMax: point.max, expandedListMax: point.listMax }));
  expect(shortScroll).toBeGreaterThan(0);
  expect(expandedScroll).toBeGreaterThan(0);
});
