// ═══════════════════════════════════════════════════════════════
// SECCIÓN — INMENSO BASTARDO
// Cuadernos de épicas. Estética: MANUSCRITO CAÓTICO (Godard).
// Fondo papel manchado, anotaciones a mano rojas, tachaduras,
// notas al margen desordenadas.
// ═══════════════════════════════════════════════════════════════

// Runtime enrichment — attach poster + related to each IB cap.
// Remove once gen-data.mjs is re-run so data.jsx ships these fields natively.
(function enrichIB() {
  const IB_POSTER_MAP = {
    '1915-nacimiento-nacion':  '/fotogramas/nacimiento-nacion-poster.jpg',
    '1939-gone-with-the-wind': '/fotogramas/gone-with-the-wind-poster.jpg',
    '1954-seven-samurai':      '/fotogramas/seven-samurai-poster.jpg',
    '1956-diez-mandamientos':  '/fotogramas/diez-mandamientos-poster.jpg',
    '1959-ben-hur':            '/fotogramas/ben-hur-poster.jpg',
    '1960-spartacus':          '/fotogramas/spartacus-poster.jpg',
    '1962-lawrence-arabia':    '/fotogramas/lawrence-arabia-poster.jpg',
    '1963-cleopatra':          '/fotogramas/cleopatra-poster.jpg',
    '1974-celine-julie':       '/fotogramas/celine-julie-poster.jpg',
    '1974-padrino-parte-ii':   '/fotogramas/padrino-parte-ii-poster.jpg',
    '1975-barry-lyndon':       '/fotogramas/barry-lyndon-poster.jpg',
    '1979-apocalypse-now':     '/fotogramas/apocalypse-now-poster.jpg',
    '1980-heavens-gate':       '/fotogramas/heavens-gate-poster.jpg',
  };
  // General poster map (by critica slug) — for related films.
  const CRITICA_POSTER_MAP = Object.assign({}, IB_POSTER_MAP, {
    '2000-nueve-reinas':        '/fotogramas/nueve-reinas-poster.jpg',
    '2020-druk':                '/fotogramas/druk-poster.jpg',
    '2020-news-of-the-world':   '/fotogramas/news-of-the-world-poster.jpg',
    '2021-french-dispatch':     '/fotogramas/french-dispatch-poster.jpg',
    '2021-mitchells-vs-machines':'/fotogramas/mitchells-poster.jpg',
    '2021-snyder-cut':          '/fotogramas/snyder-cut-poster.jpg',
    '2022-fabelmans':           '/fotogramas/fabelmans-poster.jpg',
    '2022-hustle':              '/fotogramas/hustle-poster.jpg',
    '2023-oppenheimer':         '/fotogramas/oppenheimer-poster.jpg',
    '2023-retirement-plan':     '/fotogramas/retirement-plan-poster.jpg',
    '2024-civil-war':           '/fotogramas/civil-war-poster.jpg',
    '1971-naranja-mecanica':    '/fotogramas/naranja-mecanica-poster.jpg',
    '1973-westworld':           '/fotogramas/westworld-poster.jpg',
    '1975-shivers':             '/fotogramas/shivers-poster.jpg',
    '1985-shoah':               '/fotogramas/shoah-poster.jpg',
  });
  window.__RT_POSTER_MAP__ = CRITICA_POSTER_MAP;
  const caps = window.IB_CAPITULOS || [];
  const criticasBySlug = {};
  (window.CRITICAS || []).forEach(c => { criticasBySlug[c.slug] = c; });
  caps.forEach(c => {
    if (!c.poster) c.poster = IB_POSTER_MAP[c.slug] || c.cover;
    if (!c.relatedFull || !c.relatedFull.length) {
      const src = criticasBySlug[c.slug];
      if (src && src.relatedFull) c.relatedFull = src.relatedFull;
      else c.relatedFull = [];
    }
  });
})();

function IBSection({ initialSlug, onSlugChange, onChrome }) {
  const caps = window.IB_CAPITULOS || [];
  const [openSlug, setOpenSlug] = React.useState(initialSlug || null);

  React.useEffect(() => {
    onChrome && onChrome({ accent: '#c01e1e', dark: '#1a1510', light: '#ece3cf' });
  }, [onChrome]);

  React.useEffect(() => {
    setOpenSlug(initialSlug || null);
  }, [initialSlug]);

  const open = (slug) => {
    setOpenSlug(slug);
    onSlugChange && onSlugChange(slug);
  };
  const back = () => {
    setOpenSlug(null);
    onSlugChange && onSlugChange(null);
  };

  if (openSlug) {
    const cap = caps.find(c => c.slug === openSlug);
    if (!cap) return <IBIndex caps={caps} onOpen={open} />;
    return <IBReader cap={cap} caps={caps} onBack={back} onOpen={open} />;
  }
  return <IBIndex caps={caps} onOpen={open} />;
}

