/* ============================================================
   Forja Lendár[IA] · Vídeo do Fundador (Reels 9:16, 90s)
   Cenas + atmosfera. Narração em 3ª pessoa (sobre o Fundador).
   Lei da cor: amarelo + símbolos sagrados só em peça de luz;
   sombra/inimigo recebe vermelho/brasa.
   ============================================================ */

const C = {
  preto:   '#131109',
  preto2:  '#1B1810',
  preto3:  '#221E14',
  bege:    '#E8DCC4',
  amarelo: '#F6C324',
  vermelho:'#E63946',
  brasa:   '#8B0000',
  bronze:  '#9A7D56',
  bronzeC: '#A88A5C',
  cinzas:  '#4A453E',
  aco:     '#2C3E50',
  fg2:     'rgba(232,220,196,0.70)',
  fg3:     'rgba(232,220,196,0.55)',
};
const FONT = {
  mon: "'Archivo Black', 'Arial Black', sans-serif",
  sag: "'Cinzel', serif",
  op:  "'EB Garamond', Georgia, serif",
};
const IMG = (n) => `../assets/founder/${n}`;

// ── Tweaks context (provided by App) ───────────────────────────────
const TW = React.createContext({});
const useTw = () => React.useContext(TW);

function climate(clima) {
  if (clima === 'ferro') return {
    glowA: 'rgba(168,138,92,0.42)', glowB: 'rgba(44,62,80,0.50)',
    ember: '212,196,150', tint: 'rgba(28,40,54,0.30)',
  };
  if (clima === 'ouro') return {
    glowA: 'rgba(246,195,36,0.55)', glowB: 'rgba(139,0,0,0.30)',
    ember: '246,205,90', tint: 'rgba(60,40,8,0.18)',
  };
  return { // brasa (default)
    glowA: 'rgba(139,0,0,0.55)', glowB: 'rgba(246,160,50,0.30)',
    ember: '246,150,60', tint: 'rgba(40,12,4,0.22)',
  };
}

// ── timing helpers ─────────────────────────────────────────────────
const E = Easing;

// per-element reveal: rise + fade in at `at`, optional fade out at `out`
function reveal(lt, at, opts = {}) {
  const { rise = 30, dur = 0.65, ease = E.easeOutCubic, out = null, outDur = 0.5, outRise = -14 } = opts;
  let o = 0, ty = rise;
  const t = (lt - at) / dur;
  if (t <= 0) { o = 0; ty = rise; }
  else if (t < 1) { const e = ease(t); o = e; ty = rise * (1 - e); }
  else { o = 1; ty = 0; }
  if (out != null && lt > out) {
    const e = E.easeInCubic(clamp((lt - out) / outDur, 0, 1));
    o = (t >= 1 ? 1 : o) * (1 - e); ty = outRise * e;
  }
  return { opacity: o, transform: `translateY(${ty}px)` };
}

// group envelope (whole block fade in/out)
function group(lt, inAt, outAt, inDur = 0.7, outDur = 0.7) {
  let o = 0;
  if (lt < inAt) o = 0;
  else if (lt < inAt + inDur) o = E.easeOutCubic((lt - inAt) / inDur);
  else if (lt < outAt) o = 1;
  else if (lt < outAt + outDur) o = 1 - E.easeInCubic((lt - outAt) / outDur);
  else o = 0;
  return o;
}

function counter(lt, at, to, dur = 1.4) {
  return Math.round(interpolate([at, at + dur], [0, to], E.easeOutCubic)(lt));
}

// ── Karaoke caption ────────────────────────────────────────────────
function Kara({ lt, at, text, per = 0.17, ramp = 0.3, size = 44, color = C.bege,
  font = FONT.op, weight = 500, lh = 1.32, align = 'left', x, y, width = 900,
  out = null, outDur = 0.5, style = {}, shadow = true }) {
  const tw = useTw();
  if (tw.legendas === false) return null;
  const words = text.split(' ');
  let wrapO = 1, ty = 0;
  if (out != null && lt > out) {
    const e = E.easeInCubic(clamp((lt - out) / outDur, 0, 1));
    wrapO = 1 - e; ty = -12 * e;
  }
  return (
    <div style={{
      position: 'absolute', left: x, top: y, width,
      fontFamily: font, fontSize: size, fontWeight: weight, lineHeight: lh,
      textAlign: align, opacity: wrapO, transform: `translateY(${ty}px)`,
      textShadow: shadow ? '0 2px 18px rgba(0,0,0,0.65)' : 'none',
      ...style,
    }}>
      {words.map((w, i) => {
        const e = E.easeOutQuad(clamp((lt - (at + i * per)) / ramp, 0, 1));
        return (
          <span key={i} style={{ color, opacity: 0.20 + 0.80 * e }}>{w + ' '}</span>
        );
      })}
    </div>
  );
}

