/* ============================================================
   Sara Akef, interactive components
   MotionSeq, motion-from-stills
   Shared via window.* (Babel scope isolation)
   ============================================================ */
const { useState: useStateX, useEffect: useEffectX, useRef: useRefX } = React;

/* ---- data: featured works come from the shared profile (profile.jsx) ---- */
const SA_WORKS = ((window.SARA_PROFILE && window.SARA_PROFILE.credits) || [])
  .filter((c) => c.featured)
  .map((c) => (window.SA_L ? window.SA_L(c) : c))
  .map((c) => ({
    id: c.id, title: c.title, fa: c.fa, year: c.year,
    disc: c.kind, warm: !!c.warm, alt: !!c.alt,
    tags: c.tags || [], galleryFrames: c.galleryFrames || c.frames || [],
    frames: (c.frames && c.frames.length) ? c.frames : (c.galleryFrames || []),
    posterOnly: !(c.frames && c.frames.length), focus: c.focus || null, video: c.video || null,
  }));

/* ---- MotionSeq: cross-fading flipbook of stills ----
   mode "hover" (work thumbs) | controlled via `index` */
function MotionSeq({ frames, warm, playing, fps = 8, index = null, className = "", alt = "" }) {
  const [i, setI] = useStateX(0);
  const timer = useRefX(null);

  useEffectX(() => {
    if (index !== null) { setI(index % frames.length); return; }
    if (playing) {
      // respect reduced-motion only for ambient (continuous) loops, not user hover
      const reduce = window.matchMedia && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
      if (reduce) { setI(0); return; }
      timer.current = setInterval(() => setI((p) => (p + 1) % frames.length), 1000 / fps);
      return () => clearInterval(timer.current);
    } else {
      setI(0);
    }
  }, [playing, index, frames.length, fps]);

  return (
    <div className={"mseq" + (warm ? " warm" : "") + (className ? " " + className : "")}>
      {frames.map((src, n) => (
        <img key={n} src={src} alt={n === 0 && alt ? alt : ""} className={n === i ? "on" : ""}
             loading={n === 0 ? "eager" : "lazy"} draggable="false" />
      ))}
    </div>
  );
}
window.MotionSeq = MotionSeq;
window.SA_WORKS = SA_WORKS;
