import { test, expect } from "@playwright/test";

// Regression: the steady-state loop (#vid-loop) restarts from the morph-tail
// offset via a narrow timeupdate window. If that window is ever missed the clip
// fires `ended` and — without a safety net — freezes on its last frame ("videos
// aren't looping"). This asserts the `ended` safety net recovers playback.
test("loop recovers when a clip reaches `ended` (no freeze on last frame)", async ({ page }) => {
  await page.goto("/");
  await page.waitForFunction(
    () => document.querySelector("#loading")?.classList.contains("done"),
    null,
    { timeout: 45_000 },
  );

  const r = await page.evaluate(async () => {
    const lv = document.getElementById("vid-loop") as HTMLVideoElement;
    // Reproduce the stuck state: parked on the last frame, as after a missed wrap.
    lv.pause();
    lv.currentTime = Math.max(0, lv.duration - 0.001);
    // The browser emits `ended` here in real life; emit it deterministically.
    lv.dispatchEvent(new Event("ended"));
    await new Promise((res) => setTimeout(res, 800));
    return { dur: +lv.duration.toFixed(2), ct: +lv.currentTime.toFixed(2), paused: lv.paused };
  });

  // Recovered: playing again, and seeked back near the loop tail (not stuck at end).
  expect(r.paused).toBe(false);
  expect(r.ct).toBeLessThan(5);
});