// ── Full-bleed background image with slow ken burns + veil ─────────
function Bg({ src, lt, dur, from = 1.05, to = 1.18, fx = '50%', fy = '38%',
  inDur = 0.8, outDur = 0.8, veil, tint = null, grade = 1 }) {
  const p = clamp(lt / dur, 0, 1);
  const scale = from + (to - from) * p;
  let op = 1;
  if (lt < inDur) op = E.easeOutCubic(clamp(lt / inDur, 0, 1));
  else if (lt > dur - outDur) op = 1 - E.easeInCubic(clamp((lt - (dur - outDur)) / outDur, 0, 1));
  const defVeil = 'linear-gradient(180deg, rgba(19,17,9,0.45) 0%, rgba(19,17,9,0.20) 30%, rgba(19,17,9,0.55) 68%, rgba(19,17,9,0.96) 100%)';
  return (
    <div style={{ position: 'absolute', inset: 0, opacity: op, overflow: 'hidden' }}>
      <img src={src} alt="" style={{
        position: 'absolute', inset: 0, width: '100%', height: '100%',
        objectFit: 'cover', objectPosition: `${fx} ${fy}`,
        transform: `scale(${scale})`, transformOrigin: `${fx} ${fy}`,
        filter: `saturate(${0.92 * grade}) contrast(1.04) brightness(${0.92 * grade})`,
      }} />
      {tint && <div style={{ position: 'absolute', inset: 0, background: tint, mixBlendMode: 'multiply' }} />}
      <div style={{ position: 'absolute', inset: 0, background: veil || defVeil }} />
    </div>
  );
}

// ── shared label / divider bits ────────────────────────────────────
function Eyebrow({ children, color = C.amarelo, style = {} }) {
  return (
    <div style={{
      fontFamily: FONT.sag, fontSize: 23, letterSpacing: '0.34em',
      textTransform: 'uppercase', color, fontWeight: 600, ...style,
    }}>{children}</div>
  );
}

// ════════════════════════════════════════════════════════════════════
//  ATMOSFERA · brasas, vinheta, grão  (sempre vivas, fora da timeline)
// ════════════════════════════════════════════════════════════════════
function Embers({ color }) {
  const tw = useTw();
  if (tw.embers === false) return null;
  const seeds = Embers.seeds || (Embers.seeds = Array.from({ length: 26 }, (_, i) => ({
    left: (i * 39.7) % 100,
    size: 2 + (i % 4),
    delay: -(i * 0.9) % 14,
    dur: 9 + (i % 7) * 1.6,
    drift: ((i % 5) - 2) * 28,
    op: 0.25 + (i % 5) * 0.13,
  })));
  return (
    <div style={{ position: 'absolute', inset: 0, overflow: 'hidden', pointerEvents: 'none' }}>
      {seeds.map((s, i) => (
        <span key={i} style={{
          position: 'absolute', left: `${s.left}%`, bottom: -20,
          width: s.size, height: s.size, borderRadius: '50%',
          background: `rgba(${color},${s.op})`,
          boxShadow: `0 0 ${6 + s.size * 2}px rgba(${color},${s.op})`,
          ['--dx']: `${s.drift}px`,
          animation: `emberRise ${s.dur}s linear ${s.delay}s infinite`,
        }} />
      ))}
    </div>
  );
}

function Vignette() {
  const tw = useTw();
  const v = tw.vinheta != null ? tw.vinheta : 0.62;
  return (
    <div style={{
      position: 'absolute', inset: 0, pointerEvents: 'none',
      background: `radial-gradient(120% 78% at 50% 42%, transparent 38%, rgba(8,7,3,${v}) 100%)`,
    }} />
  );
}

