// Act 3 — AI learning differentiator (20–32s)
function Act3AI() {
  return (
    <Sprite start={20.0} end={32.0}>
      <Act3Inner />
    </Sprite>
  );
}

function Act3Inner() {
  const { localTime: t } = useSprite();

  return (
    <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(180deg, #0f0f0f 0%, #000 100%)', overflow: 'hidden' }}>
      {/* Multi-idioma chip — 2s breve, no persistente, no revela método */}
      {t < 2.0 && (
        <div style={{ position: 'absolute', top: 28, right: 32, padding: '6px 12px', background: 'rgba(234,88,12,0.08)', border: '1px solid rgba(234,88,12,0.3)', borderRadius: 999, fontFamily: 'JetBrains Mono, monospace', fontSize: 16, color: '#F59E0B', letterSpacing: '0.08em', textTransform: 'uppercase', display: 'flex', alignItems: 'center', gap: 8, zIndex: 5, opacity: t < 0.3 ? Easing.easeOutCubic(t/0.3) : t > 1.7 ? Easing.easeInCubic(clamp((2.0 - t) / 0.3, 0, 1)) : 1 }}>
          🌐 español · català · english
        </div>
      )}

      {/* Title */}
      {t < 1.0 && <Act3Title t={t} />}

      {/* Phase 1: Learning curve (1.0–4.0s) */}
      {t >= 1.0 && t < 4.0 && <LearningCurve t={t - 1.0} />}

      {/* Phase 2: Hook A/B (4.0–6.5s) */}
      {t >= 4.0 && t < 6.5 && <HookAB t={t - 4.0} />}

      {/* Phase 3: PRO+ Entrena tu IA (6.5–11.5s, 5s para leer 3 traits) */}
      {t >= 6.5 && t < 11.5 && <TrainYourAI t={t - 6.5} />}

      <CueLayer t={t} cues={[
        { t: 1.0, end: 4.0, es: 'Mejora con cada clip que publicas.', en: 'Sharper with every clip you post.' },
        { t: 4.0, end: 6.5, es: 'Y replica el hook que funcionó.', en: 'And replays the hook that worked.' },
        { t: 6.5, end: 11.5, es: 'PRO+: una IA exclusiva para tu canal.', en: 'PRO+: an AI dedicated to your channel.' },
      ]} />
    </div>
  );
}

function Act3Title({ t }) {
  if (t > 1.4) return null;
  const opacity = t < 0.3 ? t / 0.3 : t > 1.0 ? Math.max(0, (1.4 - t) / 0.4) : 1;
  return (
    <div style={{ position: 'absolute', top: 60, left: 0, right: 0, textAlign: 'center', opacity }}>
      <div style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 16, color: '#F59E0B', letterSpacing: '0.16em', textTransform: 'uppercase' }}>
        diferenciador · IA personalizada
      </div>
    </div>
  );
}

