// Scenes 1-5 for Yohann Escher hero motion.

// ── SCENE 1: Intention dot + emerging modules (0 - 3.5s) ──────────────────
function Scene1() {
  const { localTime } = useSprite();
  const cx = 960, cy = 500;

  // First 1.5s: just the dot. Then modules appear.
  const modules = [
    { label: 'Ideia',       icon: Icons.spark, angle: -90, dist: 220, delay: 1.6 },
    { label: 'Produto',     icon: Icons.bolt,  angle: -30, dist: 240, delay: 1.8 },
    { label: 'Cliente',     icon: Icons.user,  angle:  30, dist: 230, delay: 2.0 },
    { label: 'Conteúdo',    icon: Icons.doc,   angle:  90, dist: 220, delay: 2.2 },
    { label: 'Venda',       icon: Icons.chart, angle: 150, dist: 240, delay: 2.4 },
    { label: 'Atendimento', icon: Icons.msg,   angle: 210, dist: 230, delay: 2.6 },
  ];

  return (
    <React.Fragment>
      <Glow x={cx} y={cy} size={500} opacity={0.5}/>
      <PulseDot x={cx} y={cy} size={18}/>

      {modules.map((m, i) => {
        const rad = m.angle * Math.PI / 180;
        const x = cx + Math.cos(rad) * m.dist;
        const y = cy + Math.sin(rad) * m.dist;
        return (
          <ModuleChip key={i} x={x} y={y} label={m.label} icon={m.icon}
            delay={m.delay} driftX={3} driftY={3} driftFreq={0.6}/>
        );
      })}

      <Eyebrow y={140}>Cena 01 — Intenção</Eyebrow>
      <SceneCaption y={920}>
        Todo crescimento começa com uma <Em>intenção</Em>.
      </SceneCaption>
    </React.Fragment>
  );
}

// ── SCENE 2: Fragmentation (3.5 - 7s) ─────────────────────────────────────
function Scene2() {
  const { localTime } = useSprite();
  const t = useTime();

  // 12 modules scattered with broken connections
  const mods = [
    { label: 'Posts',      icon: Icons.doc,    x: 280, y: 320, delay: 0.0 },
    { label: 'Tráfego',    icon: Icons.chart,  x: 520, y: 220, delay: 0.1 },
    { label: 'WhatsApp',   icon: Icons.msg,    x: 780, y: 280, delay: 0.2 },
    { label: 'CRM',        icon: Icons.user,   x: 1100, y: 220, delay: 0.3 },
    { label: 'Planilhas',  icon: Icons.doc,    x: 1380, y: 300, delay: 0.4 },
    { label: 'Reuniões',   icon: Icons.cal,    x: 1640, y: 380, delay: 0.5 },
    { label: 'Leads',      icon: Icons.user,   x: 320, y: 560, delay: 0.6 },
    { label: 'Follow-up',  icon: Icons.msg,    x: 620, y: 660, delay: 0.7 },
    { label: 'Analytics',  icon: Icons.chart,  x: 940, y: 720, delay: 0.8 },
    { label: 'Campanhas',  icon: Icons.bolt,   x: 1240, y: 660, delay: 0.9 },
    { label: 'E-mails',    icon: Icons.msg,    x: 1540, y: 580, delay: 1.0 },
    { label: 'Tarefas',    icon: Icons.cog,    x: 1700, y: 720, delay: 1.1 },
  ];

  // Broken connections between random pairs
  const broken = [
    [0, 1], [1, 2], [2, 3], [3, 4], [4, 5],
    [6, 7], [7, 8], [8, 9], [9, 10], [10, 11],
    [0, 6], [3, 9], [5, 11], [1, 7],
  ];

  // micro-text errors
  const microTexts = [
    { text: 'lead perdido',         x: 410, y: 615, delay: 1.6 },
    { text: 'follow-up atrasado',   x: 760, y: 715, delay: 1.9 },
    { text: 'dados espalhados',     x: 1340, y: 705, delay: 2.2 },
    { text: 'campanha sem leitura', x: 1480, y: 230, delay: 2.5 },
  ];

  return (
    <React.Fragment>
      {broken.map(([a, b], i) => (
        <ConnectLine key={i}
          x1={mods[a].x} y1={mods[a].y} x2={mods[b].x} y2={mods[b].y}
          start={1.2 + i * 0.05} drawDur={0.4}
          color="rgba(255,255,255,0.18)" broken
        />
      ))}

      {mods.map((m, i) => (
        <ModuleChip key={i} x={m.x} y={m.y} label={m.label} icon={m.icon}
          delay={m.delay} state="broken"
          driftX={6} driftY={5} driftFreq={0.7 + i * 0.08}/>
      ))}

      {microTexts.map((mt, i) => {
        const localT = localTime - mt.delay;
        if (localT < 0 || localT > 1.4) return null;
        const fade = Math.sin(localT * Math.PI / 1.4);
        return (
          <div key={i} style={{
            position: 'absolute', left: mt.x, top: mt.y,
            transform: 'translate(-50%, -50%)',
            fontFamily: MONO, fontSize: 11,
            color: YE.orange, opacity: fade * 0.9,
            letterSpacing: '0.04em',
            display: 'flex', alignItems: 'center', gap: 6,
          }}>
            <span style={{ width: 4, height: 4, borderRadius: '50%', background: YE.orange }}/>
            {mt.text}
          </div>
        );
      })}

      <Eyebrow y={140}>Cena 02 — Fragmentação</Eyebrow>
      <SceneCaption y={920}>
        Depois, tudo vira <Em>peça solta</Em>.
      </SceneCaption>
    </React.Fragment>
  );
}