function Grain() {
  const tw = useTw();
  if (tw.grao === false) return null;
  return (
    <div style={{
      position: 'absolute', inset: 0, pointerEvents: 'none', opacity: 0.06,
      mixBlendMode: 'overlay',
      backgroundImage: "url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='160' height='160'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.85' numOctaves='2'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E\")",
      backgroundSize: '300px 300px',
    }} />
  );
}

// Radial glow that can swell with a local progress (for gancho/CTA)
function Glow({ a, b, x = '50%', y = '46%', scale = 1, op = 1 }) {
  return (
    <div style={{
      position: 'absolute', left: x, top: y, width: 1300, height: 1300,
      transform: `translate(-50%,-50%) scale(${scale})`, opacity: op,
      background: `radial-gradient(circle, ${a} 0%, ${b} 34%, transparent 66%)`,
      pointerEvents: 'none', filter: 'blur(8px)',
    }} />
  );
}

// ════════════════════════════════════════════════════════════════════
//  CENA 1 · GANCHO  (0–8)
// ════════════════════════════════════════════════════════════════════
function S1_Gancho() {
  const tw = useTw();
  const cl = climate(tw.clima);
  const ab = tw.abertura || 'frase';
  return (
    <Sprite start={0} end={8.2}>
      {({ localTime: lt, duration: dur }) => {
        const gO = group(lt, 0, 7.2, 0.6, 1.0);
        const sw = interpolate([0, 4, 8], [0.7, 1.06, 1.18], E.easeInOutSine)(lt);
        return (
          <div style={{ position: 'absolute', inset: 0 }}>
            <div style={{ position: 'absolute', inset: 0, background: C.preto }} />
            <Glow a={cl.glowA} b={cl.glowB} y="52%" scale={sw} op={0.9 * gO} />
            <div style={cx({ position: 'absolute', left: 90, top: 250, width: 900 }, { opacity: gO })}>
              <div style={reveal(lt, 0.3, { rise: 18 })}>
                <Eyebrow>Academia Lendár[IA]</Eyebrow>
              </div>

              {ab === 'pergunta' ? (
                <>
                  <h1 style={mono(116, C.bege, reveal(lt, 0.7, { rise: 40, dur: 0.8 }))}>QUANTO<br />TEMPO<br /><span style={{ color: C.amarelo }}>VOCÊ TEM?</span></h1>
                  <Kara lt={lt} at={3.2} x={2} y={620} width={880} size={44} color={C.fg2}
                    text={'Ele parou de adiar a própria vida. E nomeou o que o prendia.'} out={6.8} />
                </>
              ) : ab === 'nome' ? (
                <>
                  <div style={reveal(lt, 0.7, { rise: 16 })}><Eyebrow color={C.bronze} style={{ marginTop: 26 }}>O Fundador do Movimento</Eyebrow></div>
                  <h1 style={mono(128, C.bege, reveal(lt, 1.0, { rise: 42, dur: 0.8 }))}>ALAN<br /><span style={{ color: C.amarelo }}>NICOLAS</span></h1>
                </>
              ) : (
                <>
                  <h1 style={mono(112, C.bege, reveal(lt, 0.7, { rise: 42, dur: 0.8 }))}>MEDIOCRIDADE</h1>
                  <h1 style={mono(112, C.bege, reveal(lt, 1.5, { rise: 42, dur: 0.8 }))}>É ESCOLHA,</h1>
                  <h1 style={mono(112, C.amarelo, reveal(lt, 2.6, { rise: 42, dur: 0.85 }))}>NÃO DESTINO.</h1>
                </>
              )}
            </div>
            {ab !== 'pergunta' && (
              <div style={cx({ position: 'absolute', left: 92, top: 760 }, reveal(lt, 4.4, { rise: 12, out: 6.8 }))}>
                <Eyebrow color={C.bronze}>Alan Nicolas · O Fundador</Eyebrow>
              </div>
            )}
          </div>
        );
      }}
    </Sprite>
  );
}

