// ═══════════════════════════════════════════════════════════════
// SECCIÓN — DETRÁS DE ESCENAS
// Estética: marquesina (bombillas + split-flap) + bio.
// Texto real del autor + invitación a las demás secciones.
// ═══════════════════════════════════════════════════════════════

// Renderiza un string reemplazando cada "Rintana" por el wordmark oficial
// (Bebas Neue + sombra azul + dot rojo). Se usa en la bio para que la marca
// se lea como logo cuando aparece mencionada en texto corrido.
function renderWithBrand(text, opts = {}) {
  const size = opts.size || 18;
  const parts = String(text).split(/(Rintana)/g);
  return parts.map((p, i) => {
    if (p !== 'Rintana') return p;
    return (
      <span key={i} style={{
        fontFamily:"'Bebas Neue', 'Anton', sans-serif",
        fontSize: size, letterSpacing:'0.12em', fontWeight: 400,
        color:'#f0ece4',
        textShadow:'2px 2px 0 #2b5dd9',
        textTransform:'uppercase',
        display:'inline-flex', alignItems:'baseline',
        verticalAlign: 'baseline',
      }}>RINTANA<span style={{
        display:'inline-block', width: 5, height: 5,
        background:'#d92b2b', borderRadius:'50%',
        marginLeft: 4, transform:'translateY(-1px)',
        boxShadow:'0 0 6px rgba(217,43,43,0.6)',
      }}/></span>
    );
  });
}

// Texto de bio hardcodeado — prevalece sobre window.RINTANA_BIO mientras
// gen-data.mjs no se re-ejecute (sandbox bash roto).
const DB_BIO_BLOCKS = [
  'y tal como dice más arriba, soy muchas cosas. Crítico de cine, Analista de Sistemas, Realizador de cine, y algunas otras cositas más. Pero además de eso, también soy un tipazo.',
  'Escribí desde 2019 hasta 2024 en Cuatro Bastardos (de dónde salen muchas de las notas escritas en esta página), y desde 2026 en adelante escribo acá, en Rintana. También tuve un podcast llamado "Benjamin Podcast", estudié crítica de cine con Diego Batlle y dirigí 3 cortometrajes en mi paso académico como director de cine. También produje uno.',
  'Rintana es un proyecto algo deforme, que juntó mis ganas de escribir y dejar registro de lo escrito, con mi interés en el desarrollo web y programación actual. A nivel técnico, todo lo que está acá podría estar en un Wordpress o en un Substack, pero hay algo de que sea "hecho a mano" que creo que es lo que debemos cuidar en la sociedad de hoy. Igual lo hice todo con IA.',
];

const DB_FLAP_CHARSET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 .,-!¿?\'';

function DBFlapCell({ ch, delay = 0 }) {
  const [shown, setShown] = React.useState(' ');
  const [flipping, setFlipping] = React.useState(false);
  const upper = (ch || ' ').toUpperCase();

  React.useEffect(() => {
    setFlipping(true);
    const start = DB_FLAP_CHARSET.indexOf(shown.toUpperCase());
    const target = DB_FLAP_CHARSET.indexOf(upper === '' ? ' ' : upper);
    let current = start < 0 ? 0 : start;
    const step = () => {
      if (DB_FLAP_CHARSET[current] === upper || target < 0) { setShown(upper); setFlipping(false); return; }
      current = (current + 1) % DB_FLAP_CHARSET.length;
      setShown(DB_FLAP_CHARSET[current]);
      setTimeout(step, 38 + Math.random()*18);
    };
    const t = setTimeout(step, delay);
    return () => clearTimeout(t);
  }, [upper, delay]);

  return (
    <span style={{
      display:'inline-block',
      width: 22, height: 36, margin: '0 1px',
      background: '#0a0805',
      border: '1px solid #2a2520',
      color: '#c8960a',
      fontFamily:"'Anton', sans-serif",
      fontSize: 28,
      lineHeight: '36px',
      textAlign:'center',
      position:'relative',
      overflow:'hidden',
      boxShadow: flipping ? 'inset 0 -6px 10px rgba(0,0,0,0.4)' : 'inset 0 -6px 10px rgba(200,150,10,0.08)',
    }}>
      <span style={{
        position:'absolute', left:0, right:0, top:'50%', height: 1, background:'#000', zIndex: 3,
      }}/>
      {shown}
    </span>
  );
}

