// Sottopagine dedicate per ognuna delle 3 verticali Media e dei 3 servizi Agency.
// Stesso linguaggio della home: PageHero centrato con HiBox, sezioni alternate
// bianco / #f6f6f6 / #F2F3F2, NumberStat, CTASplit a fondo pagina.

const { PageHero, PageNumberStat, CTASplit, HiBoxStatic, ctaPill, CaseStudiesAllVariants } = window;

/* ============ PROCESS GRID (pinned scroll-driven reveal) ============ */
function ProcessGrid({ items, accent, title }) {
  const pinned = items.some((it) => Array.isArray(it[3]) && it[3].length > 0);
  const wrapRef = React.useRef(null);
  const [progress, setProgress] = React.useState(0);
  const n = items.length;
  const easeOut = (t) => 1 - Math.pow(1 - t, 3);
  const [isMobile, setIsMobile] = React.useState(false);
  React.useEffect(() => {
    const mq = window.matchMedia("(max-width: 880px)");
    const update = () => setIsMobile(mq.matches);
    update();
    mq.addEventListener("change", update);
    return () => mq.removeEventListener("change", update);
  }, []);

  React.useEffect(() => {
    const el = wrapRef.current;
    if (!el) return;
    let raf = 0;
    const compute = () => {
      raf = 0;
      const rect = el.getBoundingClientRect();
      const vh = window.innerHeight || document.documentElement.clientHeight;
      if (pinned) {
        // Outer is taller than viewport; sticky inner stays put while we scroll
        // through (outerHeight - vh). progress = how far through that travel.
        const travel = el.offsetHeight - vh;
        const scrolled = -rect.top;
        const p = travel > 0 ? scrolled / travel : 0;
        setProgress(Math.max(0, Math.min(1, p)));
      } else {
        // Non-pinned fallback: viewport-passage progress
        const startY = vh * 0.85;
        const endY = vh * 0.15;
        const p = (startY - rect.top) / (startY - endY);
        setProgress(Math.max(0, Math.min(1, p)));
      }
    };
    const onScroll = () => { if (!raf) raf = requestAnimationFrame(compute); };
    compute();
    window.addEventListener("scroll", onScroll, { passive: true });
    window.addEventListener("resize", onScroll);
    return () => {
      window.removeEventListener("scroll", onScroll);
      window.removeEventListener("resize", onScroll);
      if (raf) cancelAnimationFrame(raf);
    };
  }, [pinned]);

  const cards = items.map((entry, i) => {
    const [num, ttl, body, bullets] = entry;
    // Reveal window per card. Use ~70% of progress to fit all cards,
    // leaving headroom at the end so the last card sits revealed before unpin.
    const usable = 0.78;
    const span = usable / n;
    const start = i * span;
    const end = start + span * 1.05;
    const local = Math.max(0, Math.min(1, (progress - start) / (end - start)));
    const eased = easeOut(local);
    const ty = (1 - eased) * 60;
    return (
      <div key={i} style={{
        background: "#F5F5F5", borderRadius: 18, padding: 36,
        display: "flex", flexDirection: "column", gap: 18,
        opacity: isMobile ? 1 : eased,
        transform: isMobile ? "none" : `translate3d(0, ${ty}px, 0)`,
        willChange: "opacity, transform"
      }}>
        <div style={{
          fontFamily: "var(--font-mono)", fontSize: 13,
          letterSpacing: "0.18em", color: accent, fontWeight: 700
        }}>{num}</div>
        <div style={{
          fontFamily: "var(--font-display)", fontWeight: 700,
          fontSize: 28, letterSpacing: "-0.02em", color: "#0A0A0A", lineHeight: 1.1
        }}>{ttl}</div>
        <div style={{ fontSize: 16, lineHeight: 1.55, color: "#4A4A4A", minHeight: "calc(16px * 1.55 * 4)" }}>{body}</div>
        {bullets && bullets.length > 0 && (
          <ul style={{ listStyle: "none", padding: 0, margin: "8px 0 0 0", display: "flex", flexDirection: "column", gap: 10 }}>
            {bullets.map((b, j) => (
              <li key={j} style={{ display: "flex", alignItems: "flex-start", gap: 12, fontSize: 15, lineHeight: 1.45, color: "#0A0A0A", minHeight: "calc(15px * 1.45 * 2)" }}>
                <svg width="16" height="16" viewBox="0 0 16 16" fill="none" style={{ flexShrink: 0, marginTop: 3 }} aria-hidden="true">
                  <path d="M3.5 8.5L6.5 11.5L12.5 5" stroke={accent} strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" />
                </svg>
                <span>{b}</span>
              </li>
            ))}
          </ul>
        )}
      </div>
    );
  });

  const grid = (
    <div className="process-grid" style={{
      display: "grid", gridTemplateColumns: `repeat(${n}, 1fr)`, gap: 20, marginTop: 56
    }}>
      {cards}
    </div>
  );

  const titleEl = title ? (
    <h2 style={{
      fontFamily: "var(--font-display)", fontWeight: 700,
      fontSize: "clamp(34px, 4.6vw, 60px)", lineHeight: 1.08,
      letterSpacing: "-0.025em", margin: 0, textAlign: "center",
      textWrap: "balance", maxWidth: 1100, marginInline: "auto"
    }}>{title}</h2>
  ) : null;

  if (pinned && !isMobile) {
    // Outer tall wrapper → sticky inner pinned to viewport center.
    // Total scroll length scales with card count so user has time to reveal each card.
    return (
      <div ref={wrapRef} style={{
        position: "relative",
        height: `${100 + n * 55}vh`
      }}>
        <div style={{
          position: "sticky", top: 0, height: "100vh",
          display: "flex", alignItems: "center", justifyContent: "center"
        }}>
          <div className="container" style={{ width: "100%" }}>
            {titleEl}
            {grid}
          </div>
        </div>
        <style>{`
          @media (max-width:1080px){ .process-grid{ grid-template-columns: repeat(2, 1fr) !important; } }
          @media (max-width:560px){ .process-grid{ grid-template-columns: 1fr !important; } }
        `}</style>
      </div>
    );
  }

  return (
    <div ref={wrapRef} className="container">
      {titleEl}
      {grid}
      <style>{`
        @media (max-width:1080px){ .process-grid{ grid-template-columns: repeat(2, 1fr) !important; } }
        @media (max-width:560px){ .process-grid{ grid-template-columns: 1fr !important; } }
      `}</style>
    </div>
  );
}