// ════════════════════════════════════════════════════════════════════
//  CENA 2 · O FUNDADOR  (8–19)  · vídeo tratado
// ════════════════════════════════════════════════════════════════════
function S2_Fundador() {
  const tw = useTw();
  return (
    <Sprite start={8} end={19.2}>
      {({ localTime: lt, duration: dur }) => {
        let op = 1;
        if (lt < 0.8) op = E.easeOutCubic(lt / 0.8);
        else if (lt > dur - 0.9) op = 1 - E.easeInCubic((lt - (dur - 0.9)) / 0.9);
        const scale = 1.04 + 0.10 * clamp(lt / dur, 0, 1);
        return (
          <div style={{ position: 'absolute', inset: 0, opacity: op, overflow: 'hidden' }}>
            <div style={{ position: 'absolute', inset: 0, overflow: 'hidden' }}>
              <video autoPlay muted loop playsInline poster={IMG('fundador-retrato-em-pe.jpg')}
                style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover', objectPosition: '50% 32%', transform: `scale(${scale})`, transformOrigin: '50% 35%', filter: 'saturate(0.9) contrast(1.05) brightness(0.9)' }}>
                <source src={IMG('fundador-video-hero.mp4')} type="video/mp4" />
              </video>
              <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(180deg, rgba(19,17,9,0.50) 0%, rgba(19,17,9,0.12) 32%, rgba(19,17,9,0.55) 66%, rgba(19,17,9,0.97) 100%)' }} />
            </div>

            <div style={cx({ position: 'absolute', left: 90, top: 110 }, reveal(lt, 0.5, { rise: 16, out: 9.4 }))}>
              <Eyebrow>O Fundador do Movimento Lendário</Eyebrow>
            </div>

            <div style={{ position: 'absolute', left: 86, top: 1180 }}>
              <h1 style={mono(150, C.bege, reveal(lt, 1.0, { rise: 50, dur: 0.8, out: 9.6 }))}>ALAN</h1>
              <h1 style={mono(150, C.amarelo, reveal(lt, 1.5, { rise: 50, dur: 0.85, out: 9.6 }))}>NICOLAS</h1>
            </div>

            <Kara lt={lt} at={3.4} x={90} y={1500} width={900} size={45} color={C.fg2}
              text={'Conheça o homem que transformou a recusa da mediocridade em um movimento.'} out={9.6} />
          </div>
        );
      }}
    </Sprite>
  );
}

// ════════════════════════════════════════════════════════════════════
//  CENA 3 · A ORIGEM / O CHUMBO  (19–32)
// ════════════════════════════════════════════════════════════════════
function S3_Chumbo() {
  return (
    <Sprite start={19} end={32.2}>
      {({ localTime: lt, duration: dur }) => (
        <div style={{ position: 'absolute', inset: 0 }}>
          <Bg src={IMG('fundador-retrato-sentado.jpg')} lt={lt} dur={dur} fx="58%" fy="30%"
            from={1.04} to={1.16}
            veil={'linear-gradient(180deg, rgba(19,17,9,0.40) 0%, rgba(19,17,9,0.30) 26%, rgba(19,17,9,0.72) 60%, rgba(19,17,9,0.97) 100%)'} />

          <div style={cx({ position: 'absolute', left: 90, top: 120 }, reveal(lt, 0.4, { rise: 16, out: 11.6 }))}>
            <Eyebrow color={C.bronze}>A Origem · O Chumbo</Eyebrow>
          </div>
          <div style={{ position: 'absolute', left: 86, top: 172 }}>
            <h1 style={mono(84, C.bege, cx(reveal(lt, 0.7, { rise: 34, out: 11.6 }), { lineHeight: 1.02 }))}>ANTES DO OURO,<br /><span style={{ color: C.bronzeC }}>O CHUMBO</span></h1>
          </div>

          <div style={{ position: 'absolute', left: 90, top: 1140, width: 910 }}>
            <Kara lt={lt} at={2.4} x={0} y={0} size={47} color={C.bege}
              text={'1990. Um bairro pobre no Rio Grande do Sul. Aluno mediano, notas baixas, que odiava ler.'} out={11.4} />
            <Kara lt={lt} at={5.4} x={0} y={210} size={47} color={C.bege}
              text={'Em 2015, a primeira falência: dez mil negativos no cheque especial, todo mês.'} out={11.4} />
          </div>

          <div style={cx({ position: 'absolute', left: 90, top: 1560, width: 910 }, reveal(lt, 8.4, { rise: 24, dur: 0.7, out: 11.4 }))}>
            <div style={{ fontFamily: FONT.sag, fontSize: 30, letterSpacing: '0.06em', color: C.fg2, marginBottom: 10 }}>O conformismo ofereceu a saída fácil.</div>
            <div style={{ fontFamily: FONT.mon, fontSize: 92, color: C.amarelo, letterSpacing: '-0.02em', lineHeight: 0.95 }}>ELE RECUSOU.</div>
          </div>
        </div>
      )}
    </Sprite>
  );
}

