/* ============================================================
   ZAYNAB SAPHIR — Film Collage
   A four-pane mosaic. Only one pane runs film at a time — the
   others hold their still — so the section stays light and the
   eye is led around the grid. The live pane advances every 7 s.
   ============================================================ */

function FilmPane({ src, poster, label, className, live }) {
  const ref = useRef(null);

  useEffect(() => {
    const el = ref.current;
    if (!el || !live) return;
    el.currentTime = 0;
    const pr = el.play();
    if (pr && pr.catch) pr.catch(() => {});
    return () => { try { el.pause(); } catch (e) {} };
  }, [live, src]);

  return (
    <figure className={"film-pane " + (className || "") + (live ? " live" : "")}>
      {poster ? (
        <img className="film-still" src={poster} alt="" aria-hidden="true" />
      ) : (
        <Ph label={label} ratio="tall" style={{ position: "absolute", inset: 0 }} />
      )}
      {live && src ? (
        <video
          ref={ref}
          className="film-media"
          src={src}
          muted
          loop
          playsInline
          preload="auto"
          aria-hidden="true"
        />
      ) : null}
      <span className="film-tag mono">{label}</span>
    </figure>
  );
}

function FilmCollage() {
  const V = window.RB_VIDEOS || [];
  const I = window.RB_IMGS || {};
  const panes = [
    { src: V[0], poster: I["LOOK 01 · DRESS"], label: "The Collection", className: "a" },
    { src: V[1], poster: I["LOOK · EVENING EDIT"], label: "Evening", className: "b" },
    { src: V[2], poster: I["DETAIL · FABRIC"], label: "Detail", className: "c" },
    { src: V[3], poster: I["LOOK · WARDROBE ESSENTIALS"], label: "In Motion", className: "d" }
  ];

  const [cur, setCur] = useState(0);
  const [inView, setInView] = useState(false);
  const secRef = useRef(null);

  useEffect(() => {
    const el = secRef.current;
    if (!el) return;
    const io = new IntersectionObserver(
      (ents) => ents.forEach((e) => setInView(e.isIntersecting)),
      { threshold: 0.25 }
    );
    io.observe(el);
    return () => io.disconnect();
  }, []);

  useEffect(() => {
    if (!inView) return;
    const t = setInterval(() => setCur((i) => (i + 1) % panes.length), 7000);
    return () => clearInterval(t);
  }, [inView, panes.length]);

  return (
    <section className="sec film-sec" ref={secRef}>
      <div className="wrap">
        <div className="film-head">
          <Eyebrow line>In motion</Eyebrow>
          <h2 className="display film-h">The films</h2>
        </div>
        <div className="film-grid">
          {panes.map((p, i) => (
            <FilmPane key={p.label} {...p} live={inView && i === cur} />
          ))}
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { FilmCollage, FilmPane });