function LearningCurve({ t }) {
  const opacity = t < 0.3 ? t / 0.3 : t > 3.0 ? Math.max(0, (3.5 - t) / 0.5) : 1;
  const points = 30;
  // Faster drawing: complete by t=2.0 (was 3.5) so the curve doesn't drag.
  const drawProgress = Math.min(1, t / 2.0);

  // Generate learning curve (rising with noise)
  const xs = Array.from({ length: points }, (_, i) => 80 + (i / (points - 1)) * 940);
  const ys = Array.from({ length: points }, (_, i) => {
    const x = i / (points - 1);
    const y = 220 - Math.pow(x, 0.5) * 160 + (Math.sin(i * 1.7) * 8);
    return y;
  });

  // Continuous draw: full integer segments + a partial last segment so the
  // line grows pixel-by-pixel instead of jumping point-to-point.
  const totalSeg = points - 1;
  const segF = drawProgress * totalSeg;
  const fullSeg = Math.floor(segF);
  const frac = segF - fullSeg;

  let path = '';
  let headX = xs[0];
  let headY = ys[0];
  if (fullSeg < 1 && frac > 0) {
    // Just starting — only a partial first segment.
    headX = xs[0] + (xs[1] - xs[0]) * frac;
    headY = ys[0] + (ys[1] - ys[0]) * frac;
    path = `M${xs[0]} ${ys[0]} L${headX} ${headY}`;
  } else {
    for (let i = 0; i <= fullSeg; i++) {
      path += (i === 0 ? 'M' : 'L') + xs[i] + ' ' + ys[i] + ' ';
      headX = xs[i]; headY = ys[i];
    }
    if (fullSeg < totalSeg && frac > 0) {
      const nx = xs[fullSeg] + (xs[fullSeg + 1] - xs[fullSeg]) * frac;
      const ny = ys[fullSeg] + (ys[fullSeg + 1] - ys[fullSeg]) * frac;
      path += `L${nx} ${ny}`;
      headX = nx; headY = ny;
    }
  }

  // Sin claim cuantitativo: la curva muestra mejora cualitativa, sin números.

  return (
    <div style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', opacity }}>
      <div style={{ width: 1100, padding: 28, background: 'rgba(255,255,255,0.03)', border: '1px solid rgba(255,255,255,0.08)', borderRadius: 20 }}>
        <div style={{ marginBottom: 24, fontFamily: 'Inter, system-ui, sans-serif' }}>
          <div style={{ color: 'rgba(255,255,255,0.5)', fontSize: 16, letterSpacing: '0.1em', textTransform: 'uppercase', marginBottom: 8, fontFamily: 'JetBrains Mono, monospace' }}>Curva de aprendizaje</div>
          <div style={{ color: '#fff', fontSize: 48, fontWeight: 800, letterSpacing: '-0.025em', lineHeight: 1.05 }}>Cada clip que publicas, <span style={{ color: '#F59E0B' }}>la IA mejora</span>.</div>
        </div>
        <svg width="1044" height="260" style={{ display: 'block' }}>
          <defs>
            <linearGradient id="curve-grad" x1="0" y1="0" x2="0" y2="1">
              <stop offset="0%" stopColor="#EA580C" stopOpacity="0.35"/>
              <stop offset="100%" stopColor="#EA580C" stopOpacity="0"/>
            </linearGradient>
          </defs>
          {/* Grid */}
          {[0, 1, 2, 3, 4].map(i => (
            <line key={i} x1={80} x2={1020} y1={60 + i * 40} y2={60 + i * 40} stroke="rgba(255,255,255,0.05)" strokeWidth="1" />
          ))}
          {/* Fill area */}
          {drawProgress > 0.02 && (
            <path d={path + ` L ${headX} 240 L ${xs[0]} 240 Z`} fill="url(#curve-grad)" />
          )}
          {/* Curve */}
          <path d={path} fill="none" stroke="#EA580C" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round" />
          {/* Active point */}
          {drawProgress > 0.02 && (
            <circle cx={headX} cy={headY} r="6" fill="#F59E0B" stroke="#fff" strokeWidth="2" />
          )}
          {/* Y axis label — cualitativo, sin múltiplos numéricos */}
          <text x={60} y={75} fill="rgba(255,255,255,0.4)" fontSize="14" fontFamily="JetBrains Mono, monospace" textAnchor="end">engagement</text>
          <text x={80} y={258} fill="rgba(255,255,255,0.4)" fontSize="14" fontFamily="JetBrains Mono, monospace">primer clip</text>
          <text x={1020} y={258} fill="rgba(255,255,255,0.4)" fontSize="14" fontFamily="JetBrains Mono, monospace" textAnchor="end">tras meses publicando</text>
        </svg>
      </div>
    </div>
  );
}