// ════════════════════════════════════════════════════════════════════
//  CENA 4 · O INIMIGO  (32–45)  · VERMELHO / sombra
// ════════════════════════════════════════════════════════════════════
function S4_Inimigo() {
  return (
    <Sprite start={32} end={45.2}>
      {({ localTime: lt, duration: dur }) => {
        const shake = lt > 3.0 && lt < 4.4 ? Math.sin(lt * 60) * (1 - (lt - 3.0) / 1.4) * 5 : 0;
        return (
          <div style={{ position: 'absolute', inset: 0 }}>
            <Bg src={IMG('fundador-microfone.jpg')} lt={lt} dur={dur} fx="46%" fy="32%"
              from={1.06} to={1.2} tint={'rgba(120,8,8,0.34)'} grade={0.86}
              veil={'linear-gradient(180deg, rgba(19,17,9,0.55) 0%, rgba(19,17,9,0.28) 30%, rgba(20,6,6,0.66) 64%, rgba(14,4,4,0.97) 100%)'} />

            <div style={cx({ position: 'absolute', left: 90, top: 120 }, reveal(lt, 0.4, { rise: 16, out: 11.8 }))}>
              <Eyebrow color={C.vermelho}>A Declaração de Guerra</Eyebrow>
            </div>

            <Kara lt={lt} at={1.0} x={90} y={1010} width={900} size={46} color={C.bege}
              text={'No fim de 2019, no primeiro episódio do podcast Vida Lendária, ele encarou a voz que o chamava de apenas mais um.'} out={11.6} />

            <div style={{ position: 'absolute', left: 84, top: 1330, transform: `translateX(${shake}px)` }}>
              <div style={cx({ fontFamily: FONT.sag, fontSize: 27, letterSpacing: '0.16em', color: C.fg2, textTransform: 'uppercase', marginBottom: 8 }, reveal(lt, 2.6, { rise: 14, out: 11.6 }))}>E nomeou o inimigo</div>
              <h1 style={mono(86, C.vermelho, cx(reveal(lt, 3.0, { rise: 30, dur: 0.5, out: 11.6 }), { whiteSpace: 'nowrap', textShadow: '0 0 40px rgba(230,57,70,0.4)' }))}>O CONFORMISMO</h1>
            </div>

            <div style={cx({ position: 'absolute', left: 90, top: 1620, width: 900 }, reveal(lt, 6.6, { rise: 18, out: 11.6 }))}>
              <div style={{ fontFamily: FONT.op, fontStyle: 'italic', fontSize: 42, color: C.bege, lineHeight: 1.25 }}>"Eu não sou mais o seu refém."</div>
              <div style={{ fontFamily: FONT.sag, fontSize: 21, letterSpacing: '0.22em', color: C.bronze, marginTop: 12, textTransform: 'uppercase' }}>Alan Nicolas</div>
            </div>
          </div>
        );
      }}
    </Sprite>
  );
}

// ════════════════════════════════════════════════════════════════════
//  CENA 5 · O MOVIMENTO / O LEGADO  (45–70)  · FOCO · luz
// ════════════════════════════════════════════════════════════════════
const FRENTES = [
  ['Academia Lendár[IA]', 'A escola-Forja onde os inconformados atravessam o fogo.'],
  ['Vida Lendária', 'O podcast onde a guerra ao conformismo começou.'],
  ['AIOX', 'O squad de inteligência artificial do Movimento.'],
  ['Mente Lendária', 'Um segundo cérebro potencializado por IA.'],
];
const STATS = [
  ['128', 'Livros em um ano'],
  ['10', 'Valores em ordem'],
  ['04', 'Frentes do Movimento'],
];