/* ============ MEDIA SUBPAGES ============ */

const MEDIA_DATA = {
  "media-economico": {
    handle: "@ilpuntoeconomico",
    title: "Il Punto Economico",
    hiboxBg: "#FFE2A8", hiboxText: "economia e attualità", hiboxColor: "#0A0A0A",
    accent: "#F0A30A", accentSoft: "#FFE2A8",
    img: "assets/media/card-economico.webp",
    glow: "assets/media/glow-yellow.webp",
    logo: "assets/media/logo-economico.webp",
    lead: "La community per chi vuole davvero capirne di più di economia, mercati e attualità, senza un linguaggio inutilmente complicato.",
    stats: [
    ["520k", "Community su Instagram"],
    ["165k", "Iscritti su YouTube"],
    ["2.5M", "Interazioni generate (Rolling 90 days)"]],

    topics: [
    { hl: "macroeconomia", body: "Tassi, inflazione, mercati e politica monetaria spiegati come servono davvero." },
    { hl: "geopolitica", body: "Le storie che muovono i prezzi: dal petrolio alle filiere, dal Mar Rosso ai chip." },
    { hl: "lavoro & finanza", body: "Stipendi, casa, investimenti, fiscalità. Niente promesse, solo numeri." }],

    formats: [
    ["Video YT 8–15'", "Long-form approfondito · 2 a settimana"],
    ["Reel & Short", "Daily news · 5 a settimana"],
    ["Caroselli IG", "Spiegazioni visual · 3 a settimana"],
    ["Newsletter", "Punto della settimana · ogni venerdì"]],

    richFormats: [
    {
      title: "Reel & Caroselli",
      body: "Pubblichiamo approfondimenti per fare il punto su economia e attualità. Partiamo dai dati, ma li rendiamo digeribili anche ai non addetti ai lavori.",
      kind: "posts", bg: "#FFE2A8",
      images: ["assets/economico/post-1.webp", "assets/economico/post-5.webp", "assets/economico/post-4.webp"]
    },
    {
      title: "Video documentari",
      body: "Creiamo documentari su YouTube per spiegare il mondo di oggi, quello di ieri e quello di domani.",
      kind: "videos", bg: "#a8e8ff",
      images: ["assets/economico/video-1.webp", "assets/economico/video-2.webp", "assets/economico/video-4.webp"]
    },
    {
      title: "Newsletter",
      body: "Arriviamo nella inbox di 75mila professionisti per spiegare 3x volte a settimana cosa sta succedendo nel mondo e perché ci dovrebbe interessare.",
      kind: "newsletter", bg: "#ffa8b5",
      images: ["assets/economico/newsletter-v2.webp"]
    }]

  },
  "media-techy": {
    handle: "@techy_ita",
    title: "Techy",
    hiboxBg: "#FFD6E8", hiboxText: "innovazione, tecnologia e AI", hiboxColor: "#0A0A0A",
    accent: "#FB037C", accentSoft: "#FFD6E8",
    img: "assets/media/card-techy.webp",
    glow: "assets/media/glow-pink.webp",
    logo: "assets/media/logo-techy.webp",
    lead: "La community per chi vuole capirne di più di tecnologia, AI e scienza. Spieghiamo come stanno cambiando le cose e perché.",
    stats: [
    ["460k", "Community su Instagram e TikTok"],
    ["15k", "Iscritti su YouTube"],
    ["1.5M", "Interazioni generate (Rolling 90 days)"]],

    topics: [
    { hl: "intelligenza artificiale", body: "Nuovi modelli, casi d'uso, limiti reali. Provati a mano, non sulla brochure." },
    { hl: "prodotti & founder", body: "Le aziende che stanno cambiando il software, dal SaaS B2B al consumer." },
    { hl: "tech policy", body: "AI Act, antitrust, chip, sovranità digitale. La regolazione che muove i mercati." }],

    formats: [
    ["Long-form YT", "Deep dive su prodotti e modelli · 1 a settimana"],
    ["Short / Reel", "News & demo · 4 a settimana"],
    ["Caroselli IG/LI", "Visual breakdown · 3 a settimana"],
    ["Podcast", "Interviste con founder · bi-settimanale"]],

    richFormats: [
    {
      title: "Reel & Caroselli",
      body: "Spieghiamo come la tecnologia, l’AI e la scienza stanno cambiando il presente e il futuro. Niente hype, solo divulgazione scientifica e tecnologica - come dovrebbe essere.",
      kind: "posts", bg: "#FFD6E8",
      images: ["assets/techy/post-1.webp", "assets/techy/post-2.webp"]
    },
    {
      title: "Video documentari",
      body: "Creiamo documentari dentro le aziende per mostrare la tecnologia a chi non l’ha mai vista da vicino - o a chi l’ha vista, ma vuole saperne di più.",
      kind: "videos", bg: "#E5E2FF",
      images: ["assets/techy/video-1.webp", "assets/techy/video-2.webp"]
    },
    {
      title: "Newsletter",
      body: "Arriviamo nell'inbox di 25mila professionisti per spiegare 3x volte a settimana come la tecnologia sta cambiando il presente e il futuro.",
      kind: "newsletter", bg: "#a8e8ff",
      images: ["assets/techy/newsletter.webp"]
    }]

  }
};

