/* ============================================================
   CinematicCarousel — gallery storytelling, drift, parallax
   ============================================================ */
const { useEffect, useRef, useState } = React;

function CinematicCarousel({ slides, speed = 28 }) {
  const stageRef = useRef(null);
  const trackRef = useRef(null);
  const offsetRef = useRef(0);
  const lastTimeRef = useRef(null);
  const widthRef = useRef(0);
  const pausedRef = useRef(false);
  const dragRef = useRef({ active: false, startX: 0, startOffset: 0, moved: 0 });
  const [progress, setProgress] = useState(0);

  // duplicate for seamless wrap
  const items = [...slides, ...slides];

  useEffect(() => {
    const track = trackRef.current;
    if (!track) return;

    const recalc = () => {
      // Width of ONE complete set (first half of children)
      const children = track.children;
      const gap = parseFloat(getComputedStyle(track).columnGap || getComputedStyle(track).gap || "0") || 0;
      let w = 0;
      for (let i = 0; i < slides.length; i++) {
        const c = children[i];
        if (!c) continue;
        w += c.offsetWidth;
        if (i < slides.length - 1) w += gap;
      }
      // include trailing gap before duplicate set
      w += gap;
      widthRef.current = w;
    };

    // first paint — wait for images to load enough
    requestAnimationFrame(recalc);
    setTimeout(recalc, 200);
    setTimeout(recalc, 800);
    setTimeout(recalc, 1600);
    const ro = new ResizeObserver(recalc);
    ro.observe(track);

    let raf;
    const step = (t) => {
      if (lastTimeRef.current == null) lastTimeRef.current = t;
      const dt = Math.min(0.05, (t - lastTimeRef.current) / 1000);
      lastTimeRef.current = t;

      if (!pausedRef.current && !dragRef.current.active) {
        offsetRef.current -= speed * dt;
      }

      const W = widthRef.current;
      if (W > 0) {
        while (offsetRef.current <= -W) offsetRef.current += W;
        while (offsetRef.current > 0) offsetRef.current -= W;
      }

      track.style.transform = `translate3d(${offsetRef.current}px, 0, 0)`;

      // parallax inner layer drift on each slide
      const slidesEls = track.querySelectorAll(".cine__slide__inner");
      slidesEls.forEach((el, i) => {
        const depth = (i % 3) * 0.4 + 0.3;
        el.style.transform = `translate3d(${offsetRef.current * 0.04 * depth}px, 0, 0)`;
      });

      setProgress(W > 0 ? Math.abs(offsetRef.current / W) * 100 : 0);
      raf = requestAnimationFrame(step);
    };
    raf = requestAnimationFrame(step);

    return () => { cancelAnimationFrame(raf); ro.disconnect(); };
  }, [slides.length, speed]);

  const onEnter = () => { pausedRef.current = true; };
  const onLeave = () => { pausedRef.current = false; };

  const onPointerDown = (e) => {
    dragRef.current = {
      active: true,
      startX: e.clientX,
      startOffset: offsetRef.current,
      moved: 0
    };
    try { e.currentTarget.setPointerCapture(e.pointerId); } catch {}
  };
  const onPointerMove = (e) => {
    if (!dragRef.current.active) return;
    const delta = e.clientX - dragRef.current.startX;
    dragRef.current.moved = Math.abs(delta);
    offsetRef.current = dragRef.current.startOffset + delta;
  };
  const endDrag = (e) => {
    if (dragRef.current.active) {
      dragRef.current.active = false;
      try { e.currentTarget.releasePointerCapture(e.pointerId); } catch {}
    }
  };

  const onWheel = (e) => {
    // horizontal wheel/scroll → drift faster temporarily
    const delta = Math.abs(e.deltaX) > Math.abs(e.deltaY) ? e.deltaX : e.deltaY * 0.6;
    offsetRef.current -= delta;
  };

  const nudge = (dir) => {
    offsetRef.current += dir * 360;
  };

  return (
    <div
      className="cine__stage"
      ref={stageRef}
      onMouseEnter={onEnter}
      onMouseLeave={onLeave}
      onPointerDown={onPointerDown}
      onPointerMove={onPointerMove}
      onPointerUp={endDrag}
      onPointerCancel={endDrag}
      onWheel={onWheel}
    >
      <div className="cine__track" ref={trackRef}>
        {items.map((s, i) => (
          <figure
            key={i}
            className={`cine__slide cine__slide--${s.variant}`}
            style={{ aspectRatio: s.aspect || undefined }}
          >
            <div className="cine__slide__inner" style={{ width: "100%", height: "100%" }}>
              <img src={s.src} alt={s.caption || ""} draggable="false" />
            </div>
            {s.caption && <figcaption className="cine__slide__caption">{s.caption}</figcaption>}
          </figure>
        ))}
      </div>
      <div className="cine__controls">
        <button className="cine__btn" onClick={() => nudge(1)} aria-label="anterior">← anterior</button>
        <div className="cine__progress">
          <div className="cine__progress__bar" style={{ width: `${progress}%` }} />
        </div>
        <button className="cine__btn" onClick={() => nudge(-1)} aria-label="próximo">próximo →</button>
      </div>
    </div>
  );
}

window.CinematicCarousel = CinematicCarousel;
