// Agency "sticky card stack" — scroll-LINKED (best practice), niente scroll-jacking.
// La sezione e' alta piu' schermate; un wrapper interno resta sticky (pinned) mentre
// scorri, e la card attiva e' derivata dalla posizione di scroll NATIVA. Cosi' lo
// scroll resta fluido e naturale (nessuna lotta con l'inerzia del trackpad), non si
// incastra mai, su/giu' e' simmetrico e non si puo' "sfondare" una card perche'
// ognuna occupa una fetta di scroll.
function AgencyStack({ navigate }) {
  const cards = [
    {
      id: "youtube",
      slug: "agency-yt",
      bg: "#3B5BFF",
      btn: "#3B5BFF",
      title: "YouTube Long-Form\nVideo Production",
      body: [
        "Produciamo e gestiamo canali YouTube in white label per aziende, per posizionarle come autorità nel proprio settore.",
        "Gestiamo la ricerca dei topic, scripting, registrazione, post-production, copertine, SEO, pubblicazione e analytics.",
      ],
      img: "assets/Card-YT.webp",
    },
    {
      id: "short",
      slug: "agency-shortform",
      bg: "#7A4DFF",
      btn: "#7A4DFF",
      title: "Short Form Video\n& UGC Production",
      body: [
        "Produciamo video short form e UGC per aziende che vogliono pubblicare in organico o fare advertising su Meta e YouTube con contenuti che convertono.",
        "Gestiamo hook, scripting, casting, registrazione, editing e consegna dei file e reporting.",
      ],
      img: "assets/Card-UGC.webp",
    },
    {
      id: "social",
      slug: "agency-social",
      bg: "#FF6B9F",
      btn: "#FF6B9F",
      title: "Social Media &\nContent Production",
      body: [
        "Gestiamo la presenza social delle aziende su Instagram, LinkedIn e TikTok: dalla strategia editoriale alla pubblicazione.",
        "Gestiamo il PED, la produzione di post e caroselli, il copywriting, la programmazione e il reporting.",
      ],
      img: "assets/Card-SMM.webp",
    },
  ];

  // Quanta altezza di scroll "dedicare" a ogni card: piu' alto = la card resta
  // visibile piu' a lungo mentre scorri (e la transizione e' piu' rilassata).
  const VH_PER_CARD = 95;

  const sectionRef = React.useRef(null);
  const [active, setActive] = React.useState(0);

  React.useEffect(() => {
    const section = sectionRef.current;
    if (!section) return;
    const N = cards.length;
    let raf = 0;

    const compute = () => {
      raf = 0;
      const rect = section.getBoundingClientRect();
      const start = window.scrollY + rect.top;                 // top della sezione nel documento
      const scrollable = section.offsetHeight - window.innerHeight; // scroll totale dentro il pin
      const p = scrollable > 0 ? (window.scrollY - start) / scrollable : 0;
      const clamped = Math.max(0, Math.min(0.999999, p));
      const idx = Math.min(N - 1, Math.floor(clamped * N));    // ogni card = una fetta uguale
      setActive((prev) => (prev === idx ? prev : idx));
    };

    const onScroll = () => { if (!raf) raf = requestAnimationFrame(compute); };

    compute();
    window.addEventListener("scroll", onScroll, { passive: true });
    window.addEventListener("resize", onScroll, { passive: true });
    return () => {
      window.removeEventListener("scroll", onScroll);
      window.removeEventListener("resize", onScroll);
      if (raf) cancelAnimationFrame(raf);
    };
  }, []);

  return (
    <section ref={sectionRef} style={{
      background: "#fff",
      position: "relative",
      // Altezza = una schermata di "pin" per card. Lo scroll attraverso questa
      // altezza fa avanzare le card, poi la pagina prosegue normalmente.
      height: `${cards.length * VH_PER_CARD + 100}vh`,
    }}>
      <div style={{
        position: "sticky", top: 0, height: "100vh",
        display: "flex", alignItems: "center", justifyContent: "center",
        background: "#fff", overflow: "hidden",
      }}>
        <div style={{ position: "relative", width: "100%", height: "100%" }}>
          {cards.map((c, i) => {
            const offset = i - active; // quante card sotto la corrente
            // Le card sotto (offset > 0) stanno piu' in basso e sfumate; la corrente sopra.
            const translateY = offset > 0 ? `${offset * 8}vh` : "0";
            const scale = offset > 0 ? 1 - offset * 0.04 : 1;
            const opacity = offset > 0 ? 0 : 1;
            return (
              <div key={c.id} style={{
                position: "absolute", inset: 0,
                display: "flex", alignItems: "center", justifyContent: "center",
                zIndex: i + 1,
                transform: `translateY(${translateY}) scale(${scale})`,
                opacity,
                transition: "transform 600ms cubic-bezier(.22,1,.36,1), opacity 500ms ease",
                pointerEvents: i === active ? "auto" : "none",
              }}>
                <article style={{
                  background: c.bg,
                  borderRadius: 28,
                  width: "min(1320px, 92vw)",
                  height: "min(82vh, 700px)",
                  display: "grid",
                  gridTemplateColumns: "1fr 1.1fr",
                  alignItems: "center",
                  padding: "clamp(40px, 5vw, 80px)",
                  gap: "clamp(24px, 3vw, 56px)",
                  overflow: "hidden",
                  boxShadow: "0 30px 80px -30px rgba(0,0,0,0.35)",
                }} className="agency-card">
                  <div style={{ color: "#fff" }}>
                    <h3 style={{
                      fontFamily: "var(--font-display)", fontWeight: 700,
                      fontSize: "clamp(32px, 3.4vw, 52px)", lineHeight: 1.05,
                      letterSpacing: "-0.025em", margin: 0,
                      whiteSpace: "pre-line",
                      color: "#fff",
                    }}>
                      {c.title}
                    </h3>
                    <div style={{ marginTop: 28, display: "flex", flexDirection: "column", gap: 16 }}>
                      {c.body.map((p, idx) => (
                        <p key={idx} style={{
                          margin: 0, fontSize: "clamp(14px, 1.05vw, 16px)",
                          lineHeight: 1.55, color: "rgba(255,255,255,0.95)",
                        }}>{p}</p>
                      ))}
                    </div>
                    <button
                      onClick={() => navigate(c.slug)}
                      style={{
                        marginTop: 36,
                        background: c.btn, color: "#fff",
                        fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 16,
                        padding: "14px 26px", borderRadius: "999px 999px 999px 0px",
                        border: "1px solid rgba(255,255,255,0.5)",
                        display: "inline-flex", alignItems: "center", gap: 10,
                        cursor: "pointer",
                        transition: "background 200ms, color 200ms",
                      }}
                      onMouseEnter={(e)=>{ e.currentTarget.style.background = "#fff"; e.currentTarget.style.color = c.btn; }}
                      onMouseLeave={(e)=>{ e.currentTarget.style.background = c.btn; e.currentTarget.style.color = "#fff"; }}>
                      Scopri di più <ArrowRight />
                    </button>
                  </div>
                  <div style={{ display: "flex", alignItems: "center", justifyContent: "center", height: "100%" }}>
                    <img src={c.img} alt="" style={{
                      maxWidth: "100%", maxHeight: "100%", width: "auto", height: "auto",
                      objectFit: "contain",
                    }} />
                  </div>
                </article>
              </div>
            );
          })}
        </div>

        {/* Step indicator */}
        <div style={{
          position: "absolute", bottom: 28, left: "50%", transform: "translateX(-50%)",
          display: "flex", gap: 10, zIndex: 50,
        }}>
          {cards.map((_, i) => (
            <span key={i} style={{
              width: i === active ? 28 : 10, height: 10, borderRadius: 999,
              background: i === active ? "#0A0A0A" : "rgba(0,0,0,0.18)",
              transition: "width 300ms, background 300ms",
            }} />
          ))}
        </div>
      </div>

      <style>{`
        @media (max-width: 880px){
          .agency-card {
            grid-template-columns: 1fr !important;
            height: 80vh !important;
            max-height: 680px !important;
            padding: 44px 28px !important;
            align-content: center;
            gap: 16px !important;
          }
          .agency-card img { max-height: 24vh !important; }
        }
      `}</style>
    </section>
  );
}

window.AgencyStack = AgencyStack;