function RichFormatsSection({ d }) {
  return (
    <section style={{ background: "#F6F6F6", padding: "clamp(47px, 5.85vw, 91px) 0 clamp(72px, 9vw, 140px)", color: "#0A0A0A" }}>
      <div className="container">
        <h2 style={{
          fontFamily: "var(--font-display)", fontWeight: 700,
          fontSize: "clamp(34px, 4.6vw, 60px)", lineHeight: 1.08,
          letterSpacing: "-0.025em", margin: 0, textAlign: "center", color: "#0A0A0A",
          textWrap: "balance", maxWidth: 1100, marginInline: "auto"
        }}>
          <>I <HiBox bg={d.accent}>format</HiBox> che pubblichiamo</>
        </h2>
        <div className="rich-formats-grid" style={{
          display: "grid",
          gridTemplateColumns: "repeat(3, 1fr)",
          gap: "clamp(20px, 2vw, 28px)",
          marginTop: "clamp(48px, 5vw, 72px)"
        }}>
          {d.richFormats.map((f, i) =>
          <RichFormatCard key={i} f={f} accent={d.accent} />
          )}
        </div>
        <style>{`
          @media (max-width:980px){ .rich-formats-grid{ grid-template-columns: 1fr !important; max-width: 480px; margin-inline: auto; } }
        `}</style>
      </div>
    </section>);

}


function RichFormatCard({ f, accent }) {
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 24 }}>
      {/* visual canvas — same aspect for all 3 cards */}
      <div style={{
        position: "relative", width: "100%", aspectRatio: "4/5",
        background: f.bg, borderRadius: 22, overflow: "hidden"
      }}>
        {f.kind === "posts" && <PostsCollage images={f.images} />}
        {f.kind === "videos" && <VideosCollage images={f.images} />}
        {f.kind === "newsletter" && <NewsletterCollage image={f.images[0]} accent={accent} />}
      </div>
      {/* title + body below the canvas */}
      <div style={{ paddingInline: 4 }}>
        <div style={{
          fontFamily: "var(--font-display)", fontWeight: 700,
          fontSize: "clamp(22px, 2vw, 28px)", letterSpacing: "-0.02em",
          color: "#0A0A0A", marginBottom: 10, textAlign: "center"
        }}>{f.title}</div>
        <p style={{
          margin: 0, fontSize: "clamp(14px, 1vw, 15px)", lineHeight: 1.55,
          color: "#4A4A4A", textAlign: "center", maxWidth: 360, marginInline: "auto"
        }}>{f.body}</p>
      </div>
    </div>);

}

function PostsCollage({ images }) {
  // Two portrait posts overlapping with slight rotation
  return (
    <div style={{ position: "absolute", inset: 0 }}>
      <img src={images[0]} alt="" style={{
        position: "absolute", left: "8%", top: "10%", width: "55%", height: "auto",
        borderRadius: 10, boxShadow: "0 20px 40px rgba(0,0,0,0.18)",
        transform: "rotate(-6deg)"
      }} />
      <img src={images[1]} alt="" style={{
        position: "absolute", right: "6%", bottom: "8%", width: "55%", height: "auto",
        borderRadius: 10, boxShadow: "0 20px 40px rgba(0,0,0,0.22)",
        transform: "rotate(5deg)"
      }} />
    </div>);

}

function VideosCollage({ images }) {
  // With 2 images: smaller, overlapping diagonally, fully inside the card.
  // With 3 images: original stacked layout.
  if (!images[2]) {
    return (
      <div style={{ position: "absolute", inset: 0 }}>
        <img src={images[0]} alt="" style={{
          position: "absolute", left: "10%", top: "8%", width: "52%", height: "auto",
          borderRadius: 10, boxShadow: "0 20px 40px rgba(0,0,0,0.22)",
          transform: "rotate(-6deg)"
        }} />
        <img src={images[1]} alt="" style={{
          position: "absolute", right: "8%", bottom: "8%", width: "52%", height: "auto",
          borderRadius: 10, boxShadow: "0 20px 40px rgba(0,0,0,0.22)",
          transform: "rotate(5deg)"
        }} />
      </div>);

  }
  return (
    <div style={{ position: "absolute", inset: 0 }}>
      <img src={images[0]} alt="" style={{
        position: "absolute", left: "6%", top: "12%", width: "78%", height: "auto",
        borderRadius: 8, boxShadow: "0 16px 32px rgba(0,0,0,0.20)",
        transform: "rotate(-5deg)"
      }} />
      <img src={images[1]} alt="" style={{
        position: "absolute", right: "4%", top: "44%", width: "76%", height: "auto",
        borderRadius: 8, boxShadow: "0 16px 32px rgba(0,0,0,0.22)",
        transform: "rotate(4deg)"
      }} />
      <img src={images[2]} alt="" style={{
        position: "absolute", left: "10%", bottom: "6%", width: "78%", height: "auto",
        borderRadius: 8, boxShadow: "0 18px 36px rgba(0,0,0,0.22)",
        transform: "rotate(-2deg)"
      }} />
    </div>);

}

function NewsletterCollage({ image, accent }) {
  // Phone mockup with floating badges baked into PNG.
  // Image is landscape (~1.15:1) inside a portrait 4/5 card —
  // scale by height so the phone fills vertically; horizontal overflow is fine.
  return (
    <div style={{
      position: "absolute", inset: 0, display: "flex",
      alignItems: "center", justifyContent: "center"
    }}>
      <img src={image} alt="" style={{
        height: "75%", width: "auto", maxWidth: "none",
        objectFit: "contain",
        filter: "drop-shadow(0 24px 36px rgba(0,0,0,0.18))"
      }} />
    </div>);

}


