// JungleSection.jsx — single-row animal marquee with four live portraits.
const JUNGLE_CREATURES = window.JUNGLE_CREATURES || [];

function JungleCreature({ creature }) {
  const videoRef = React.useRef(null);
  const mobile = useMobileLayout(900);
  const isVideo = creature.type === "video";
  const cached = useVideoCached(isVideo ? creature.src : null);
  const showPoster = isVideo && mobile && creature.poster && !cached;

  useInViewVideo(videoRef, isVideo && !showPoster);

  return (
    <li
      className={`zg-jungle-portrait${isVideo ? " zg-jungle-portrait--video" : ""}`}
    >
      {isVideo && !showPoster ? (
        <video
          ref={videoRef}
          src={creature.src}
          poster={creature.poster}
          loop
          muted
          playsInline
          preload="none"
          style={{ objectPosition: creature.position || "50% 50%" }}
          aria-hidden="true"
        />
      ) : (
        <img
          src={showPoster ? creature.poster : creature.src}
          alt=""
          loading="lazy"
          decoding="async"
          aria-hidden="true"
        />
      )}
      <span className="zg-jungle-portrait-ring" aria-hidden="true" />
    </li>
  );
}

function JungleSection() {
  const sectionRef = React.useRef(null);
  const playedRef = React.useRef(false);
  const mobile = useMobileLayout(900);

  const splitIndex = Math.ceil(JUNGLE_CREATURES.length / 2);
  const rowA = mobile ? JUNGLE_CREATURES.slice(0, splitIndex) : JUNGLE_CREATURES;
  const rowB = mobile ? JUNGLE_CREATURES.slice(splitIndex) : [];
  const trackA = [...rowA, ...rowA];
  const trackB = [...rowB, ...rowB];

  React.useEffect(() => {
    const section = sectionRef.current;
    if (!section) return undefined;

    const reduced = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
    const gsap = window.gsap;

    const play = () => {
      if (playedRef.current) return;
      playedRef.current = true;

      const opener = section.querySelector(".zg-jungle-opener");
      const stage = section.querySelector(".zg-jungle-stage");

      if (reduced || !gsap) {
        section.classList.add("zg-jungle-section--revealed");
        return;
      }

      const tl = gsap.timeline({ defaults: { ease: "power3.out" } });

      tl.from(opener, { opacity: 0, y: 24, duration: 0.75 }).from(
        stage,
        { opacity: 0, y: 28, duration: 0.82 },
        "-=0.42"
      );

      tl.add(() => section.classList.add("zg-jungle-section--revealed"));
    };

    const io = new IntersectionObserver(
      ([entry]) => {
        if (entry.isIntersecting) {
          play();
          io.disconnect();
        }
      },
      { threshold: 0.22 }
    );

    io.observe(section);
    return () => io.disconnect();
  }, []);

  return (
    <section
      ref={sectionRef}
      className={`zg-jungle-section${mobile ? " zg-jungle-section--stacked" : ""}`}
      aria-labelledby="zg-jungle-title"
    >
      <div className="zg-container">
        <header className="zg-jungle-opener">
          <span className="label">After launch</span>
          <h2 id="zg-jungle-title">
            Launch is not <span className="zg-highlight">the finish line</span>.
          </h2>
          <p className="zg-jungle-lede">
            We stay in and keep improving the workflow once real users, real data,
            and edge cases show up.
          </p>
        </header>

        <div className="zg-jungle-stage">
          <div className="zg-jungle-marquee-wrap">
            <ul className="zg-jungle-track" aria-hidden="true">
              {trackA.map((creature, index) => (
                <JungleCreature key={`a-${creature.src}-${index}`} creature={creature} />
              ))}
            </ul>
          </div>
          {mobile && rowB.length > 0 && (
            <div className="zg-jungle-marquee-wrap zg-jungle-marquee-wrap--reverse">
              <ul className="zg-jungle-track zg-jungle-track--reverse" aria-hidden="true">
                {trackB.map((creature, index) => (
                  <JungleCreature key={`b-${creature.src}-${index}`} creature={creature} />
                ))}
              </ul>
            </div>
          )}
        </div>
      </div>
    </section>
  );
}

window.JungleSection = JungleSection;