function S5_Movimento() {
  return (
    <Sprite start={45} end={70.3}>
      {({ localTime: lt, duration: dur }) => {
        const oA = group(lt, 0, 7.4, 0.7, 0.8);   // intro
        const oB = group(lt, 7.6, 16.2, 0.7, 0.8);  // frentes
        const oC = group(lt, 16.4, 25.2, 0.7, 0.9);  // stats + fecho
        return (
          <div style={{ position: 'absolute', inset: 0 }}>
            <Bg src={IMG('fundador-laptop-quente.jpg')} lt={lt} dur={dur} fx="52%" fy="36%"
              from={1.05} to={1.16} grade={0.82}
              veil={'linear-gradient(180deg, rgba(19,17,9,0.78) 0%, rgba(19,17,9,0.55) 40%, rgba(19,17,9,0.80) 72%, rgba(19,17,9,0.97) 100%)'} />

            {/* A · intro */}
            <div style={{ position: 'absolute', inset: 0, opacity: oA }}>
              <div style={cx({ position: 'absolute', left: 90, top: 300 }, reveal(lt, 0.4, { rise: 16 }))}>
                <Eyebrow>O Que Ele Construiu</Eyebrow>
              </div>
              <div style={{ position: 'absolute', left: 84, top: 350 }}>
                <h1 style={mono(132, C.bege, reveal(lt, 0.7, { rise: 44, dur: 0.8 }))}>O MOVIMENTO</h1>
                <h1 style={mono(132, C.amarelo, reveal(lt, 1.2, { rise: 44, dur: 0.85 }))}>LENDÁRIO</h1>
              </div>
              <Kara lt={lt} at={3.0} x={90} y={830} width={920} size={46} color={C.fg2}
                text={'A recusa coletiva da mediocridade, repetida dia após dia. O que era jornada de um virou caminho de muitos.'} />
            </div>

            {/* B · 4 frentes */}
            <div style={{ position: 'absolute', inset: 0, opacity: oB }}>
              <div style={cx({ position: 'absolute', left: 90, top: 250 }, reveal(lt, 7.7, { rise: 14 }))}>
                <Eyebrow color={C.bronze}>As Quatro Frentes</Eyebrow>
              </div>
              <div style={{ position: 'absolute', left: 86, top: 360, right: 80 }}>
                {FRENTES.map((f, i) => {
                  const at = 8.0 + i * 0.85;
                  const st = reveal(lt, at, { rise: 30, dur: 0.6 });
                  return (
                    <div key={i} style={cx({ borderTop: `1px solid rgba(154,125,86,0.42)`, padding: '26px 0 24px' }, st)}>
                      <div style={{ display: 'flex', alignItems: 'baseline', gap: 22 }}>
                        <span style={{ fontFamily: FONT.sag, fontSize: 26, color: C.amarelo, letterSpacing: '0.1em', minWidth: 52 }}>{`0${i + 1}`}</span>
                        <span style={{ fontFamily: FONT.mon, fontSize: 46, color: C.bege, letterSpacing: '-0.01em', lineHeight: 1, whiteSpace: 'nowrap' }}>{f[0]}</span>
                      </div>
                      <div style={{ fontFamily: FONT.op, fontSize: 33, color: C.fg2, marginLeft: 74, marginTop: 6, lineHeight: 1.22 }}>{f[1]}</div>
                    </div>
                  );
                })}
              </div>
            </div>

            {/* C · stats + fecho */}
            <div style={{ position: 'absolute', inset: 0, opacity: oC }}>
              <div style={cx({ position: 'absolute', left: 90, top: 360 }, reveal(lt, 16.6, { rise: 14 }))}>
                <Eyebrow color={C.bronze}>O Legado em Números</Eyebrow>
              </div>
              <div style={{ position: 'absolute', left: 86, top: 430, right: 80, display: 'flex', flexDirection: 'column', gap: 4 }}>
                {STATS.map((s, i) => {
                  const at = 16.9 + i * 0.5;
                  const st = reveal(lt, at, { rise: 26, dur: 0.6 });
                  const val = s[0] === '128' ? String(counter(lt, at + 0.1, 128, 1.3))
                    : s[0] === '10' ? String(counter(lt, at + 0.1, 10, 1.0)).padStart(2, '0')
                    : s[0];
                  return (
                    <div key={i} style={cx({ display: 'flex', alignItems: 'baseline', gap: 30, borderBottom: '1px solid rgba(154,125,86,0.30)', padding: '18px 0' }, st)}>
                      <span style={{ fontFamily: FONT.mon, fontSize: 116, color: C.amarelo, letterSpacing: '-0.03em', lineHeight: 0.9, minWidth: 240 }}>{val}</span>
                      <span style={{ fontFamily: FONT.sag, fontSize: 34, color: C.bege, letterSpacing: '0.04em' }}>{s[1]}</span>
                    </div>
                  );
                })}
              </div>
              <div style={cx({ position: 'absolute', left: 90, top: 1180, width: 920 }, reveal(lt, 19.4, { rise: 22, dur: 0.7 }))}>
                <div style={{ fontFamily: FONT.sag, fontSize: 30, letterSpacing: '0.06em', color: C.fg2, marginBottom: 14 }}>A missão, declarada sem rodeios:</div>
                <div style={{ fontFamily: FONT.mon, fontSize: 88, color: C.bege, letterSpacing: '-0.02em', lineHeight: 0.98 }}>FORJAR LENDÁRIOS<br /><span style={{ color: C.amarelo }}>EM ESCALA.</span></div>
                <div style={{ fontFamily: FONT.op, fontStyle: 'italic', fontSize: 40, color: C.fg2, marginTop: 24, lineHeight: 1.3 }}>Para que o fogo siga aceso depois de quem o acendeu.</div>
              </div>
            </div>
          </div>
        );
      }}
    </Sprite>
  );
}