function MediaScrollColumns({ slug }) {
  // Two columns of images scrolling vertically, infinite loop, paused on hover.
  // Same set repeated 2x in DOM for seamless wrap.
  const SETS = {
    "media-techy": {
      a: [
      "assets/techy/marquee/t1.webp",
      "assets/techy/marquee/t5.webp",
      "assets/techy/marquee/t3.webp",
      "assets/techy/marquee/t8.webp",
      "assets/techy/marquee/t11.webp",
      "assets/techy/marquee/t13.webp",
      "assets/techy/marquee/t14.webp"],

      b: [
      "assets/techy/marquee/t2.webp",
      "assets/techy/marquee/t6.webp",
      "assets/techy/marquee/t4.webp",
      "assets/techy/marquee/t9.webp",
      "assets/techy/marquee/t7.webp",
      "assets/techy/marquee/t10.webp",
      "assets/techy/marquee/t12.webp"]

    },
    default: {
      a: [
      "assets/media/marquee/m1.webp",
      "assets/media/marquee/m5.webp",
      "assets/media/marquee/m3.webp",
      "assets/media/marquee/m8.webp",
      "assets/media/marquee/m11.webp",
      "assets/media/marquee/m13.webp"],

      b: [
      "assets/media/marquee/m2.webp",
      "assets/media/marquee/m6.webp",
      "assets/media/marquee/m4.webp",
      "assets/media/marquee/m14.webp",
      "assets/media/marquee/m9.webp",
      "assets/media/marquee/m12.webp"]

    }
  };
  const set = SETS[slug] || SETS.default;
  const colA = set.a;
  const colB = set.b;

  return (
    <div className="msc-wrap" aria-hidden="true">
      <div className="msc-cols">
        <div className="msc-col msc-col-a">
          <div className="msc-track">
            {[...colA, ...colA].map((src, i) =>
            <img key={`a-${i}`} src={src} alt="" loading="lazy" />
            )}
          </div>
        </div>
        <div className="msc-col msc-col-b">
          <div className="msc-track">
            {[...colB, ...colB].map((src, i) =>
            <img key={`b-${i}`} src={src} alt="" loading="lazy" />
            )}
          </div>
        </div>
      </div>
      {/* gradient fades top and bottom */}
      <div className="msc-fade msc-fade-top" />
      <div className="msc-fade msc-fade-bottom" />

      <style>{`
        .msc-wrap{
          position: relative;
          width: 100%;
          height: clamp(460px, 56vw, 640px);
          overflow: hidden;
        }
        .msc-cols{
          position: absolute; inset: 0;
          display: grid;
          grid-template-columns: 1fr 1fr;
          gap: 12px;
        }
        .msc-col{
          position: relative;
          overflow: hidden;
        }
        /* Column A starts at the top, B starts ~200px lower so the two columns
           are never aligned horizontally — staggered, asymmetric composition. */
        .msc-col-a .msc-track{ animation: msc-scroll 38s linear infinite; }
        .msc-col-b .msc-track{ animation: msc-scroll-b 38s linear infinite; }
        .msc-track{
          display: flex;
          flex-direction: column;
          gap: 12px;
          will-change: transform;
        }
        .msc-track img{
          width: 100%;
          height: auto;
          display: block;
          border-radius: 12px;
          object-fit: cover;
        }
        /* pause both columns on hover anywhere in the component */
        .msc-wrap:hover .msc-track{ animation-play-state: paused; }

        /* Seamless loop: track holds set twice; translate -50% lands us back at start. */
        @keyframes msc-scroll {
          from { transform: translateY(0); }
          to   { transform: translateY(-50%); }
        }
        /* Column B is offset by +200px throughout, but starts mid-cycle so the
           tail of the duplicated set fills the top — no white gap on load. */
        @keyframes msc-scroll-b {
          from { transform: translateY(calc(-50% + 200px)); }
          to   { transform: translateY(calc(-100% + 200px)); }
        }

        .msc-fade{
          position: absolute; left: 0; right: 0;
          height: 80px;
          pointer-events: none;
          z-index: 2;
        }
        .msc-fade-top{
          top: 0;
          background: linear-gradient(to bottom, #fff 0%, rgba(255,255,255,0) 100%);
        }
        .msc-fade-bottom{
          bottom: 0;
          background: linear-gradient(to top, #fff 0%, rgba(255,255,255,0) 100%);
        }
        @media (prefers-reduced-motion: reduce){
          .msc-track{ animation: none !important; }
        }
      `}</style>
    </div>);

}