// ── SCENE 3: The real problem (7 - 10s) ───────────────────────────────────
function Scene3() {
  const { localTime } = useSprite();

  // Reuse mods from scene 2 but frozen + dimmed
  const mods = [
    { label: 'Posts',      icon: Icons.doc,    x: 280, y: 320 },
    { label: 'Tráfego',    icon: Icons.chart,  x: 520, y: 220 },
    { label: 'WhatsApp',   icon: Icons.msg,    x: 780, y: 280 },
    { label: 'CRM',        icon: Icons.user,   x: 1100, y: 220 },
    { label: 'Planilhas',  icon: Icons.doc,    x: 1380, y: 300 },
    { label: 'Reuniões',   icon: Icons.cal,    x: 1640, y: 380 },
    { label: 'Leads',      icon: Icons.user,   x: 320, y: 560 },
    { label: 'Follow-up',  icon: Icons.msg,    x: 620, y: 660 },
    { label: 'Analytics',  icon: Icons.chart,  x: 940, y: 720 },
    { label: 'Campanhas',  icon: Icons.bolt,   x: 1240, y: 660 },
    { label: 'E-mails',    icon: Icons.msg,    x: 1540, y: 580 },
    { label: 'Tarefas',    icon: Icons.cog,    x: 1700, y: 720 },
  ];

  const phase1 = clamp(localTime / 0.6, 0, 1); // dim
  const phase2 = clamp((localTime - 0.5) / 0.6, 0, 1); // first headline
  const phase3 = clamp((localTime - 1.7) / 0.7, 0, 1); // swap to "estrutura"

  // dark veil
  const veil = phase1 * 0.55;

  return (
    <React.Fragment>
      {mods.map((m, i) => (
        <ModuleChip key={i} x={m.x} y={m.y} label={m.label} icon={m.icon}
          delay={0} state="dim" driftX={1} driftY={1}/>
      ))}

      <div style={{
        position: 'absolute', inset: 0,
        background: `radial-gradient(ellipse 50% 40% at 50% 50%, rgba(0,0,0,${veil * 0.3}), rgba(0,0,0,${veil}))`,
        pointerEvents: 'none',
      }}/>

      {/* central headline */}
      <div style={{
        position: 'absolute', left: '50%', top: 440,
        transform: 'translate(-50%, 0)',
        textAlign: 'center', width: 1400,
      }}>
        <div style={{
          opacity: phase2 * (1 - phase3 * 0.35),
          transform: `translateY(${(1 - phase2) * 16}px)`,
          fontFamily: SANS, fontSize: 62, fontWeight: 500,
          color: YE.cream, letterSpacing: '-0.025em',
          lineHeight: 1.1,
        }}>
          O problema não é falta de <Em>ferramenta</Em>.
        </div>

        {phase3 > 0 && (
          <div style={{
            marginTop: 28,
            opacity: phase3,
            transform: `translateY(${(1 - phase3) * 18}px)`,
            fontFamily: SANS, fontSize: 72, fontWeight: 500,
            color: YE.cream, letterSpacing: '-0.025em',
            lineHeight: 1.1,
          }}>
            É falta de{' '}
            <span style={{
              fontFamily: SERIF, fontStyle: 'italic',
              color: YE.orange,
              textShadow: `0 0 ${20 + 10 * Math.sin(localTime * 4)}px ${YE.orangeGlow}`,
            }}>
              estrutura.
            </span>
          </div>
        )}
      </div>

      {phase3 > 0.3 && <Glow x={960} y={540} size={700} opacity={phase3 * 0.5}/>}

      <Eyebrow y={140}>Cena 03 — O diagnóstico</Eyebrow>
    </React.Fragment>
  );
}