// ════════════════════════════════════════════════════════════════════
//  CENA 6 · A DOUTRINA  (70–81)
// ════════════════════════════════════════════════════════════════════
function S6_Doutrina() {
  return (
    <Sprite start={70} end={81.2}>
      {({ localTime: lt, duration: dur }) => (
        <div style={{ position: 'absolute', inset: 0 }}>
          <Bg src={IMG('fundador-ampulheta.jpg')} lt={lt} dur={dur} fx="50%" fy="34%"
            from={1.05} to={1.16} grade={0.8}
            veil={'linear-gradient(180deg, rgba(19,17,9,0.72) 0%, rgba(19,17,9,0.50) 36%, rgba(19,17,9,0.80) 70%, rgba(19,17,9,0.97) 100%)'} />

          <div style={cx({ position: 'absolute', left: 90, top: 300 }, reveal(lt, 0.4, { rise: 16, out: 9.6 }))}>
            <Eyebrow color={C.bronze}>A Doutrina · O Ser Antes do Ter</Eyebrow>
          </div>

          <div style={{ position: 'absolute', left: 86, top: 660 }}>
            <h1 style={mono(84, C.bege, cx(reveal(lt, 1.0, { rise: 40, out: 9.6 }), { whiteSpace: 'normal', lineHeight: 1.0 }))}>NÃO TENTA<br />SER O MELHOR.</h1>
          </div>
          <div style={{ position: 'absolute', left: 86, top: 920 }}>
            <h1 style={mono(116, C.amarelo, cx(reveal(lt, 3.0, { rise: 46, dur: 0.7, out: 9.6 }), { lineHeight: 0.98, textShadow: '0 0 44px rgba(246,195,36,0.35)' }))}>TENTA SER<br />O ÚNICO.</h1>
          </div>

          <div style={cx({ position: 'absolute', left: 90, top: 1500 }, reveal(lt, 5.4, { rise: 16, out: 9.6 }))}>
            <div style={{ fontFamily: FONT.sag, fontSize: 23, letterSpacing: '0.22em', color: C.bronze, textTransform: 'uppercase' }}>Alan Nicolas · O Fundador</div>
          </div>
        </div>
      )}
    </Sprite>
  );
}