function MediaSubPage({ slug, navigate }) {
  const d = MEDIA_DATA[slug];
  const [kitOpen, setKitOpen] = React.useState(false);
  if (!d) return null;
  const KIT_CONFIG = {
    "media-economico": { url: "https://canva.link/osu8vlpc4z9ggw6", title: "Scarica il Media Kit de Il Punto Economico", accent: "#E8442A" },
    "media-techy":     { url: "https://canva.link/lhs1kkvjps7hntg", title: "Scarica il Media Kit di Techy",            accent: "#FB037C" }
  };
  const kit = KIT_CONFIG[slug];
  return (
    <main>
      {/* HERO */}
      <section style={{ background: "#fff", padding: "clamp(56px, 7vw, 100px) 0 clamp(40px, 5vw, 80px)" }}>
        <div className="container">
          <div className="media-sub-hero" style={{
            display: "grid", gridTemplateColumns: "1fr 1fr",
            gap: "clamp(32px, 5vw, 80px)", alignItems: "center"
          }}>
            <div>
              <div style={{
                display: "inline-flex", alignItems: "center", gap: 12,
                marginBottom: 24
              }}>
                <img src={d.logo} alt="" style={{ width: 48, height: 48, borderRadius: 999 }} />
                <span style={{
                  fontFamily: "var(--font-display)", fontWeight: 700,
                  fontSize: "clamp(15px, 1.1vw, 17px)", color: "#0A0A0A"
                }}>{d.handle}</span>
              </div>
              <h1 style={{
                fontFamily: "var(--font-display)", fontWeight: 700,
                fontSize: "clamp(40px, 5vw, 76px)", lineHeight: 1.05,
                letterSpacing: "-0.03em", margin: 0
              }}>
                {d.title}
              </h1>
              <p style={{
                marginTop: 24, fontSize: "clamp(15px, 1.15vw, 18px)",
                lineHeight: 1.55, color: "#0A0A0A", opacity: 0.78,
                maxWidth: 540
              }}>
                {d.lead}
              </p>
              <div style={{ display: "flex", gap: 14, marginTop: 32, flexWrap: "wrap" }}>
                <a href="#" onClick={(e) => { e.preventDefault(); if (kit) setKitOpen(true); }} style={ctaPill(d.accent)}>
                  Scarica il Media Kit <ArrowRight />
                </a>
                <a href="#contatti" onClick={(e) => {e.preventDefault();navigate("contatti");}} style={
                  { ...ctaPill("#0A0A0A"), background: "transparent", color: "#0A0A0A", border: "1.5px solid #0A0A0A" }
                }>
                  Collabora con noi <ArrowRight />
                </a>
              </div>
            </div>
            <MediaScrollColumns slug={slug} />

          </div>
        </div>
        <style>{`@media (max-width:880px){ .media-sub-hero{ grid-template-columns: 1fr !important; } }`}</style>
      </section>

      {/* NUMBERS */}
      <section style={{ background: "#f6f6f6", padding: "clamp(64px, 8vw, 120px) 0 clamp(42px, 5.2vw, 78px)" }}>
        <div className="container">
          <h2 style={{
            fontFamily: "var(--font-display)", fontWeight: 700,
            fontSize: "clamp(34px, 4.6vw, 60px)", lineHeight: 1.08,
            letterSpacing: "-0.025em", margin: 0, textAlign: "center",
            textWrap: "balance", maxWidth: 1100, marginInline: "auto"
          }}>
            {d.title === "Techy" ? (
              <>Ogni mese 🥳 raggiungiamo <HiBox bg={d.accent}>10 milioni di persone</HiBox> 📲</>
            ) : (
              <>Ogni mese 🥳 raggiungiamo <HiBox bg={d.accent}>15 milioni di persone</HiBox> 📲</>
            )}
          </h2>
          <div style={{
            display: "grid", gridTemplateColumns: "repeat(3, 1fr)",
            marginTop: 80, alignItems: "start"
          }} className="sub-numbers">
            {d.stats.map(([v, lbl], i) =>
            <PageNumberStat key={i} value={v} desc={lbl} divider={i > 0} accentColor={d.accent} />
            )}
          </div>
          <style>{`@media (max-width:880px){ .sub-numbers{ grid-template-columns: 1fr !important; gap: 56px; } .sub-numbers > *{ border-left: 0 !important; } }`}</style>
        </div>
      </section>

      {/* FORMAT */}
      {d.richFormats ?
      <RichFormatsSection d={d} /> :

      <section style={{ background: "#f6f6f6", padding: "clamp(42px, 5.2vw, 78px) 0 clamp(64px, 8vw, 120px)" }}>
          <div className="container">
            <h2 style={{
            fontFamily: "var(--font-display)", fontWeight: 700,
            fontSize: "clamp(34px, 4.6vw, 60px)", lineHeight: 1.08,
            letterSpacing: "-0.025em", margin: 0, textAlign: "center",
            textWrap: "balance", maxWidth: 1100, marginInline: "auto"
          }}>
              I <HiBox bg={d.accent}>format</HiBox> che pubblichiamo
            </h2>
            <div className="formats-grid" style={{
            display: "grid", gridTemplateColumns: "repeat(2, 1fr)", gap: 16,
            marginTop: 72, maxWidth: 920, marginInline: "auto"
          }}>
              {d.formats.map(([title, body], i) =>
            <div key={i} style={{
              background: "#fff", borderRadius: 14,
              padding: "24px 28px",
              display: "flex", flexDirection: "column", gap: 6
            }}>
                  <div style={{
                fontFamily: "var(--font-display)", fontWeight: 700,
                fontSize: 19, letterSpacing: "-0.015em", color: "#0A0A0A"
              }}>{title}</div>
                  <div style={{ fontSize: 14, color: "#4A4A4A", lineHeight: 1.5 }}>{body}</div>
                </div>
            )}
            </div>
            <style>{`@media (max-width:720px){ .formats-grid{ grid-template-columns: 1fr !important; } }`}</style>
          </div>
        </section>
      }

      {/* CASE STUDIES */}
      {(slug === "media-economico" || slug === "media-techy") && <CaseStudiesAllVariants accent={d.accent} slug={slug} />}

      <CTASplit navigate={navigate} />
      {kit && kitOpen && <MediaKitModal onClose={() => setKitOpen(false)} url={kit.url} title={kit.title} accent={kit.accent} />}
    </main>);

}


/* ============ AGENCY SUBPAGES ============ */