// ─── Shared paper background ─────────────────────────────────
const paperBg = `
  radial-gradient(circle at 15% 20%, rgba(150,100,50,0.08) 0%, transparent 35%),
  radial-gradient(circle at 82% 78%, rgba(120,30,20,0.06) 0%, transparent 40%),
  radial-gradient(circle at 45% 50%, rgba(200,160,100,0.04) 0%, transparent 50%),
  repeating-linear-gradient(93deg, transparent 0 60px, rgba(100,70,40,0.03) 60px 61px),
  #ece3cf
`;

function PaperStain({ top, left, size=80, color='rgba(180,100,60,0.12)' }) {
  return (
    <div style={{
      position:'absolute', top, left,
      width: size, height: size * 0.7,
      background: `radial-gradient(ellipse, ${color}, transparent 65%)`,
      borderRadius:'50%', pointerEvents:'none', zIndex: 0,
    }}/>
  );
}

function InkBlot({ top, left, size=14, rot=0 }) {
  // tiny scattered ink blot, hand-drawn feel
  return (
    <div style={{
      position:'absolute', top, left, zIndex: 1,
      width: size, height: size,
      background:'#c01e1e', borderRadius:'50%',
      transform:`rotate(${rot}deg) scale(${0.6 + Math.random()*0.4})`,
      opacity: 0.85, pointerEvents:'none',
      filter:'blur(0.4px)',
    }}/>
  );
}

