import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("Thread details changes presentation only at panel motion boundaries", WEB, async ({ t3, app, screen, browser }) => {
  await browser.setViewport({ width: 1600, height: 1000 });
  const project = await t3.project("Panel animation demo");
  const thread = await t3.thread({ project, title: "Panel animation", messages: ["Show a short example"], model: "multi-turn" });
  await t3.open("/settings/appearance");
  await screen.getByRole("button", "Advanced").first().waitFor({ state: "visible" });
  await browser.evaluate(() => {
    for (const button of document.querySelectorAll("button")) {
      if (button.textContent?.trim() === "Advanced") button.click();
    }
  });
  await screen.getByRole("slider", "Panel animation duration").tap();
  await browser.keyboard.press("Home");
  for (let i = 0; i < 10; i++) await browser.keyboard.press("ArrowRight");
  await t3.open(thread);
  await screen.getByRole("button", "Toggle right panel").waitFor({ state: "visible" });
  await screen.getByText("first fixture turn complete", { exact: true }).waitFor({ state: "visible" });
  await screen.getByText("Loading messages...", { exact: true }).waitFor({ state: "hidden" });
  await screen.getByText("Syncing messages...", { exact: true }).waitFor({ state: "hidden" });
  await app.screenshot("closed-before-motion");
  const results = [];
  for (let cycle = 0; cycle < 3; cycle++) {
    if (cycle === 2) {
      await browser.setViewport({ width: 1920, height: 1000 });
      await app.screenshot("wide-control-before-motion");
    }
    for (const direction of ["opening", "closing"]) {
      const result = await browser.evaluate(async (direction) => {
        const canvas = document.querySelector<HTMLElement>("[data-chat-canvas]")!;
        const inline = () => !!document.querySelector('[data-thread-details-panel="inline"]');
        const initial = inline();
        const startWidth = canvas.clientWidth;
        const button = document.querySelector<HTMLButtonElement>('button[aria-label="Toggle right panel"]')!;
        const samples: { ms: number; width: number; inline: boolean; running: boolean; progress: number }[] = [];
        const start = performance.now();
        const changes: typeof samples = [];
        let previous = initial;
        const observer = new MutationObserver(() => {
          const current = inline();
          if (current === previous) return;
          previous = current;
          const panels = document.querySelectorAll('[data-slot="sidebar-gap"], [data-preview-panel-mode="inline"]');
          const transitions = Array.from(panels).flatMap((p) => p.getAnimations()).filter((a) => a instanceof CSSTransition && a.transitionProperty === "width" && a.playState === "running");
          changes.push({ ms: Math.round(performance.now() - start), width: canvas.clientWidth, inline: current, running: transitions.length > 0, progress: Number(transitions[0]?.effect?.getComputedTiming().progress ?? 0) });
        });
        observer.observe(canvas, { subtree: true, childList: true });
        button.click();
        await new Promise<void>((resolve) => {
          const frame = () => {
            const panels = document.querySelectorAll('[data-slot="sidebar-gap"], [data-preview-panel-mode="inline"]');
            const transitions = Array.from(panels).flatMap((p) => p.getAnimations()).filter((a) => a instanceof CSSTransition && a.transitionProperty === "width" && a.playState === "running");
            samples.push({ ms: Math.round(performance.now() - start), width: canvas.clientWidth, inline: inline(), running: transitions.length > 0, progress: Number(transitions[0]?.effect?.getComputedTiming().progress ?? 0) });
            if (performance.now() - start < 650) requestAnimationFrame(frame); else resolve();
          };
          requestAnimationFrame(frame);
        });
        observer.disconnect();
        return { direction, initial, startWidth, endWidth: canvas.clientWidth, changes, samples };
      }, direction);
      results.push(result);
      console.log(JSON.stringify({ cycle, ...result }));
      await app.screenshot(`${direction}-cycle-${cycle + 1}`);
    }
  }
  const midMotionChanges = results.flatMap((r) => r.changes.filter((s) => s.running && s.progress > 0 && s.progress < 1));
  await expect(midMotionChanges).toEqual([]);
});