const AGENCY_DATA = {
  "agency-yt": {
    kicker: "Servizio Agency",
    titleBefore: <>Gestiamo il canale YouTube<br /></>,
    hiboxBg: "#3B5BFF", hiboxText: "del tuo brand",
    titleAfter: "",
    accent: "#3B5BFF", accentSoft: "#DDE9FB",
    img: "assets/Card-YT.webp",
    lead: "Produciamo e gestiamo canali YouTube in white label per aziende, per posizionarle come autorità nel proprio settore. Il tuo brand, la nostra capacità di creazione di contenuti.",
    numbersTitle: <>Rendiamo <HiBox bg="#3B5BFF">YouTube</HiBox> la casa del tuo brand</>,
    stats: [
    ["3+", "Canali YouTube gestiti"],
    ["200+", "Long + Clip prodotti per i nostri clienti ogni anno"],
    ["1.2M", "visualizzazioni generate nell'ultimo anno per i nostri clienti YT"]],

    process: [
    ["01", "Strategy", "Mappiamo il tuo posizionamento, troviamo i topic che la tua audience cerca davvero.",
    ["Analisi del canale e dei competitor", "Piano editoriale trimestrale", "Definizione del posizionamento"]],
    ["02", "Scripting", "Scriviamo gli script con il tono giusto e la struttura che funziona su YouTube.",
    ["Ricerca approfondita delle fonti", "Script completo con hook e struttura narrativa", "Revisione e fact-checking"]],
    ["03", "Production", "Registriamo, montiamo e produciamo le copertine. Standard da media digitale.",
    ["Registrazione in studio professionale", "Editing, post-produzione e sound design", "Copertine in A/B Testing e ottimizzate per CTR"]],
    ["04", "SEO & Analytics", "Pubblichiamo, ottimizziamo SEO e consegniamo un report mensile con cosa funziona.",
    ["Ottimizzazione titolo, descrizione e tag", "Pubblicazione e scheduling", "Report mensile con analytics"]]],

    includes: [
    "Topic mining mensile",
    "Scripting & casting interno",
    "Registrazione in studio o on-location",
    "Editing, copertine, SEO",
    "Analytics & reporting mensile",
    "Strategia di crescita continua"]

  },
  "agency-shortform": {
    kicker: "Servizio Agency",
    titleBefore: <>Creiamo UGC<br />per il tuo brand<br /></>,
    hiboxBg: "#7A4DFF", hiboxText: "che convertono",
    titleAfter: "",
    accent: "#7A4DFF", accentSoft: "#E5E2FF",
    img: "assets/Card-UGC.webp",
    heroImgMax: 720,
    lead: "Reels, TikTok e Shorts pensati per fermare lo scroll. Hook che funzionano, scripting diretto, casting di creator UGC e consegna in 72h. In organico o per advertising su Meta e YouTube.",
    numbersTitle: <>Trasformiamo <HiBox bg="#7A4DFF">3 secondi</HiBox> in conversioni</>,
    stats: [
    [<>100<span style={{ color: "#7A4DFF" }}>+</span></>, "Numero di UGC prodotti per i brand"],
    [<>2,3<span style={{ color: "#7A4DFF" }}>x</span></>, "ROAS medio generato in paid"],
    [<>72<span style={{ color: "#7A4DFF" }}>h</span></>, "Tempo medio di consegna per ogni variante creativa"]],

    process: [
    ["01", "Hook design", "Catturiamo l'attenzione nei primi 3 secondi del video e sperimentiamo con varianti.",
    ["Benchmarking sui top performer della nicchia", "Definizione di 3-5 angoli narrativi", "Briefing creativo condiviso"]],
    ["02", "Scripting", "Realizziamo script che sono veloci e dinamici, per tenere alta la retention del video.",
    ["Script da 30-60 secondi con hook, build-up e CTA", "Tone of voice allineato al brand", "Revisione e fact-checking"]],
    ["03", "Cast + Shooting", "Selezioniamo creator dal nostro network e produciamo in 72h.",
    ["Casting da network proprietario", "Riprese in studio, esterno o remote", "Direzione creativa inclusa"]],
    ["04", "Editing & A/B", "Tagli aggressivi, sottotitoli, sound design. Più varianti per testare in adv.",
    ["Editing rapido con sottotitoli", "Più varianti di hook per testing", "Reporting su hook rate, CTR, ROAS"]]],

    includes: [
    "Hook & scripting basati sulla tua nicchia",
    "Casting UGC dal nostro network",
    "Riprese in studio, esterno o remote",
    "Editing rapido + sottotitoli + grafica",
    "A/B testing creativi",
    "Reporting su CTR, ROAS, hook rate"]

  },
  "agency-social": {
    kicker: "Servizio Agency",
    titleBefore: <>Gestiamo i social<br />del tuo brand </>,
    hiboxBg: "#FF6B9E", hiboxText: "end-to-end",
    titleAfter: "",
    accent: "#FF6B9E", accentSoft: "#FFD6E8",
    img: "assets/Card-SMM.webp",
    lead: "Gestiamo la presenza social delle aziende su Instagram, LinkedIn e TikTok. Una redazione esterna, dentro al tuo brand: dalla strategia alla pubblicazione, dal copy al reporting.",
    numbersTitle: <>Diventiamo la tua <HiBox bg="#FF6B9E">redazione social</HiBox> interna</>,
    stats: [
    [<><span style={{ color: "#FF6B9E" }}>+</span>55%</>, "Engagement medio generato vs baseline"],
    [<>30<span style={{ color: "#FF6B9E" }}>+</span></>, "Contenuti organici pubblicati ogni mese per i nostri clienti"],
    [<>3<span style={{ color: "#FF6B9E" }}>+</span></>, "Piattaforme social gestite in parallelo"]],

    process: [
    ["01", "PED mensile", "Piano editoriale costruito su obiettivi e calendario commerciale del cliente.",
    ["Analisi competitor e baseline", "Calendario editoriale mensile", "Definizione dei pillar di contenuto"]],
    ["02", "Produzione", "Post, caroselli, reel, copy. Tutto in linea con il tone of voice del brand.",
    ["Ricerca editoriale e controllo delle fonti", "Redazione in grafica dei contenuti definitivi", "Branding coerente con le guidelines definite"]],
    ["03", "Programmazione", "Pubblicazione su IG, LinkedIn e TikTok con orari ottimizzati per piattaforma.",
    ["Scheduling multi-piattaforma", "Ottimizzazione per fascia oraria", "Community management\nsui canali social"]],
    ["04", "Reporting", "Reach, engagement, saved, shared. KPI chiari, niente vanity metric.",
    ["Dashboard mensile con KPI condivisi", "Analisi dei top performer della tua nicchia", "Iterazione del piano editoriale"]]],

    includes: [
    "Strategia editoriale mensile (PED)",
    "Copy + visual + caroselli",
    "Reel verticali + tagli da long-form",
    "Programmazione su IG, LinkedIn, TikTok",
    "Community management base",
    "Reporting mensile su KPI condivisi"]

  }
};