// ── SCENE 4: Strategy enters (10 - 13.5s) ─────────────────────────────────
function Scene4() {
  const { localTime } = useSprite();
  const cx = 960, cy = 500;

  const groups = {
    marketing: { x: 380, y: 320, label: 'Marketing',
      items: [{ l: 'Conteúdo', i: Icons.doc }, { l: 'Posts', i: Icons.doc },
              { l: 'Landing', i: Icons.globe }, { l: 'Campanhas', i: Icons.bolt }] },
    comercial: { x: 1540, y: 320, label: 'Comercial',
      items: [{ l: 'Leads', i: Icons.user }, { l: 'CRM', i: Icons.user },
              { l: 'Follow-up', i: Icons.msg }, { l: 'Propostas', i: Icons.doc }] },
    operacao:  { x: 380, y: 720, label: 'Operação',
      items: [{ l: 'Atendimento', i: Icons.msg }, { l: 'Tarefas', i: Icons.cog },
              { l: 'Processos', i: Icons.flow }, { l: 'Agenda', i: Icons.cal }] },
    inteligencia: { x: 1540, y: 720, label: 'Inteligência',
      items: [{ l: 'Dados', i: Icons.chart }, { l: 'Analytics', i: Icons.chart },
              { l: 'IA', i: Icons.spark }, { l: 'Relatórios', i: Icons.doc }] },
  };

  // Strategy card appears at 0
  const stratEnter = Easing.easeOutBack(clamp(localTime / 0.6, 0, 1));

  return (
    <React.Fragment>
      <Glow x={cx} y={cy} size={650} opacity={0.5}/>

      {/* Lines from center to each group */}
      {Object.entries(groups).map(([key, g], i) => (
        <CurveConnect key={key}
          x1={cx} y1={cy} x2={g.x} y2={g.y}
          start={0.6 + i * 0.15} drawDur={0.7}
          color="rgba(255,107,26,0.55)" width={1.5}
          pulse pulseDelay={1.6 + i * 0.1} pulseDur={2.2}
        />
      ))}

      {/* Group cluster cards */}
      {Object.entries(groups).map(([key, g], gi) => (
        <GroupCluster key={key} cx={g.x} cy={g.y} label={g.label} items={g.items}
          delay={1.0 + gi * 0.15}/>
      ))}

      {/* Central Strategy card */}
      <div style={{
        position: 'absolute', left: cx, top: cy,
        transform: `translate(-50%, -50%) scale(${0.6 + 0.4 * stratEnter})`,
        opacity: stratEnter,
        padding: '22px 36px',
        background: 'linear-gradient(180deg, #2A201A, #1A1715)',
        border: `1.5px solid ${YE.orange}`,
        borderRadius: 24,
        boxShadow: `0 20px 60px rgba(255,107,26,0.25), 0 0 0 1px rgba(255,107,26,0.15)`,
        display: 'flex', alignItems: 'center', gap: 16,
      }}>
        <div style={{
          width: 44, height: 44, borderRadius: 14,
          background: YE.orange, color: '#1a0d05',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          boxShadow: `0 0 24px ${YE.orangeGlow}`,
        }}>
          <svg width="24" height="24" viewBox="0 0 24 24" fill="currentColor">
            <path d="M12 2l2.5 5.5 6 .8-4.5 4 1.2 6-5.2-3-5.2 3 1.2-6L3.5 8.3l6-.8z"/>
          </svg>
        </div>
        <div>
          <div style={{
            fontFamily: MONO, fontSize: 10, letterSpacing: '0.24em',
            color: YE.orange, textTransform: 'uppercase', marginBottom: 4,
          }}>EIXO</div>
          <div style={{
            fontFamily: SANS, fontSize: 36, fontWeight: 600,
            color: YE.cream, letterSpacing: '-0.02em',
          }}>Estratégia</div>
        </div>
      </div>

      <Eyebrow y={140}>Cena 04 — Direção</Eyebrow>
      <SceneCaption y={920}>
        Estratégia transforma <Em>peças em direção</Em>.
      </SceneCaption>
    </React.Fragment>
  );
}