// ─── INDEX ────────────────────────────────────────────────────
function IBIndex({ caps, onOpen }) {
  return (
    <div style={{
      width:'100%', height:'100%', background: paperBg,
      color:'#1a1510', fontFamily:"'Kalam', 'Caveat', cursive",
      overflowY:'auto', overflowX:'hidden', position:'relative',
      scrollbarWidth:'none',
    }} className="ib-scroll">
      <style>{`
        .ib-scroll::-webkit-scrollbar { display: none; }
        @import url('https://fonts.googleapis.com/css2?family=Caveat:wght@400;500;600;700&family=Kalam:wght@300;400;700&family=Special+Elite&display=swap');
      `}</style>
      <link href="https://fonts.googleapis.com/css2?family=Caveat:wght@400;500;600;700&family=Kalam:wght@300;400;700&family=Special+Elite&display=swap" rel="stylesheet"/>

      <PaperStain top={40} left={-20} size={160} />
      <PaperStain top={380} left={260} size={120} color="rgba(120,30,20,0.08)" />
      <PaperStain top={700} left={-30} size={140} />

      <div style={{ height: 24 }}/>

      {/* HEADER — messy cover page */}
      <div style={{ padding:'20px 18px 12px', position:'relative' }}>

        {/* typewriter meta top — right padding clears the hamburger button */}
        <div style={{
          fontFamily:"'Special Elite', 'Courier New', monospace",
          fontSize: 10, letterSpacing:'0.18em',
          color:'#1a1510', textTransform:'uppercase',
          marginBottom: 8,
          display:'flex', justifyContent:'space-between', opacity: 0.75,
          paddingRight: 54,
        }}>
          <span>cuadernos / 2026</span>
          <span style={{ color:'#c01e1e' }}>★ vol. II ★</span>
        </div>

        {/* Hand-written title */}
        <div style={{
          fontFamily:"'Caveat', cursive", fontWeight: 700,
          fontSize: 78, lineHeight: 0.82,
          color:'#1a1510', letterSpacing:'-0.01em',
          transform:'rotate(-1.5deg)',
          marginBottom: 6, marginTop: 10,
        }}>
          Inmenso
        </div>
        <div style={{
          fontFamily:"'Caveat', cursive", fontWeight: 700,
          fontSize: 86, lineHeight: 0.82,
          color:'#c01e1e', letterSpacing:'-0.015em',
          transform:'rotate(1deg) translateX(40px)',
          marginBottom: 14,
          textDecoration:'underline', textDecorationColor:'#c01e1e',
          textDecorationThickness:'3px', textUnderlineOffset: '4px',
        }}>
          Bastardo.
        </div>

        {/* Crossed-out subtitle */}
        <div style={{
          fontFamily:"'Kalam', cursive", fontSize: 16,
          color:'#4a3a2a', marginLeft: 14,
          position:'relative', display:'inline-block',
          transform:'rotate(-0.5deg)', marginBottom: 6,
        }}>
          <span style={{ textDecoration:'line-through', textDecorationColor:'#c01e1e', textDecorationThickness:'2px' }}>
            Notas sobre cine épico
          </span>
        </div>
        <div style={{
          fontFamily:"'Caveat', cursive", fontWeight: 600, fontSize: 24,
          color:'#c01e1e', marginLeft: 40, marginTop: -2, marginBottom: 8,
          transform:'rotate(-1deg)',
        }}>
          ↖ cuadernos.
        </div>

        <div style={{
          fontFamily:"'Kalam', cursive", fontSize: 13, lineHeight: 1.5,
          color:'#1a1510', marginLeft: 12, marginTop: 14,
          maxWidth:'30ch', transform:'rotate(-0.5deg)',
        }}>
          Un análisis de las películas más grandes, más largas, más épicas <s style={{ textDecorationColor:'#c01e1e', textDecorationThickness:'2px' }}>fallidas</s> de la historia del cine. Todas de 3 horas o más.
        </div>

        {/* hand arrow */}
        <div style={{
          position:'absolute', right: 18, bottom: 18,
          fontFamily:"'Caveat', cursive", fontWeight: 700,
          fontSize: 18, color:'#c01e1e', transform:'rotate(8deg)',
          textAlign:'right', maxWidth: 140, lineHeight: 1.05,
        }}>
          Se recomienda discreción
        </div>
      </div>

      {/* DIVIDER — squiggly hand drawn */}
      <div style={{ padding:'14px 18px 4px', position:'relative' }}>
        <svg width="100%" height="22" style={{ display:'block' }} viewBox="0 0 400 22" preserveAspectRatio="none">
          <path d="M2,11 Q30,4 60,12 T120,10 T180,13 T240,9 T300,12 T360,11 L398,11"
            fill="none" stroke="#1a1510" strokeWidth="1.3" strokeLinecap="round" opacity="0.7"/>
          <path d="M4,14 Q34,8 66,15 T128,12 T188,16 T248,11 T310,15 T372,13 L398,13"
            fill="none" stroke="#c01e1e" strokeWidth="1" strokeLinecap="round" opacity="0.5"/>
        </svg>
      </div>

      {/* INDEX — numbered, hand-drawn boxes */}
      <div style={{ padding:'18px 18px 10px' }}>
        <div style={{
          fontFamily:"'Special Elite', monospace", fontSize: 11,
          letterSpacing:'0.2em', textTransform:'uppercase',
          color:'#1a1510', marginBottom: 16,
          borderBottom:'1.5px solid #1a1510', paddingBottom: 4,
        }}>
          Índice (provisorio)
        </div>

        {caps.map((c, i) => {
          const tilt = (i % 2 === 0 ? -0.7 : 0.6);
          const posterTilt = (i % 2 === 0 ? -2.5 : 3);
          return (
            <button
              key={c.slug}
              onClick={() => onOpen(c.slug)}
              style={{
                display:'block', width:'100%', textAlign:'left',
                background:'transparent', border:'none', padding: 0,
                marginBottom: 28, position:'relative',
                cursor:'pointer', transform:`rotate(${tilt}deg)`,
              }}>
              <div style={{
                display:'flex', alignItems:'flex-start', gap: 12,
                borderBottom:'1px dashed rgba(26,21,16,0.3)', paddingBottom: 14,
              }}>
                {/* vintage poster — taped to the page */}
                {(c.poster || c.cover) ? (
                  <div style={{
                    flex:'0 0 auto', width: 78, position:'relative',
                    transform:`rotate(${posterTilt}deg)`,
                    marginTop: 4,
                  }}>
                    <div style={{
                      padding: 4,
                      background:'#f4ece0',
                      border:'1px solid rgba(26,21,16,0.2)',
                      boxShadow:'0 6px 14px rgba(26,21,16,0.25), 0 1px 2px rgba(26,21,16,0.1)',
                      position:'relative',
                    }}>
                      <img src={c.poster || c.cover} alt={c.filmTitle || c.title}
                        loading="lazy"
                        style={{
                          display:'block', width:'100%', aspectRatio:'2/3',
                          objectFit:'cover',
                          filter:'sepia(0.35) contrast(0.95) saturate(0.85) brightness(0.92)',
                          background:'#1a1510',
                        }}/>
                      {/* aged overlay */}
                      <div style={{
                        position:'absolute', inset: 4,
                        pointerEvents:'none',
                        background:'radial-gradient(ellipse at 30% 25%, transparent 40%, rgba(120,60,20,0.18) 100%)',
                        mixBlendMode:'multiply',
                      }}/>
                      {/* number badge on the poster */}
                      <div style={{
                        position:'absolute', top:-8, left:-6,
                        fontFamily:"'Caveat', cursive", fontWeight: 700,
                        fontSize: 26, color:'#c01e1e', lineHeight: 0.9,
                        transform:`rotate(${-posterTilt - 4}deg)`,
                        textShadow:'0 2px 4px rgba(0,0,0,0.35)',
                      }}>{c.num}.</div>
                    </div>
                    {/* tape strip */}
                    <span aria-hidden="true" style={{
                      position:'absolute', top:-7, right: 8,
                      width: 34, height: 12,
                      background:'rgba(224,200,142,0.7)',
                      boxShadow:'0 1px 2px rgba(0,0,0,0.12)',
                      transform:'rotate(6deg)',
                    }}/>
                  </div>
                ) : (
                  <div style={{
                    fontFamily:"'Caveat', cursive", fontWeight: 700,
                    fontSize: (c.num || '').length <= 2 ? 40
                            : (c.num || '').length === 3 ? 34
                            : 26,
                    color:'#c01e1e', lineHeight: 0.9,
                    width: 52, flexShrink: 0, paddingTop: 2,
                  }}>{c.num}.</div>
                )}
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{
                    fontFamily:"'Caveat', cursive", fontWeight: 600,
                    fontSize: 26, lineHeight: 1.02, color:'#1a1510',
                    marginBottom: 4,
                  }}>
                    {c.title}
                  </div>
                  {c.filmTitle && (
                    <div style={{
                      fontFamily:"'Special Elite', monospace", fontSize: 10,
                      letterSpacing:'0.18em', color:'#6a5a45',
                      textTransform:'uppercase', marginBottom: 6,
                    }}>
                      {c.filmTitle}{c.year ? ` · ${c.year}` : ''}{c.director ? ` · ${Array.isArray(c.director) ? c.director[0] : c.director}` : ''}
                    </div>
                  )}
                  {c.excerpt && (
                    <div style={{
                      fontFamily:"'Kalam', 'Crimson Pro', serif", fontSize: 13,
                      lineHeight: 1.45, color:'#3a2d20',
                      marginBottom: 6, opacity: 0.92,
                      display:'-webkit-box', WebkitLineClamp: 3, WebkitBoxOrient:'vertical',
                      overflow:'hidden',
                    }}>
                      {c.excerpt}
                    </div>
                  )}
                  <div style={{
                    fontFamily:"'Special Elite', monospace", fontSize: 9,
                    letterSpacing:'0.2em', color:'#6a5a45',
                    textTransform:'uppercase',
                  }}>
                    {c.kicker} · →
                  </div>
                </div>
              </div>
              {i === 0 && (
                <div style={{
                  position:'absolute', right: -4, top: -14,
                  fontFamily:"'Caveat', cursive", fontWeight: 700,
                  fontSize: 18, color:'#c01e1e', transform:'rotate(8deg)',
                }}>empezar acá ↓</div>
              )}
              {i === 2 && (
                <div style={{
                  position:'absolute', right: 4, bottom: -14,
                  fontFamily:"'Caveat', cursive", fontWeight: 500,
                  fontSize: 14, color:'#4a3a2a', transform:'rotate(-3deg)',
                  fontStyle:'italic',
                }}>(esto hay que reescribirlo)</div>
              )}
            </button>
          );
        })}
      </div>

      {/* FOOTER — solo aire + un par de manchas para cerrar la página */}
      <div style={{ padding:'24px 22px 40px', position:'relative' }}>
        <InkBlot top={10} left={20} size={8} rot={20}/>
        <InkBlot top={24} left={40} size={5} />
      </div>
    </div>
  );
}