function AgencySubPage({ slug, navigate }) {
  const d = AGENCY_DATA[slug];
  if (!d) return null;
  return (
    <main>
      {/* HERO */}
      <section style={{ background: "#fff", padding: "clamp(56px, 7vw, 100px) 0 clamp(40px, 5vw, 80px)" }}>
        <div className="container">
          <div className="agency-sub-hero" style={{
            display: "grid", gridTemplateColumns: "1.05fr 1fr",
            gap: "clamp(32px, 5vw, 80px)", alignItems: "center"
          }}>
            <div>
              <div style={{
                fontFamily: "var(--font-mono)", fontSize: 12,
                letterSpacing: "0.18em", color: "#8A8A8A",
                textTransform: "uppercase", marginBottom: 24
              }}>{d.kicker}</div>
              <h1 style={{
                fontFamily: "var(--font-display)", fontWeight: 700,
                fontSize: "clamp(40px, 5vw, 76px)", lineHeight: 1.05,
                letterSpacing: "-0.03em", margin: 0
              }}>
                {d.titleBefore}
                <HiBox bg={d.hiboxBg}>{d.hiboxText}</HiBox>
                {d.titleAfter}
              </h1>
              <p style={{
                marginTop: 24, fontSize: "clamp(15px, 1.15vw, 18px)",
                lineHeight: 1.55, color: "#0A0A0A", opacity: 0.78,
                maxWidth: 560
              }}>
                {d.lead}
              </p>
              <div style={{ display: "flex", gap: 14, marginTop: 32, flexWrap: "wrap" }}>
                <a href="#contatti" onClick={(e) => {e.preventDefault();navigate("contatti");}} style={ctaPill(d.accent)}>
                  Prenota una call <ArrowRight />
                </a>
                <a href="#casi" onClick={(e) => {e.preventDefault();navigate("casi");}} style={{
                  ...ctaPill("#0A0A0A"), background: "transparent", color: "#0A0A0A",
                  border: "1.5px solid #0A0A0A"
                }}>
                  Vedi i casi studio <ArrowRight />
                </a>
              </div>
            </div>
            <div style={{ display: "flex", alignItems: "center", justifyContent: "center" }}>
              <img src={d.img} alt="" style={{ width: "100%", maxWidth: d.heroImgMax || 560, height: "auto" }} />
            </div>
          </div>
        </div>
        <style>{`@media (max-width:880px){ .agency-sub-hero{ grid-template-columns: 1fr !important; } }`}</style>
      </section>

      {/* NUMBERS */}
      <section style={{ background: "#f6f6f6", padding: "clamp(64px, 8vw, 120px) 0" }}>
        <div className="container">
          <h2 style={{
            fontFamily: "var(--font-display)", fontWeight: 700,
            fontSize: "clamp(34px, 4.6vw, 60px)", lineHeight: 1.08,
            letterSpacing: "-0.025em", margin: 0, textAlign: "center",
            textWrap: "balance", maxWidth: 1100, marginInline: "auto"
          }}>
            {d.numbersTitle ? d.numbersTitle : (<><HiBox bg={d.accent}>Numeri</HiBox>, non vibe.</>)}
          </h2>
          <div style={{
            display: "grid", gridTemplateColumns: "repeat(3, 1fr)",
            marginTop: 80, alignItems: "start"
          }} className="agency-numbers">
            {d.stats.map(([v, lbl], i) =>
            <PageNumberStat key={i} value={v} desc={lbl} divider={i > 0} />
            )}
          </div>
          <style>{`@media (max-width:880px){ .agency-numbers{ grid-template-columns: 1fr !important; gap: 56px; } .agency-numbers > *{ border-left: 0 !important; } }`}</style>
        </div>
      </section>

      {/* PROCESS */}
      <section className="agency-process" style={{ background: "#fff", padding: d.process.some((it) => Array.isArray(it[3]) && it[3].length > 0) ? "0" : "clamp(64px, 8vw, 120px) 0" }}>
        <ProcessGrid items={d.process} accent={d.accent} title={<>Come <HiBox bg={d.accent}>lavoriamo</HiBox></>} />
        <style>{`@media (max-width:880px){ .agency-process{ padding: clamp(56px, 10vw, 88px) 0 !important; } }`}</style>
      </section>

      {/* CASE STUDIES */}
      <CaseStudiesAllVariants accent={d.accent} slug={slug} />

      <CTASplit navigate={navigate} />
    </main>);

}