function GroupCluster({ cx, cy, label, items, delay = 0 }) {
  const { localTime } = useSprite();
  const localT = Math.max(0, localTime - delay);
  const enter = Easing.easeOutCubic(clamp(localT / 0.5, 0, 1));
  const t = useTime();

  return (
    <div style={{
      position: 'absolute', left: cx, top: cy,
      transform: `translate(-50%, -50%) scale(${0.85 + 0.15 * enter})`,
      opacity: enter,
      width: 280,
      padding: 16,
      background: 'rgba(25,28,30,0.85)',
      backdropFilter: 'blur(8px)',
      border: `1px solid ${YE.borderStrong}`,
      borderRadius: 20,
      boxShadow: '0 12px 40px rgba(0,0,0,0.4)',
    }}>
      <div style={{
        fontFamily: MONO, fontSize: 10, letterSpacing: '0.22em',
        color: YE.orange, textTransform: 'uppercase', marginBottom: 12,
        display: 'flex', alignItems: 'center', gap: 8,
      }}>
        <span style={{ width: 6, height: 6, borderRadius: '50%', background: YE.orange,
          boxShadow: `0 0 8px ${YE.orange}` }}/>
        {label}
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
        {items.map((it, i) => {
          const itDelay = delay + 0.2 + i * 0.05;
          const itT = Math.max(0, localTime - itDelay);
          const itEnter = Easing.easeOutCubic(clamp(itT / 0.4, 0, 1));
          return (
            <div key={i} style={{
              opacity: itEnter,
              transform: `translateY(${(1 - itEnter) * 6}px)`,
              padding: '8px 10px',
              background: YE.cardLight,
              border: `1px solid ${YE.border}`,
              borderRadius: 10,
              fontFamily: SANS, fontSize: 12, fontWeight: 500,
              color: YE.cream,
              display: 'flex', alignItems: 'center', gap: 6,
            }}>
              <span style={{ color: YE.textMuted, display: 'inline-flex' }}>{it.i}</span>
              {it.l}
            </div>
          );
        })}
      </div>
    </div>
  );
}