function HookAB({ t }) {
  const opacity = t < 0.3 ? t / 0.3 : t > 2.5 ? Math.max(0, (3.0 - t) / 0.5) : 1;
  const showV2 = t > 1.0;
  const showResult = t > 2.5;

  return (
    <div style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', flexDirection: 'column', gap: 24, opacity }}>
      <div style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 16, color: '#F59E0B', letterSpacing: '0.12em', textTransform: 'uppercase' }}>
        hooks · qué titular gana
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 14, width: 900 }}>
        <HookRow
          version="V1"
          text="Aquí está el momento."
          barW={0.18}
          status="loser"
          visible={true}
        />
        {showV2 && (
          <HookRow
            version="V2"
            text="¿Sabes qué pasó después?"
            barW={0.92}
            status="winner"
            visible={true}
          />
        )}
      </div>
      {showResult && (
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, opacity: Math.min(1, (t - 2.5) * 3), padding: '10px 18px', background: 'rgba(234,88,12,0.1)', border: '1px solid rgba(234,88,12,0.3)', borderRadius: 999 }}>
          <span style={{ fontSize: 18 }}>💡</span>
          <span style={{ fontFamily: 'Inter, system-ui, sans-serif', fontSize: 15, color: '#F59E0B', fontWeight: 600 }}>Y lo replica automáticamente.</span>
        </div>
      )}
    </div>
  );
}

function HookRow({ version, text, barW, status, visible }) {
  const isWinner = status === 'winner';
  return (
    <div style={{
      padding: '18px 24px',
      background: isWinner ? 'rgba(234,88,12,0.08)' : 'rgba(255,255,255,0.02)',
      border: `1px solid ${isWinner ? 'rgba(234,88,12,0.4)' : 'rgba(255,255,255,0.08)'}`,
      borderRadius: 14,
      display: 'flex', alignItems: 'center', gap: 20,
      fontFamily: 'Inter, system-ui, sans-serif',
    }}>
      <div style={{
        padding: '6px 12px',
        background: isWinner ? '#EA580C' : 'rgba(255,255,255,0.06)',
        color: isWinner ? '#fff' : 'rgba(255,255,255,0.5)',
        borderRadius: 6,
        fontFamily: 'JetBrains Mono, monospace', fontSize: 14, fontWeight: 700,
        letterSpacing: '0.06em',
      }}>{version}</div>
      <div style={{ flex: 1, fontSize: 22, fontWeight: 600, color: isWinner ? '#fff' : 'rgba(255,255,255,0.55)', letterSpacing: '-0.01em' }}>
        "{text}"
      </div>
      {/* Barra relativa — sin claim numérico absoluto */}
      <div style={{ width: 240, height: 18, background: 'rgba(255,255,255,0.06)', borderRadius: 9, overflow: 'hidden' }}>
        <div style={{
          width: `${barW * 100}%`,
          height: '100%',
          background: isWinner ? 'linear-gradient(90deg, #EA580C, #F59E0B)' : 'rgba(255,255,255,0.18)',
          borderRadius: 9,
        }} />
      </div>
      <div style={{ fontSize: 22 }}>{isWinner ? '✅' : '❌'}</div>
    </div>
  );
}

