"use client";

import { useEffect, useLayoutEffect, useRef, useState } from "react";

/**
 * Plays a comic strip like an animated Sunday strip: when it scrolls into
 * view, the panels ink in one after another, each balloon popping in after
 * its drawing. "Read it again" replays it. Before the strip is armed (no
 * JavaScript, or reduced motion), every panel simply shows.
 */
export default function ComicPlayer({ children, replayLabel = "Read it again" }: { children: React.ReactNode; replayLabel?: string }) {
  const ref = useRef<HTMLDivElement>(null);
  const [state, setState] = useState<"static" | "armed" | "playing">("static");

  useLayoutEffect(() => {
    if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) return;
    setState("armed");
  }, []);

  useEffect(() => {
    if (state !== "armed") return;
    const el = ref.current;
    if (!el || !("IntersectionObserver" in window)) {
      setState("playing");
      return;
    }
    const io = new IntersectionObserver(
      (entries) => {
        if (entries.some((e) => e.isIntersecting)) {
          setState("playing");
          io.disconnect();
        }
      },
      { threshold: 0.25 }
    );
    io.observe(el);
    return () => io.disconnect();
  }, [state]);

  const replay = () => {
    setState("armed");
    requestAnimationFrame(() => requestAnimationFrame(() => setState("playing")));
  };

  return (
    <div ref={ref} className={`comic-player is-${state}`}>
      {children}
      {state !== "static" && (
        <button type="button" className="comic-replay" onClick={replay}>
          {replayLabel}
        </button>
      )}
    </div>
  );
}