function DBFlapRow({ text, width = 12, delayBase = 0 }) {
  const chars = text.padEnd(width, ' ').slice(0, width).split('');
  return (
    <div style={{ display:'flex', justifyContent:'center', flexWrap:'wrap', gap: 0 }}>
      {chars.map((c, i) => <DBFlapCell key={i+'-'+c+'-'+text} ch={c} delay={delayBase + i*40} />)}
    </div>
  );
}

function DBBulbs({ bulbs, count = 14 }) {
  return (
    <div style={{ display:'flex', justifyContent:'space-around', alignItems:'center', padding:'4px 2px' }}>
      {Array.from({length: count}).map((_,i) => {
        const on = (i + bulbs) % 3 !== 0;
        return (
          <span key={i} style={{
            width: 8, height: 8, borderRadius:'50%',
            background: on ? '#ffd87a' : '#3a2a12',
            boxShadow: on ? '0 0 8px 2px rgba(255,216,122,0.6), 0 0 2px 0 rgba(255,216,122,0.9)' : 'none',
            transition:'background 0.2s, box-shadow 0.2s',
          }}/>
        );
      })}
    </div>
  );
}

// ─── Section ────────────────────────────────────────────────
function DBSection({ onPickFilm, onPickSection, onChrome }) {
  const [bulbs, setBulbs] = React.useState(0);

  React.useEffect(() => {
    onChrome && onChrome({ accent: '#c8960a', dark: '#0b0907', light: '#f0e6d0' });
  }, [onChrome]);

  React.useEffect(() => {
    const t = setInterval(() => setBulbs(b => b+1), 700);
    return () => clearInterval(t);
  }, []);

  return (
    <div style={{
      width:'100%', height:'100%', background:'#0b0907', color:'#f0e6d0',
      fontFamily:"'Crimson Pro', serif", overflow:'auto', position:'relative',
      scrollbarWidth:'none',
    }} className="db-scroll">
      <style>{`.db-scroll::-webkit-scrollbar { display: none; }`}</style>

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

      {/* Status row — right padding clears the hamburger button (top:14, 44×44) */}
      <div style={{
        padding:'10px 64px 10px 22px', display:'flex', justifyContent:'space-between', alignItems:'center',
        borderBottom:'1px solid #2a2520',
      }}>
        <div style={{ fontFamily:"'Bebas Neue', sans-serif", fontSize: 18, letterSpacing:'0.14em', color:'#f0ece4' }}>
          DETRÁS DE ESCENAS
        </div>
        <div style={{ fontFamily:"'JetBrains Mono', monospace", fontSize: 9, letterSpacing:'0.22em', color:'#6a5e50', textTransform:'uppercase' }}>
          Hoy · el autor
        </div>
      </div>

      {/* THE MARQUEE — "SOY NICO" */}
      <div style={{
        margin: '18px 10px 0',
        background: 'radial-gradient(ellipse at top, rgba(192,57,43,0.18), transparent 70%), #100b08',
        border: '1px solid #2a2520',
        padding: '18px 8px 16px',
        position:'relative',
      }}>
        <DBBulbs bulbs={bulbs} />

        <div style={{
          textAlign:'center', fontFamily:"'JetBrains Mono', monospace", fontSize: 9,
          letterSpacing:'0.3em', color:'#c0392b', textTransform:'uppercase', margin: '6px 0 12px',
        }}>
          ★ ★ ★    EL AUTOR    ★ ★ ★
        </div>

        <div style={{ marginBottom: 6 }}>
          <DBFlapRow text="SOY NICO" width={9} delayBase={0} />
        </div>
        <div style={{ marginBottom: 10 }}>
          <DBFlapRow text="BARAK" width={9} delayBase={400} />
        </div>

        <div style={{
          textAlign:'center', fontFamily:"'Crimson Pro', serif", fontStyle:'italic',
          fontSize: 13.5, color:'#b8a88a', marginTop: 8, marginBottom: 4,
          lineHeight: 1.4, padding:'0 8px',
        }}>
          Crítico de cine, Analista de Sistemas<br/>
          <span style={{ color:'#f0e6d0', fontStyle:'normal', fontSize:13.5, letterSpacing:'0.04em' }}>y Realizador de cine.</span>
        </div>

        <DBBulbs bulbs={bulbs+1} />
      </div>

      {/* QUICK STATS — stacked rows so long values have room */}
      <div style={{
        margin: '16px 10px 0', padding: '14px 16px',
        background:'#13100c', border:'1px solid #2a2520',
        display:'flex', flexDirection:'column',
      }}>
        {[
          ['Pelis por año', 'Muchas', '#c8960a'],
          ['Ritmo', 'Menos de las que me gustarían', '#f0e6d0'],
          ['Desde', '1997', '#f0e6d0'],
        ].map(([label, value, color], i) => (
          <div key={label} style={{
            display:'flex', justifyContent:'space-between', alignItems:'baseline',
            gap: 14,
            padding:'8px 0',
            borderBottom: i < 2 ? '1px dashed #2a2520' : 'none',
          }}>
            <div style={{
              fontFamily:"'JetBrains Mono', monospace", fontSize: 9,
              letterSpacing:'0.22em', color:'#6a5e50', textTransform:'uppercase',
              flexShrink: 0,
            }}>{label}</div>
            <div style={{
              fontFamily:"'Anton', sans-serif",
              fontSize: value.length > 14 ? 16 : 26,
              color, lineHeight: 1.05, textAlign:'right',
              textTransform:'uppercase',
            }}>{value}</div>
          </div>
        ))}
      </div>

      {/* BIO — "SOY NICO BARAK," (el título se continúa en el primer párrafo) */}
      <section style={{ padding:'28px 22px 16px' }}>
        <div style={{
          fontFamily:"'Anton', sans-serif", fontSize: 38, lineHeight: 0.95,
          textTransform:'uppercase', letterSpacing:'-0.01em',
          color:'#f0e6d0', marginBottom: 14,
        }}>
          Soy Nico<br/>
          <span style={{ color:'#c8960a' }}>Barak,</span>
        </div>

        {DB_BIO_BLOCKS.map((text, i) => (
          <p key={i} style={{
            fontFamily:"'Crimson Pro', serif", fontSize: 16.5, lineHeight: 1.65,
            color: i === 0 ? '#f0e6d0' : '#d6c8a8',
            margin:'0 0 14px',
          }}>
            {renderWithBrand(text, { size: 18 })}
          </p>
        ))}
      </section>

      {/* CONTACTAME */}
      <section style={{
        padding:'18px 22px 24px', borderTop:'1px solid #2a2520',
      }}>
        <div style={{
          fontFamily:"'JetBrains Mono', monospace", fontSize: 9,
          letterSpacing:'0.32em', color:'#c0392b', textTransform:'uppercase',
          marginBottom: 14,
        }}>Contactame ↗</div>

        <div style={{
          fontFamily:"'Crimson Pro', serif", fontSize: 16.5, lineHeight: 1.6,
          color:'#d6c8a8',
        }}>
          Podés escribirme por Instagram a{' '}
          <a href="https://instagram.com/nicobarak" target="_blank" rel="noopener noreferrer"
            style={{
              fontFamily:"'Anton', sans-serif",
              fontStyle:'normal',
              color:'#c8960a',
              textDecoration:'underline',
              textDecorationColor:'#c0392b',
              textDecorationThickness: '2px',
              textUnderlineOffset: '3px',
              letterSpacing:'0.02em',
              fontSize: 17,
            }}>@nicobarak</a>
          , mandarme un mail a…{' '}
          <span style={{ fontStyle:'italic', color:'#8a7d6b' }}>
            ¿? ¿Por qué mandás mails? Escribime por Instagram.
          </span>
        </div>
      </section>

      {/* PRÓXIMAS FUNCIONES — links a secciones (counts se calculan en vivo) */}
      <div style={{ padding:'10px 22px 10px', borderTop:'1px solid #2a2520' }}>
        <div style={{ fontFamily:"'JetBrains Mono', monospace", fontSize: 9, letterSpacing:'0.28em', color:'#c0392b', textTransform:'uppercase', margin:'14px 0 10px' }}>
          Ir a ↓
        </div>
        <div style={{ display:'flex', flexDirection:'column', gap: 0 }}>
          {(() => {
            // VV_FULL es objeto keyed por slug — usamos VV_ORDER (array) para contar.
            // Fallback a CRITICAS si VV_ORDER no está disponible.
            const vvCount = Array.isArray(window.VV_ORDER)
              ? window.VV_ORDER.length
              : (window.VV_FULL ? Object.keys(window.VV_FULL).length
                : (window.CRITICAS || []).length);
            const ibCount = (window.IB_CAPITULOS || []).length;
            const edCount = (window.EDITORIALES || []).length;
            const plural = (n, s, p) => `${n} ${n === 1 ? s : p}`;
            return [
              { id:'vv', name:'Vamos Viendo',     sub:`${plural(vvCount, 'crítica', 'críticas')} · feed`,        num:'01' },
              { id:'ib', name:'Inmenso Bastardo', sub:`${plural(ibCount, 'capítulo', 'capítulos')} · épicas`,    num:'02' },
              { id:'ed', name:'EdiBarak',         sub:`${plural(edCount, 'editorial', 'editoriales')} · opinión`, num:'03' },
            ];
          })().map((sec, i) => (
            <div key={sec.id} onClick={() => onPickSection && onPickSection(sec.id)} style={{
              padding:'12px 0', borderBottom:'1px dashed #2a2520',
              display:'flex', justifyContent:'space-between', alignItems:'center',
              cursor:'pointer',
            }}>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontFamily:"'JetBrains Mono', monospace", fontSize: 8, letterSpacing:'0.2em', color:'#c0392b', textTransform:'uppercase' }}>
                  {sec.num} · {sec.sub}
                </div>
                <div style={{ fontFamily:"'Anton', sans-serif", fontSize: 20, textTransform:'uppercase', color:'#f0e6d0', lineHeight: 1.05, marginTop: 2, overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>
                  {sec.name}
                </div>
              </div>
              <div style={{ fontFamily:"'Anton', sans-serif", fontSize: 22, color:'#c8960a', marginLeft: 10 }}>→</div>
            </div>
          ))}
        </div>
      </div>

      {/* SIGNOFF — chiste sobre derechos reservados & IA.
          Más chico y sin line-breaks manuales, para que fluya como footer. */}
      <div style={{
        padding:'28px 18px 14px', textAlign:'center',
        fontFamily:"'Crimson Pro', serif", fontStyle:'italic', fontSize: 12,
        color:'#8a7d6b', lineHeight: 1.55,
      }}>
        © 2026 — Todos los derechos reservados a Nico Barak. La IA dice que son suyos también, y por ahora tiene mejores abogados.
      </div>

      {/* Wordmark bottom — extra bottom padding to clear mobile browser chrome */}
      <div style={{ padding:'0 22px 96px', textAlign:'center', fontFamily:"'JetBrains Mono', monospace", fontSize: 9, letterSpacing:'0.3em', color:'#4a4036', textTransform:'uppercase' }}>
        · rintana · 2026 — ∞ ·
      </div>
    </div>
  );
}

window.DBSection = DBSection;