// ════════════════════════════════════════════════════════════════════
//  CENA 7 · CTA  (81–90)
// ════════════════════════════════════════════════════════════════════
function S7_CTA() {
  const tw = useTw();
  const cl = climate(tw.clima);
  return (
    <Sprite start={81} end={90}>
      {({ localTime: lt, duration: dur }) => {
        const gO = group(lt, 0, 8.4, 0.7, 0.6);
        const sw = interpolate([0, 4, 9], [0.75, 1.05, 1.16], E.easeOutSine)(lt);
        return (
          <div style={{ position: 'absolute', inset: 0, background: C.preto }}>
            <Glow a={cl.glowA} b={cl.glowB} y="40%" scale={sw} op={0.8 * gO} />

            <div style={cx({ position: 'absolute', left: '50%', top: 430, transform: 'translateX(-50%)' }, reveal(lt, 0.5, { rise: 24, dur: 0.8 }))}>
              <Logo size={200} color={C.amarelo} />
            </div>

            <div style={cx({ position: 'absolute', left: 0, right: 0, top: 720, textAlign: 'center' }, reveal(lt, 1.4, { rise: 18 }))}>
              <Eyebrow color={C.bronze} style={{ textAlign: 'center' }}>O fogo segue aceso</Eyebrow>
            </div>

            <div style={{ position: 'absolute', left: 70, right: 70, top: 800, textAlign: 'center' }}>
              <h1 style={mono(96, C.bege, cx(reveal(lt, 1.9, { rise: 40, dur: 0.8 }), { textAlign: 'center' }))}>ENTRE NO</h1>
              <h1 style={mono(96, C.amarelo, cx(reveal(lt, 2.4, { rise: 40, dur: 0.85 }), { textAlign: 'center', textShadow: '0 0 44px rgba(246,195,36,0.3)' }))}>MOVIMENTO<br />LENDÁRIO</h1>
            </div>

            <div style={cx({ position: 'absolute', left: 0, right: 0, top: 1340, textAlign: 'center' }, reveal(lt, 3.6, { rise: 16 }))}>
              <div style={{ fontFamily: FONT.sag, fontSize: 30, letterSpacing: '0.18em', color: C.bege, textTransform: 'uppercase' }}>@academialendaria</div>
              <div style={{ fontFamily: FONT.sag, fontSize: 24, letterSpacing: '0.16em', color: C.bronze, marginTop: 14 }}>alanicolas.com</div>
            </div>
          </div>
        );
      }}
    </Sprite>
  );
}

// ── style helpers ──────────────────────────────────────────────────
function mono(size, color, extra = {}) {
  return { fontFamily: FONT.mon, fontSize: size, color, letterSpacing: '-0.02em', lineHeight: 0.94, margin: 0, ...extra };
}
function cx(a, b) { return { ...a, ...b }; }
function cap() { return {}; } // placeholder (unused styling hook)

// ── Logo (marca recolorida via fetch + inject; máscara como fallback) ──
function Logo({ size = 200, color = C.amarelo }) {
  const ref = React.useRef(null);
  React.useEffect(() => {
    let alive = true;
    fetch('../assets/brand/logo-academialendaria.svg')
      .then((r) => r.text())
      .then((txt) => {
        if (!alive || !ref.current) return;
        const svg = txt
          .replace(/fill="white"/g, `fill="${color}"`)
          .replace('<svg ', '<svg style="width:100%;height:100%;display:block" ');
        ref.current.innerHTML = svg;
      })
      .catch(() => {});
    return () => { alive = false; };
  }, [color]);
  return (
    <div ref={ref} style={{ width: size, height: size }} />
  );
}

// ════════════════════════════════════════════════════════════════════
//  Root scenes + atmosphere
// ════════════════════════════════════════════════════════════════════
function Scenes() {
  const tw = useTw();
  const cl = climate(tw.clima);
  const time = useTime();
  const tl = useTimeline();
  React.useEffect(() => { window.__seek = (s) => { tl.setPlaying(false); tl.setTime(s); }; }, [tl]);
  React.useEffect(() => {
    const el = document.getElementById('video-root');
    if (el) el.dataset.screenLabel = `t=${Math.floor(time)}s`;
  }, [Math.floor(time)]);
  return (
    <div style={{ position: 'absolute', inset: 0, background: C.preto }}>
      <S1_Gancho />
      <S2_Fundador />
      <S3_Chumbo />
      <S4_Inimigo />
      <S5_Movimento />
      <S6_Doutrina />
      <S7_CTA />
      <Embers color={cl.ember} />
      <Vignette />
      <Grain />
    </div>
  );
}

Object.assign(window, { C, FONT, TW, useTw, climate, reveal, group, counter, Kara, Bg, Eyebrow, Embers, Vignette, Grain, Glow, Logo, Scenes,
  S1_Gancho, S2_Fundador, S3_Chumbo, S4_Inimigo, S5_Movimento, S6_Doutrina, S7_CTA });