// ── Phase 4 · PRO — Entrena tu IA ────────────────────────────────────────────
// Dedica un momento a la propuesta de valor PRO: una IA que conoce tu canal
// (bromas, audiencia, forma de hablar, qué triunfa).
function TrainYourAI({ t }) {
  const opacity = t < 0.4 ? t / 0.4 : t > 4.3 ? Math.max(0, (4.8 - t) / 0.5) : 1;
  // Pulsar PRO badge
  const proPulse = 0.85 + Math.sin(t * 3) * 0.15;

  const traits = [
    { tag: '01', icon: '🎙️', label: 'Tu voz',         desc: 'humor, ritmo, muletillas' },
    { tag: '02', icon: '👥', label: 'Tu audiencia',  desc: 'qué responden tus fans' },
    { tag: '03', icon: '🚀', label: 'Lo que triunfa', desc: 'replica los hooks que ganan' },
  ];

  return (
    <div style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', flexDirection: 'column', gap: 30, opacity, padding: '80px 60px' }}>
      {/* PRO seal */}
      <div style={{
        display: 'flex', alignItems: 'center', gap: 14,
        padding: '12px 22px',
        background: 'linear-gradient(90deg, rgba(144,97,249,0.18), rgba(234,88,12,0.12))',
        border: '2px solid rgba(144,97,249,0.5)',
        borderRadius: 999,
        fontFamily: 'JetBrains Mono, monospace',
        fontSize: 16,
        color: '#fff',
        letterSpacing: '0.18em',
        textTransform: 'uppercase',
        fontWeight: 700,
        boxShadow: `0 0 ${20 + proPulse * 30}px rgba(144,97,249,${0.3 + proPulse * 0.2})`,
        transform: `scale(${0.97 + proPulse * 0.05})`,
      }}>
        <ProSealBolt /> exclusivo plan PRO+
      </div>

      {/* Headline */}
      <div style={{ textAlign: 'center', maxWidth: 1200 }}>
        <div style={{
          fontFamily: 'Inter, system-ui, sans-serif',
          fontSize: 72,
          fontWeight: 800,
          color: '#fff',
          letterSpacing: '-0.03em',
          lineHeight: 1.05,
        }}>
          Una IA que <span style={{ background: 'linear-gradient(90deg, #9061f9, #F59E0B)', WebkitBackgroundClip: 'text', WebkitTextFillColor: 'transparent', backgroundClip: 'text' }}>conoce tu canal</span>.
        </div>
        <div style={{
          fontFamily: 'Inter, system-ui, sans-serif',
          fontSize: 22,
          color: 'rgba(255,255,255,0.6)',
          marginTop: 16,
          lineHeight: 1.4,
          letterSpacing: '-0.005em',
        }}>
          Entrenada únicamente con tus vídeos, tus clips ganadores y la reacción real de tu audiencia.
        </div>
      </div>

      {/* Trait grid */}
      <div style={{ display: 'flex', gap: 16, marginTop: 8 }}>
        {traits.map((tr, i) => {
          const delay = 0.3 + i * 0.22;
          const local = t - delay;
          const ease = Easing.easeOutBack(clamp(local * 3, 0, 1));
          return (
            <div key={i} style={{
              width: 340,
              padding: '28px 28px',
              background: 'rgba(144,97,249,0.06)',
              border: '1px solid rgba(144,97,249,0.25)',
              borderRadius: 16,
              fontFamily: 'Inter, system-ui, sans-serif',
              opacity: ease,
              transform: `translateY(${(1 - ease) * 20}px)`,
            }}>
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 18 }}>
                <div style={{ fontSize: 38, lineHeight: 1 }}>{tr.icon}</div>
                <div style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 16, color: '#9061f9', letterSpacing: '0.18em', fontWeight: 700 }}>{tr.tag}</div>
              </div>
              <div style={{ fontSize: 22, fontWeight: 700, color: '#fff', letterSpacing: '-0.01em', marginBottom: 6, lineHeight: 1.15 }}>{tr.label}</div>
              <div style={{ fontSize: 14, color: 'rgba(255,255,255,0.55)', lineHeight: 1.45 }}>{tr.desc}</div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

function ProSealBolt() {
  return (
    <svg width="18" height="18" viewBox="0 0 100 100">
      <defs>
        <linearGradient id="pro-seal-grad" x1="0" y1="0" x2="1" y2="1">
          <stop offset="0%" stopColor="#9061f9"/>
          <stop offset="100%" stopColor="#F59E0B"/>
        </linearGradient>
      </defs>
      <path d="M55 8 L25 52 L48 52 L42 92 L75 42 L52 42 Z" fill="url(#pro-seal-grad)" />
    </svg>
  );
}

window.Act3AI = Act3AI;