/* ============ MEDIA KIT MODAL (Il Punto Economico / Techy) ============ */
function MediaKitModal({ onClose, url, title, accent }) {
  const KIT_URL = url;
  const ACCENT = accent || "#E8442A";
  const TITLE = title || "Scarica il Media Kit";
  const [values, setValues] = React.useState({ name: "", email: "", site: "", role: "" });
  const [errors, setErrors] = React.useState({});
  const [submitted, setSubmitted] = React.useState(false);

  React.useEffect(() => {
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    document.addEventListener("keydown", onKey);
    const prevOverflow = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    return () => {
      document.removeEventListener("keydown", onKey);
      document.body.style.overflow = prevOverflow;
    };
  }, [onClose]);

  React.useEffect(() => {
    if (!submitted) return;
    const t = setTimeout(onClose, 3000);
    return () => clearTimeout(t);
  }, [submitted, onClose]);

  const set = (k) => (e) => {
    setValues((v) => ({ ...v, [k]: e.target.value }));
    setErrors((er) => ({ ...er, [k]: undefined }));
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    const newErr = {};
    if (!values.name.trim()) newErr.name = "Inserisci nome e cognome";
    if (!values.email.trim()) newErr.email = "Inserisci la tua email aziendale";
    else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(values.email)) newErr.email = "Email non valida";
    if (!values.site.trim()) newErr.site = "Inserisci il sito web aziendale";
    if (Object.keys(newErr).length) { setErrors(newErr); return; }
    window.open(KIT_URL, "_blank", "noopener,noreferrer");
    setSubmitted(true);
  };

  const labelStyle = { fontSize: 13, fontWeight: 700, letterSpacing: "0.02em", textTransform: "uppercase", color: "#8A8A8A", display: "block", marginBottom: 8 };
  const inputBase = {
    width: "100%", padding: "13px 15px", borderRadius: 12,
    border: "1.5px solid #DCD8D0", background: "#fff",
    fontFamily: "inherit", fontSize: 15, outline: "none", boxSizing: "border-box"
  };

  return (
    <div role="dialog" aria-modal="true" aria-labelledby="mk-title"
      onMouseDown={(e) => { if (e.target === e.currentTarget) onClose(); }}
      style={{
        position: "fixed", inset: 0, zIndex: 9999,
        background: "rgba(10,10,10,0.55)",
        display: "flex", alignItems: "center", justifyContent: "center",
        padding: 20, animation: "mk-fade 180ms ease-out"
      }}>
      <div style={{
        position: "relative", width: "100%", maxWidth: 480,
        background: "#fff", borderRadius: 16, padding: "clamp(28px, 4vw, 40px)",
        boxShadow: "0 30px 80px rgba(10,10,10,0.35)",
        animation: "mk-pop 220ms cubic-bezier(.2,.8,.2,1)"
      }}>
        <button aria-label="Chiudi" onClick={onClose} style={{
          position: "absolute", top: 14, right: 14,
          width: 36, height: 36, borderRadius: 999,
          border: 0, background: "#F2F0EB", color: "#0A0A0A",
          cursor: "pointer", display: "inline-flex", alignItems: "center", justifyContent: "center",
          transition: "background 160ms"
        }}
          onMouseEnter={(e) => e.currentTarget.style.background = "#E6E3DD"}
          onMouseLeave={(e) => e.currentTarget.style.background = "#F2F0EB"}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round"><path d="M6 6l12 12M18 6L6 18" /></svg>
        </button>

        {!submitted ? (
          <>
            <h3 id="mk-title" style={{
              margin: 0, fontFamily: "var(--font-display)", fontWeight: 700,
              fontSize: "clamp(22px, 2.2vw, 28px)", lineHeight: 1.15,
              letterSpacing: "-0.02em", color: "#0A0A0A", paddingRight: 32
            }}>
              {TITLE}
            </h3>
            <p style={{ margin: "10px 0 24px", color: "#7A766E", fontSize: 15, lineHeight: 1.45 }}>
              Inserisci i tuoi dati e riceverai il link
            </p>
            <form onSubmit={handleSubmit} style={{ display: "flex", flexDirection: "column", gap: 16 }} noValidate>
              <div>
                <label style={labelStyle}>Nome e cognome<span style={{ color: ACCENT }}> *</span></label>
                <input type="text" value={values.name} onChange={set("name")} autoComplete="name"
                  style={{ ...inputBase, borderColor: errors.name ? ACCENT : "#DCD8D0" }}
                  onFocus={(e) => e.target.style.borderColor = ACCENT}
                  onBlur={(e) => e.target.style.borderColor = errors.name ? ACCENT : "#DCD8D0"} />
                {errors.name && <div style={{ marginTop: 6, fontSize: 13, color: ACCENT, fontWeight: 600 }}>{errors.name}</div>}
              </div>
              <div>
                <label style={labelStyle}>Email aziendale<span style={{ color: ACCENT }}> *</span></label>
                <input type="email" value={values.email} onChange={set("email")} autoComplete="email"
                  style={{ ...inputBase, borderColor: errors.email ? ACCENT : "#DCD8D0" }}
                  onFocus={(e) => e.target.style.borderColor = ACCENT}
                  onBlur={(e) => e.target.style.borderColor = errors.email ? ACCENT : "#DCD8D0"} />
                {errors.email && <div style={{ marginTop: 6, fontSize: 13, color: ACCENT, fontWeight: 600 }}>{errors.email}</div>}
              </div>
              <div>
                <label style={labelStyle}>Sito web aziendale<span style={{ color: ACCENT }}> *</span></label>
                <input type="text" value={values.site} onChange={set("site")} autoComplete="url" placeholder="www.azienda.com"
                  style={{ ...inputBase, borderColor: errors.site ? ACCENT : "#DCD8D0" }}
                  onFocus={(e) => e.target.style.borderColor = ACCENT}
                  onBlur={(e) => e.target.style.borderColor = errors.site ? ACCENT : "#DCD8D0"} />
                {errors.site && <div style={{ marginTop: 6, fontSize: 13, color: ACCENT, fontWeight: 600 }}>{errors.site}</div>}
              </div>
              <div>
                <label style={labelStyle}>Ruolo</label>
                <input type="text" value={values.role} onChange={set("role")} autoComplete="organization-title"
                  style={inputBase}
                  onFocus={(e) => e.target.style.borderColor = ACCENT}
                  onBlur={(e) => e.target.style.borderColor = "#DCD8D0"} />
              </div>
              <button type="submit" style={{
                marginTop: 10, width: "100%",
                background: ACCENT, color: "#fff", border: 0,
                fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 16,
                padding: "16px 22px", borderRadius: 50, cursor: "pointer",
                display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 10,
                transition: "transform 180ms ease, filter 180ms ease"
              }}
                onMouseEnter={(e) => { e.currentTarget.style.filter = "brightness(1.06)"; e.currentTarget.style.transform = "translateY(-1px)"; }}
                onMouseLeave={(e) => { e.currentTarget.style.filter = "none"; e.currentTarget.style.transform = "none"; }}>
                Scarica ora <ArrowRight />
              </button>
            </form>
          </>
        ) : (
          <div style={{ padding: "16px 4px 8px", textAlign: "center" }}>
            <div style={{
              width: 64, height: 64, borderRadius: 999, background: "#E6F4EC",
              display: "inline-flex", alignItems: "center", justifyContent: "center",
              marginBottom: 18
            }}>
              <svg width="30" height="30" viewBox="0 0 24 24" fill="none" stroke="#1E9D5F" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round">
                <path d="M5 12.5l4.5 4.5L19 7.5" />
              </svg>
            </div>
            <h3 style={{
              margin: 0, fontFamily: "var(--font-display)", fontWeight: 700,
              fontSize: "clamp(20px, 2vw, 24px)", lineHeight: 1.2,
              letterSpacing: "-0.02em", color: "#0A0A0A"
            }}>
              Ottimo!
            </h3>
            <p style={{ margin: "10px 0 4px", color: "#4A4A4A", fontSize: 15, lineHeight: 1.5 }}>
              Il Media Kit si sta aprendo in una nuova scheda.
            </p>
            <p style={{ marginTop: 14, fontSize: 13, color: "#8A8A8A" }}>
              Non si è aperto?{" "}
              <a href={KIT_URL} target="_blank" rel="noopener noreferrer" style={{ color: ACCENT, fontWeight: 700 }}>Clicca qui</a>
            </p>
          </div>
        )}
      </div>
      <style>{`
        @keyframes mk-fade { from { opacity: 0 } to { opacity: 1 } }
        @keyframes mk-pop { from { opacity: 0; transform: translateY(8px) scale(0.985) } to { opacity: 1; transform: none } }
      `}</style>
    </div>);
}

Object.assign(window, { MediaSubPage, AgencySubPage, MediaKitModal });