// ─── READER ───────────────────────────────────────────────────
function IBReader({ cap, caps, onBack, onOpen }) {
  const idx = caps.findIndex(c => c.slug === cap.slug);
  // No cyclical wrap — hide "anterior" on first chapter, "siguiente" on last.
  const next = idx >= 0 && idx < caps.length - 1 ? caps[idx + 1] : null;
  const prev = idx > 0 ? caps[idx - 1] : null;

  // Auto-scroll to top when the chapter changes — otherwise React re-uses the
  // scroll container and the new chapter opens mid-page.
  const readerRef = React.useRef(null);
  React.useEffect(() => {
    if (readerRef.current) readerRef.current.scrollTop = 0;
    else window.scrollTo(0, 0);
  }, [cap.slug]);

  return (
    <div style={{
      width:'100%', height:'100%', background: paperBg,
      color:'#1a1510', fontFamily:"'Kalam', cursive",
      overflowY:'auto', overflowX:'hidden', position:'relative',
      scrollbarWidth:'none',
    }} className="ib-reader" ref={readerRef}>
      <style>{`.ib-reader::-webkit-scrollbar { display: none; }`}</style>

      <PaperStain top={120} left={-30} size={180} />
      <PaperStain top={580} left={240} size={140} color="rgba(120,30,20,0.07)" />

      <div style={{ height: 20 }}/>

      {/* TOP BAR — right padding clears the hamburger button */}
      <div style={{
        padding:'10px 64px 8px 18px', display:'flex', justifyContent:'space-between', alignItems:'center',
        borderBottom:'1px dashed rgba(26,21,16,0.3)', marginBottom: 10,
      }}>
        <button onClick={onBack} style={{
          background:'transparent', border:'none', cursor:'pointer',
          fontFamily:"'Caveat', cursive", fontWeight: 600, fontSize: 20,
          color:'#c01e1e', padding: 0,
        }}>← volver al índice</button>
        <div style={{
          fontFamily:"'Special Elite', monospace", fontSize: 9,
          letterSpacing:'0.2em', color:'#6a5a45', textTransform:'uppercase',
        }}>cap {String(idx+1).padStart(2,'0')} / {String(caps.length).padStart(2,'0')}</div>
      </div>

      {/* CHAPTER OPENER */}
      <div style={{ padding:'14px 18px 10px', position:'relative' }}>
        {/* big roman numeral — font-size scales with numeral length so
            wide numerals like "XIII" or "XVIII" never bleed into the title. */}
        <div style={{
          fontFamily:"'Caveat', cursive", fontWeight: 700,
          fontSize: (cap.num || '').length <= 2 ? 108
                  : (cap.num || '').length === 3 ? 92
                  : 72,
          lineHeight: 0.82,
          color:'#c01e1e', letterSpacing:'-0.02em',
          transform:'rotate(-3deg)',
          marginBottom: 6, marginLeft: -4,
          textShadow:'2px 2px 0 rgba(120,30,20,0.1)',
          display: 'inline-block',
        }}>
          {cap.num}
        </div>

        <div style={{
          fontFamily:"'Special Elite', monospace", fontSize: 10,
          letterSpacing:'0.22em', color:'#6a5a45',
          textTransform:'uppercase', marginTop: 10, marginBottom: 4,
        }}>
          {cap.kicker}
        </div>

        <h1 style={{
          fontFamily:"'Caveat', cursive", fontWeight: 700,
          fontSize: 52, lineHeight: 0.92,
          color:'#1a1510', letterSpacing:'-0.01em',
          margin:'0 0 6px',
          textDecoration:'underline', textDecorationColor:'#c01e1e',
          textDecorationThickness: '2.5px', textUnderlineOffset: '6px',
          paddingRight: 60,
        }}>
          {cap.title}
        </h1>

        <div style={{
          position:'absolute', right: 12, top: 10,
          fontFamily:"'Caveat', cursive", fontSize: 14,
          color:'#c01e1e', transform:'rotate(10deg)',
          textAlign:'center', lineHeight: 1.1,
          opacity: 0.85,
        }}>
          ✎ <br/>seguir<br/>pensando
        </div>
      </div>

      {/* BODY — blocks with different kinds */}
      <div style={{ padding:'18px 20px 24px' }}>
        {cap.blocks.map((b, i) => {
          if (b.kind === 'p') {
            return (
              <p key={i} style={{
                fontFamily:"'Crimson Pro', Georgia, serif",
                fontSize: 17, fontWeight: 400,
                lineHeight: 1.6, color:'#1a1510',
                margin:'0 0 18px',
                textWrap:'pretty',
              }}>
                {i === 0 && (
                  <span style={{
                    fontFamily:"'Caveat', cursive", fontWeight: 700,
                    fontSize: 56, color:'#c01e1e',
                    float:'left', lineHeight: 0.8,
                    paddingRight: 8, paddingTop: 4,
                  }}>{b.text[0]}</span>
                )}
                {i === 0 ? b.text.slice(1) : b.text}
              </p>
            );
          }
          if (b.kind === 'note') {
            // margin note — hand-written red, rotated
            return (
              <div key={i} style={{
                margin:'14px 0 18px auto',
                maxWidth:'72%',
                fontFamily:"'Caveat', cursive", fontWeight: 600,
                fontSize: 22, color:'#c01e1e',
                lineHeight: 1.2,
                transform:'rotate(-1.5deg)',
                padding:'8px 12px',
                borderLeft:'2.5px solid #c01e1e',
                borderBottom:'1px solid rgba(192,30,30,0.5)',
                background:'rgba(192,30,30,0.04)',
                position:'relative',
              }}>
                <span style={{
                  position:'absolute', left: -16, top: 4,
                  fontSize: 22, color:'#c01e1e',
                }}>✎</span>
                {b.text}
              </div>
            );
          }
          if (b.kind === 'crossout') {
            return (
              <div key={i} style={{
                margin:'10px 0 16px',
                fontFamily:"'Crimson Pro', Georgia, serif",
                fontSize: 16, fontWeight: 400,
                color:'#6a5a45',
                textDecoration:'line-through',
                textDecorationColor:'#c01e1e',
                textDecorationThickness:'2px',
                fontStyle:'italic', opacity: 0.78,
                lineHeight: 1.5,
              }}>
                <span style={{
                  fontFamily:"'Caveat', cursive", fontWeight: 700,
                  textDecoration:'none', color:'#c01e1e', marginRight: 8,
                  fontSize: 20,
                }}>(no.)</span>
                {b.text}
              </div>
            );
          }
          if (b.kind === 'img') {
            // film photogram as if it were a polaroid taped into the notebook
            const rot = ((i * 53) % 7) - 3; // stable rotation per position
            return (
              <figure key={i} style={{
                margin:'22px auto 26px',
                padding:'10px 10px 14px',
                background:'#f4ece0',
                border:'1px solid rgba(26,21,16,0.18)',
                boxShadow:'0 8px 22px rgba(26,21,16,0.18), 0 2px 4px rgba(26,21,16,0.14)',
                transform:`rotate(${rot}deg)`,
                maxWidth: 320,
                position:'relative',
              }}>
                <img src={b.src} alt={b.alt || ''} style={{
                  display:'block', width:'100%', aspectRatio:'16/10',
                  objectFit:'cover', background:'#1a1510',
                }} loading="lazy"/>
                {b.alt && (
                  <figcaption style={{
                    marginTop: 8,
                    fontFamily:"'Caveat', cursive", fontWeight: 600,
                    fontSize: 16, color:'#1a1510',
                    textAlign:'center', lineHeight: 1.15,
                  }}>
                    {b.alt}
                  </figcaption>
                )}
                {/* tape strip */}
                <span aria-hidden="true" style={{
                  position:'absolute', top:-10, left:'50%',
                  transform:'translateX(-50%) rotate(-2deg)',
                  width: 58, height: 16,
                  background:'rgba(224,200,142,0.65)',
                  boxShadow:'0 1px 2px rgba(0,0,0,0.12)',
                }}/>
              </figure>
            );
          }
          if (b.kind === 'pull') {
            return (
              <blockquote key={i} style={{
                margin:'20px 0 22px',
                padding:'10px 0 10px 14px',
                borderLeft:'3px solid #c01e1e',
                fontFamily:"'Caveat', cursive", fontWeight: 700,
                fontSize: 26, lineHeight: 1.15,
                color:'#1a1510',
                transform:'rotate(-0.4deg)',
              }}>
                {b.text}
              </blockquote>
            );
          }
          if (b.kind === 'h2' || b.kind === 'h3') {
            return (
              <h3 key={i} style={{
                margin:'26px 0 12px',
                fontFamily:"'Caveat', cursive", fontWeight: 700,
                fontSize: b.kind === 'h2' ? 30 : 24,
                lineHeight: 1.08,
                color:'#1a1510',
                textDecoration:'underline',
                textDecorationColor:'#c01e1e',
                textDecorationThickness: '2px',
                textUnderlineOffset: '4px',
              }}>
                {b.text}
              </h3>
            );
          }
          return null;
        })}

      </div>

      {/* RELATED FILMS — "Seguí leyendo" */}
      <IBRelated cap={cap} />

      {/* PREV / NEXT nav — stacked so long titles breathe.
          First chapter has no "anterior"; last chapter has no "siguiente". */}
      <div style={{
        display:'flex', flexDirection:'column', gap: 10,
        padding:'10px 18px 0',
      }}>
        {prev && (
          <button
            onClick={() => onOpen(prev.slug)}
            aria-label={`Anterior — ${prev.title}`}
            style={{
              background:'rgba(26,21,16,0.04)',
              border:'1.5px dashed #1a1510',
              padding:'12px 14px', cursor:'pointer',
              textAlign:'left',
              fontFamily:"'Kalam', cursive",
              position:'relative',
              transform:'rotate(-0.4deg)',
              display:'flex', alignItems:'center', gap: 12,
            }}>
            <div style={{
              fontFamily:"'Caveat', cursive", fontWeight: 700,
              fontSize: 30, color:'#c01e1e', lineHeight: 0.9,
              flex:'0 0 auto', minWidth: 44,
            }}>{prev.num}.</div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{
                fontFamily:"'Special Elite', monospace", fontSize: 9,
                letterSpacing:'0.22em', color:'#6a5a45',
                textTransform:'uppercase', marginBottom: 4,
              }}>← Capítulo anterior</div>
              <div style={{
                fontFamily:"'Caveat', cursive", fontWeight: 600,
                fontSize: 20, color:'#1a1510', lineHeight: 1.05,
                wordBreak:'break-word',
              }}>{prev.title}</div>
            </div>
          </button>
        )}

        {next && (
          <button
            onClick={() => onOpen(next.slug)}
            aria-label={`Siguiente — ${next.title}`}
            style={{
              background:'rgba(26,21,16,0.04)',
              border:'1.5px dashed #1a1510',
              padding:'12px 14px', cursor:'pointer',
              textAlign:'right',
              fontFamily:"'Kalam', cursive",
              position:'relative',
              transform:'rotate(0.4deg)',
              display:'flex', alignItems:'center', gap: 12,
            }}>
            <div style={{ flex: 1, minWidth: 0, textAlign:'right' }}>
              <div style={{
                fontFamily:"'Special Elite', monospace", fontSize: 9,
                letterSpacing:'0.22em', color:'#6a5a45',
                textTransform:'uppercase', marginBottom: 4,
              }}>Capítulo siguiente →</div>
              <div style={{
                fontFamily:"'Caveat', cursive", fontWeight: 600,
                fontSize: 20, color:'#1a1510', lineHeight: 1.05,
                wordBreak:'break-word',
              }}>{next.title}</div>
            </div>
            <div style={{
              fontFamily:"'Caveat', cursive", fontWeight: 700,
              fontSize: 30, color:'#c01e1e', lineHeight: 0.9,
              flex:'0 0 auto', minWidth: 44, textAlign:'right',
            }}>{next.num}.</div>
          </button>
        )}
      </div>
      <div style={{ height: 72 }}/>
    </div>
  );
}

