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

test("Details card leaves before shrinking and returns after expansion", WEB, async ({ t3, app, screen, browser }) => {
  await browser.setViewport({ width: 1600, height: 1000 });
  const project = await t3.project("panel-demo");
  const thread = await t3.thread({ project, title: "Panel animation", messages: ["Show the demo"], model: "multi-turn" });
  await t3.open("/settings/appearance#panel-animations");
  const slider = screen.getByRole("slider", "Panel animation duration");
  await slider.press("Home");
  for (let i = 0; i < 10; i++) await slider.press("ArrowRight");
  await t3.open(thread);
  await expect(browser.locator('[data-thread-details-panel="inline"]')).toBeVisible();
  await app.screenshot("closed-1600");
  const results = [];
  for (const width of [1600, 1920]) {
    await browser.setViewport({ width, height: 1000 });
    for (let cycle = 0; cycle < 2; cycle++) {
      for (const direction of ["opening", "closing"]) {
        await browser.evaluate(() => {
          const w = window as any;
          w.panelSamples = new Promise((resolve) => {
            document.addEventListener("click", () => {
              const start = performance.now();
              const frames: any[] = [];
              const read = () => {
                const canvas = document.querySelector('[data-chat-canvas]')!;
                const composer = document.querySelector('[data-chat-composer-form="true"]');
                frames.push({ ms: Math.round(performance.now() - start), width: canvas.clientWidth,
                  inline: !!document.querySelector('[data-thread-details-panel="inline"]'),
                  composerX: composer?.getBoundingClientRect().x ?? null,
                  running: document.getAnimations().some((a) => a instanceof CSSTransition && a.transitionProperty === 'width' && a.playState === 'running') });
                };
              let previous = !!document.querySelector('[data-thread-details-panel="inline"]');
              const observer = new MutationObserver(() => {
                const inline = !!document.querySelector('[data-thread-details-panel="inline"]');
                if (inline !== previous) { read(); previous = inline; }
              });
              observer.observe(document.querySelector('[data-chat-canvas]')!, { childList: true, subtree: true });
              const sample = () => {
                read();
                if (performance.now() - start < 650) requestAnimationFrame(sample);
                else { observer.disconnect(); resolve(frames); }
              };
              requestAnimationFrame(sample);
            }, { once: true, capture: true });
          });
        });
        await screen.getByRole("button", "Toggle right panel").tap();
        const frames = await browser.evaluate(() => (window as any).panelSamples) as any[];
        results.push({ width, cycle, direction, frames });
        console.log(JSON.stringify({ width, cycle, direction, frames }));
        await app.screenshot(`${width}-${cycle}-${direction}`);
      }
    }
  }
  // Opening must drop the inline card while the canvas is still at its wide endpoint;
  // closing must wait until it reaches that endpoint again. The 1920px control stays inline.
  const transitions = results.filter((r) => r.width === 1600).map((r) => ({
    direction: r.direction,
    switchWidth: r.frames.find((f) => r.direction === "opening" ? !f.inline : f.inline)?.width ?? 0,
  }));
  console.log("PRESENTATION SWITCHES", JSON.stringify(transitions));
  await expect(transitions.every((r) => r.switchWidth >= 1335)).toBe(true);
  await expect(results.filter((r) => r.width === 1920).every((r) => r.frames.every((f) => f.inline))).toBe(true);
});
