/* ============================================================
   3DAX — Story: pinned scroll storytelling of the deckbox
   ============================================================ */
function Story({ onShop }){
  const sectionRef = useRef(null);
  const frameRefs = useRef([]);
  const labelWrapRef = useRef(null);
  const fillRef = useRef(null);
  const [phase, setPhase] = useState(0);

  const frames = [
    { img: "assets/products/chopper-tall-front.png", scale: 1.0 },
    { img: "assets/products/chopper-open.png",       scale: 1.04 },
    { img: "assets/products/chopper-exploded.png",   scale: 1.06 },
    { img: "assets/products/chopper-top.png",        scale: 1.02 },
  ];

  const chapters = [
    { kicker: "Capítulo 01", title: "Una sola pieza,\nimponente.",
      body: "Cerrada mide para 100+ cartas enfundadas. Cartel “Wanted” en relieve al frente, flores de cerezo en la base. Una silueta que pide estar a la vista." },
    { kicker: "Capítulo 02", title: "Se abre con\nun “click”.",
      body: "La tapa encaja a presión con tolerancias finas. Por dentro, un retrato esculpido te recibe cada vez que la abres." },
    { kicker: "Capítulo 03", title: "Tres piezas,\ncero plástico genérico.",
      body: "Tapa, caja y base se imprimen y acaban por separado para que cada cara cuente con su propio relieve. Nada es liso. Nada es casual." },
    { kicker: "Capítulo 04", title: "Detalle hasta\nel último mm.",
      body: "Esquinas reforzadas, interior limpio y un acabado mate de coleccionista. Mira dentro: incluso el fondo está esculpido." },
  ];

  const labels = [
    { t: "Tapa",  x: "63%", y: "26%" },
    { t: "Caja",  x: "24%", y: "60%" },
    { t: "Base",  x: "80%", y: "74%" },
  ];

  useEffect(() => {
    let raf = 0;
    const update = () => {
      raf = 0;
      const sec = sectionRef.current; if(!sec) return;
      const vh = window.innerHeight;
      const total = sec.offsetHeight - vh;
      const p = Math.min(1, Math.max(0, (window.scrollY - sec.offsetTop) / total));

      // frame crossfade — centers spread across progress
      const centers = [0.10, 0.38, 0.66, 0.92];
      const span = 0.20;
      frames.forEach((f, i) => {
        const el = frameRefs.current[i]; if(!el) return;
        const d = Math.abs(p - centers[i]);
        let o = Math.max(0, 1 - d / span);
        o = o * o * (3 - 2 * o); // smoothstep
        el.style.opacity = o.toFixed(3);
        const sc = f.scale * (0.96 + 0.06 * o);
        const dir = i % 2 === 0 ? 1 : -1;
        el.style.transform = `translate3d(${(p - centers[i]) * 60 * dir}px, ${(p - centers[i]) * -40}px, 0) scale(${sc})`;
      });

      // exploded labels appear only near frame 3
      const lw = labelWrapRef.current;
      if(lw){
        const d = Math.abs(p - centers[2]);
        let o = Math.max(0, 1 - d / 0.14);
        lw.style.opacity = (o*o*(3-2*o)).toFixed(3);
      }

      // progress fill
      if(fillRef.current) fillRef.current.style.transform = `scaleY(${p})`;

      // active chapter
      let ph = 0;
      for(let i=0;i<centers.length;i++){ if(p >= centers[i] - 0.14) ph = i; }
      setPhase(ph);
    };
    const onScroll = () => { if(!raf) raf = requestAnimationFrame(update); };
    window.addEventListener("scroll", onScroll, { passive:true });
    window.addEventListener("resize", onScroll);
    update();
    return () => { window.removeEventListener("scroll", onScroll); window.removeEventListener("resize", onScroll); cancelAnimationFrame(raf); };
  }, []);

  return (
    <>
    <section className="story grain" id="story" ref={sectionRef} data-screen-label="Story">
      <div className="story__sticky">
        <div className="blob" style={{ width:620, height:620, top:"50%", left:"58%", transform:"translate(-50%,-50%)", background:"rgba(217,138,43,.13)" }} />

        <div className="story__inner wrap">
          {/* text column */}
          <div className="story__text">
            <div className="story__chapters">
              {chapters.map((c, i) => (
                <div key={i} className={"story__chapter" + (i === phase ? " is-active" : i < phase ? " is-past" : "")}>
                  <div className="kicker" style={{ color:"var(--gold)" }}>{c.kicker}</div>
                  <h2 className="display story__title">{c.title.split("\n").map((l,j)=><span key={j} style={{display:"block"}}>{l}</span>)}</h2>
                  <p className="lead story__body">{c.body}</p>
                </div>
              ))}
            </div>
            <div className="story__dots">
              {chapters.map((_, i) => (
                <span key={i} className={"story__dot" + (i === phase ? " on" : "")} />
              ))}
            </div>
          </div>

          {/* product stage */}
          <div className="story__stage">
            <div className="story__halo" />
            {frames.map((f, i) => (
              <img key={i} ref={el => frameRefs.current[i] = el}
                   className="story__frame prod-shadow" src={f.img} alt=""
                   style={{ opacity: i === 0 ? 1 : 0, zIndex: 10 - i }} />
            ))}
            <div ref={labelWrapRef} className="story__labels" style={{ opacity:0 }}>
              {labels.map((l, i) => (
                <div key={i} className="story__label" style={{ left:l.x, top:l.y }}>
                  <span className="story__label-dot" />
                  <span className="story__label-t">{l.t}</span>
                </div>
              ))}
            </div>
          </div>
        </div>

        {/* vertical progress */}
        <div className="story__progress">
          <span className="story__progress-track"><span ref={fillRef} className="story__progress-fill" /></span>
        </div>
      </div>
    </section>

    <section className="story-outro grain">
      <div className="wrap">
        <Reveal className="story__outro-inner">
          <h3 className="display">Y esto es solo<br/>una de <em>50+</em> historias.</h3>
          <button className="btn btn-gold btn-lg" onClick={onShop}>Explorar la colección <span className="arr">→</span></button>
        </Reveal>
      </div>
    </section>
    </>
  );
}
window.Story = Story;