// ── SCENE 5: System born / Dashboard pillars (13.5 - 17s) ─────────────────
function Scene5() {
  const { localTime } = useSprite();
  const cx = 960;

  const enter = Easing.easeOutCubic(clamp(localTime / 0.7, 0, 1));

  const pillars = [
    { label: 'Marketing Inteligente', desc: 'Conteúdo + funil + dados', icon: Icons.bolt, accent: '+34%' },
    { label: 'Automação',             desc: 'Fluxos sem fricção',       icon: Icons.flow, accent: '24/7' },
    { label: 'IA Aplicada',           desc: 'Decisão amplificada',      icon: Icons.spark, accent: 'live' },
    { label: 'Dados & Decisão',       desc: 'Da planilha à clareza',    icon: Icons.chart, accent: '3.2x' },
  ];

  return (
    <React.Fragment>
      <Glow x={cx} y={520} size={900} opacity={0.4}/>

      {/* Main panel */}
      <div style={{
        position: 'absolute', left: cx, top: 520,
        transform: `translate(-50%, -50%) scale(${0.92 + 0.08 * enter})`,
        opacity: enter,
        width: 1480,
        padding: 32,
        background: 'linear-gradient(180deg, rgba(32,35,37,0.95), rgba(20,22,24,0.95))',
        backdropFilter: 'blur(12px)',
        border: `1px solid ${YE.borderStrong}`,
        borderRadius: 28,
        boxShadow: '0 30px 80px rgba(0,0,0,0.5)',
      }}>
        {/* Header */}
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 24 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <div style={{
              width: 36, height: 36, borderRadius: 10,
              background: 'linear-gradient(135deg, #FF6B1A, #E9580C)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              boxShadow: `0 0 16px ${YE.orangeGlow}`,
            }}>
              <span style={{ color: '#1a0d05', display: 'flex' }}>{Icons.star}</span>
            </div>
            <div>
              <div style={{ fontFamily: MONO, fontSize: 10, letterSpacing: '0.24em', color: YE.textMuted, textTransform: 'uppercase' }}>SISTEMA</div>
              <div style={{ fontFamily: SANS, fontSize: 24, fontWeight: 600, color: YE.cream, letterSpacing: '-0.01em' }}>
                Sistema de Crescimento
              </div>
            </div>
          </div>
          <div style={{
            display: 'flex', alignItems: 'center', gap: 8,
            padding: '6px 12px', borderRadius: 999,
            background: 'rgba(255,107,26,0.12)',
            border: '1px solid rgba(255,107,26,0.3)',
          }}>
            <span style={{ width: 6, height: 6, borderRadius: '50%', background: YE.orange,
              boxShadow: `0 0 8px ${YE.orange}`, animation: 'none' }}/>
            <span style={{ fontFamily: MONO, fontSize: 10, letterSpacing: '0.18em', color: YE.orange, textTransform: 'uppercase' }}>
              Operando
            </span>
          </div>
        </div>

        {/* 4 pillars */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 16 }}>
          {pillars.map((p, i) => {
            const pDelay = 0.5 + i * 0.12;
            const pT = Math.max(0, localTime - pDelay);
            const pEnter = Easing.easeOutCubic(clamp(pT / 0.5, 0, 1));
            return (
              <div key={i} style={{
                opacity: pEnter,
                transform: `translateY(${(1 - pEnter) * 14}px)`,
                padding: 20,
                background: YE.card,
                border: `1px solid ${YE.border}`,
                borderRadius: 18,
                position: 'relative',
                overflow: 'hidden',
              }}>
                <div style={{
                  position: 'absolute', top: 0, left: 0, right: 0, height: 2,
                  background: 'linear-gradient(90deg, transparent, rgba(255,107,26,0.6), transparent)',
                }}/>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 16 }}>
                  <div style={{
                    width: 36, height: 36, borderRadius: 10,
                    background: 'rgba(255,107,26,0.12)',
                    border: '1px solid rgba(255,107,26,0.3)',
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    color: YE.orange,
                  }}>{p.icon}</div>
                  <div style={{
                    fontFamily: MONO, fontSize: 11, color: YE.orange,
                    fontVariantNumeric: 'tabular-nums',
                  }}>{p.accent}</div>
                </div>
                <div style={{ fontFamily: SANS, fontSize: 16, fontWeight: 600, color: YE.cream, marginBottom: 4, letterSpacing: '-0.01em' }}>
                  {p.label}
                </div>
                <div style={{ fontFamily: SANS, fontSize: 12, color: YE.textMuted, lineHeight: 1.4 }}>
                  {p.desc}
                </div>
                {/* mini sparkline */}
                <svg width="100%" height="32" viewBox="0 0 200 32" style={{ marginTop: 12 }}>
                  <path d={pillarSparkline(i, localTime)} stroke={YE.orange} strokeWidth="1.5" fill="none" strokeLinecap="round"/>
                  <path d={pillarSparkline(i, localTime) + ' L 200 32 L 0 32 Z'} fill="rgba(255,107,26,0.1)"/>
                </svg>
              </div>
            );
          })}
        </div>
      </div>

      <Eyebrow y={140}>Cena 05 — Sistema</Eyebrow>
      <SceneCaption y={920}>
        Quando tudo se conecta, o negócio opera com <Em>inteligência</Em>.
      </SceneCaption>
    </React.Fragment>
  );
}

function pillarSparkline(seed, t) {
  const pts = [];
  const n = 12;
  for (let i = 0; i < n; i++) {
    const x = (i / (n - 1)) * 200;
    const phase = seed * 1.7 + i * 0.5;
    const noise = Math.sin(phase + t * 0.4) * 4;
    const trend = 28 - i * (1.6 + seed * 0.2);
    const y = clamp(trend + noise, 4, 28);
    pts.push(`${i === 0 ? 'M' : 'L'} ${x.toFixed(1)} ${y.toFixed(1)}`);
  }
  return pts.join(' ');
}

Object.assign(window, { Scene1, Scene2, Scene3, Scene4, Scene5 });
