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

test("Busy fork respects reduced motion and keeps its normal-motion pulse", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("demo");
  await t3.open();
  await browser.locator("[data-chat-provider-model-picker-label]").first().tap();
  await screen.getByRole("option", /Multi turn/).waitFor();
  await browser.keyboard.press("Escape");
  const thread = await t3.thread({ project, title: "Fork motion", messages: ["Start"] });
  await browser.addInitScript(() => {
    const send = WebSocket.prototype.send;
    WebSocket.prototype.send = function(data) {
      if (typeof data === "string") {
        const frames = [JSON.parse(data)].flat();
        if (frames.some(frame => frame.tag === "orchestration.dispatchCommand" && frame.payload?.type === "thread.fork")) return;
      }
      return send.call(this, data);
    };
  });
  await browser.emulateMedia({ reducedMotion: "reduce", colorScheme: "dark" });
  await t3.open(thread);
  await screen.getByText("first fixture turn complete", { exact: false }).waitFor();
  const fork = screen.getByRole("button", "Fork from this response", { exact: true }).last();
  await fork.tap();
  await browser.locator('button[aria-label="Fork from this response"]:disabled').waitFor();
  const sample = () => browser.evaluate(async () => {
    const button = document.querySelector<HTMLButtonElement>('button[aria-label="Fork from this response"]:disabled')!;
    const icon = button.querySelector("svg")!;
    const opacities: number[] = [];
    const started = performance.now();
    let previous = -200;
    await new Promise<void>(resolve => {
      const frame = () => {
        const elapsed = performance.now() - started;
        if (elapsed - previous >= 200) { opacities.push(Number(getComputedStyle(icon).opacity)); previous = elapsed; }
        if (elapsed >= 2200) resolve(); else requestAnimationFrame(frame);
      };
      requestAnimationFrame(frame);
    });
    return { reduced: matchMedia('(prefers-reduced-motion: reduce)').matches, disabled: button.disabled, animation: getComputedStyle(icon).animationName, opacities };
  });
  const reduced = await sample();
  await app.screenshot("busy-fork-reduced-motion");
  await browser.emulateMedia({ reducedMotion: "no-preference" });
  const normal = await sample();
  await app.screenshot("busy-fork-normal-motion-control");
  console.log(JSON.stringify({ reduced, normal }));
  expect(normal.animation).toBe("pulse");
  expect(reduced.animation).toBe("none");
});