// ─── RELATED (Seguí leyendo) ──────────────────────────────────
function IBRelated({ cap }) {
  const rel = (cap.relatedFull || [])
    .filter(r => r && r.type === 'critica')
    .slice(0, 4);
  if (!rel.length) return null;

  const criticasBySlug = React.useMemo(() => {
    const m = {};
    (window.CRITICAS || []).forEach(c => { m[c.slug] = c; });
    return m;
  }, []);
  const ibSlugs = React.useMemo(() => {
    const s = new Set();
    (window.IB_CAPITULOS || []).forEach(c => s.add(c.slug));
    return s;
  }, []);
  const posterMap = window.__RT_POSTER_MAP__ || {};

  const resolved = rel.map(r => {
    const c = criticasBySlug[r.slug];
    if (!c) return null;
    const film = c.film || {};
    // Route to the correct section based on whether this is an IB chapter.
    const isIB = ibSlugs.has(c.slug)
      || (Array.isArray(c.series) && c.series.includes('inmenso-bastardo'));
    return {
      slug: c.slug,
      href: isIB ? `#/ib/${c.slug}` : `#/vv/${c.slug}`,
      title: c.title,
      filmTitle: film.title || c.filmTitle || '',
      year: film.year || c.year || '',
      director: Array.isArray(film.director) ? film.director[0] : (c.director || ''),
      poster: c.poster || posterMap[c.slug] || c.cover,
      section: isIB ? 'Inmenso Bastardo' : 'Vamos Viendo',
    };
  }).filter(Boolean);

  if (!resolved.length) return null;

  return (
    <div style={{
      margin:'28px 18px 10px',
      padding:'18px 0 6px',
      borderTop:'1.5px solid #1a1510',
      position:'relative',
    }}>
      <div style={{
        fontFamily:"'Special Elite', monospace", fontSize: 10,
        letterSpacing:'0.22em', color:'#1a1510',
        textTransform:'uppercase', marginBottom: 14,
        display:'flex', alignItems:'center', gap: 8,
      }}>
        <span style={{ color:'#c01e1e' }}>✎</span>
        Seguí leyendo — películas relacionadas
      </div>
      <div style={{
        display:'grid', gridTemplateColumns:'repeat(2, 1fr)',
        gap: 14,
      }}>
        {resolved.map((r, i) => {
          const tilt = (i % 2 === 0 ? -1.6 : 1.8);
          return (
            <a
              key={r.slug}
              href={r.href}
              style={{
                textDecoration:'none', color:'inherit',
                display:'block', position:'relative',
                transform:`rotate(${tilt}deg)`,
              }}>
              <div style={{
                padding: 4,
                background:'#f4ece0',
                border:'1px solid rgba(26,21,16,0.2)',
                boxShadow:'0 6px 14px rgba(26,21,16,0.22), 0 1px 2px rgba(26,21,16,0.1)',
                position:'relative',
              }}>
                {r.poster ? (
                  <img src={r.poster} alt={r.filmTitle || r.title}
                    loading="lazy"
                    style={{
                      display:'block', width:'100%', aspectRatio:'2/3',
                      objectFit:'cover',
                      filter:'sepia(0.3) contrast(0.95) saturate(0.85) brightness(0.93)',
                      background:'#1a1510',
                    }}/>
                ) : (
                  <div style={{
                    width:'100%', aspectRatio:'2/3',
                    background:'#1a1510',
                    display:'flex', alignItems:'center', justifyContent:'center',
                    color:'#c01e1e', fontFamily:"'Caveat', cursive",
                    fontSize: 26, fontWeight: 700,
                  }}>{r.filmTitle || '?'}</div>
                )}
                <div style={{
                  position:'absolute', inset: 4,
                  pointerEvents:'none',
                  background:'radial-gradient(ellipse at 30% 25%, transparent 40%, rgba(120,60,20,0.18) 100%)',
                  mixBlendMode:'multiply',
                }}/>
                <span aria-hidden="true" style={{
                  position:'absolute', top:-7, right: 10,
                  width: 30, height: 11,
                  background:'rgba(224,200,142,0.7)',
                  boxShadow:'0 1px 2px rgba(0,0,0,0.12)',
                  transform:'rotate(-4deg)',
                }}/>
              </div>
              <div style={{
                marginTop: 8,
                fontFamily:"'Caveat', cursive", fontWeight: 700,
                fontSize: 18, lineHeight: 1.05, color:'#1a1510',
              }}>{r.filmTitle || r.title}</div>
              {(r.year || r.director) && (
                <div style={{
                  fontFamily:"'Special Elite', monospace", fontSize: 9,
                  letterSpacing:'0.18em', color:'#6a5a45',
                  textTransform:'uppercase', marginTop: 2,
                }}>
                  {r.year}{r.director ? ` · ${r.director}` : ''}
                </div>
              )}
              <div style={{
                fontFamily:"'Special Elite', monospace", fontSize: 8,
                letterSpacing:'0.22em', color:'#c01e1e',
                textTransform:'uppercase', marginTop: 4,
              }}>
                → {r.section}
              </div>
            </a>
          );
        })}
      </div>
    </div>
  );
}

window.IBSection = IBSection;
