// KarlaPay — Scenes part 2: Carla call + Result + Tagline

// ─────────────────────────────────────────────────────────────────────────────
// SCENE 3 — Carla calls (10.5 → 19.0s)
// Abstract orange orb pulses while a voice waveform animates; live transcript.

function Waveform({ localTime, width = 520, height = 120, bars = 48, active = true }) {
  const barW = 4;
  const gap = (width - bars * barW) / (bars - 1);

  return (
    <div style={{
      position: 'relative',
      width, height,
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
      gap: `${gap}px`,
    }}>
      {Array.from({ length: bars }).map((_, i) => {
        // Organic waveform using layered sines
        const phase = i * 0.42;
        const envelope = Math.sin((i / bars) * Math.PI); // peak in middle
        const base = 0.15;
        const variance = active
          ? (0.5 + 0.5 * Math.sin(localTime * 6 + phase)) *
            (0.6 + 0.4 * Math.sin(localTime * 2.3 + phase * 0.5))
          : 0.1;
        const h = (base + variance * envelope * 0.85) * height;
        const color = ORANGE;
        return (
          <div key={i} style={{
            width: barW,
            height: Math.max(3, h),
            background: color,
            borderRadius: barW / 2,
            opacity: active ? 0.9 : 0.3,
            transition: 'none',
          }}/>
        );
      })}
    </div>
  );
}

function CarlaOrb({ localTime, size = 280 }) {
  const pulse1 = 1 + 0.08 * Math.sin(localTime * 2.2);
  const pulse2 = 1 + 0.12 * Math.sin(localTime * 3.1 + 1.2);
  const pulse3 = 1 + 0.06 * Math.sin(localTime * 1.5 + 2.4);

  return (
    <div style={{ position: 'relative', width: size, height: size }}>
      {/* Outer rings */}
      <div style={{
        position: 'absolute', inset: -60,
        borderRadius: '50%',
        border: `1px solid rgba(255,106,26,0.15)`,
        transform: `scale(${pulse3})`,
      }}/>
      <div style={{
        position: 'absolute', inset: -30,
        borderRadius: '50%',
        border: `1px solid rgba(255,106,26,0.25)`,
        transform: `scale(${pulse2})`,
      }}/>
      {/* Glow */}
      <div style={{
        position: 'absolute', inset: -80,
        borderRadius: '50%',
        background: `radial-gradient(circle, rgba(255,106,26,0.35) 0%, rgba(255,106,26,0) 65%)`,
        transform: `scale(${pulse1})`,
      }}/>
      {/* Core */}
      <div style={{
        position: 'absolute', inset: 0,
        borderRadius: '50%',
        background: `radial-gradient(circle at 35% 30%, #FF8A45 0%, ${ORANGE} 45%, #C84A00 100%)`,
        boxShadow: `0 0 80px rgba(255,106,26,0.6), inset 0 -20px 40px rgba(0,0,0,0.3)`,
        transform: `scale(${pulse1})`,
      }}>
        {/* Inner highlight */}
        <div style={{
          position: 'absolute',
          top: '18%', left: '24%',
          width: '32%', height: '28%',
          borderRadius: '50%',
          background: 'radial-gradient(circle, rgba(255,255,255,0.35) 0%, rgba(255,255,255,0) 70%)',
          filter: 'blur(4px)',
        }}/>
      </div>
      {/* Headset suggestion - thin arc */}
      <svg
        style={{ position: 'absolute', inset: -12 }}
        viewBox="0 0 100 100"
        width={size + 24} height={size + 24}
      >
        <path
          d="M 15 50 A 35 35 0 0 1 85 50"
          fill="none"
          stroke="rgba(255,255,255,0.25)"
          strokeWidth="1.2"
          strokeLinecap="round"
        />
      </svg>
    </div>
  );
}

function TranscriptLine({ speaker, text, visible, enter, color }) {
  const opacity = clamp(enter, 0, 1);
  const dy = (1 - opacity) * 12;

  return (
    <div style={{
      opacity: visible ? opacity : 0,
      transform: `translateY(${dy}px)`,
      marginBottom: 18,
      fontFamily: SATOSHI,
    }}>
      <div style={{
        fontSize: 12,
        color: color,
        fontFamily: MONO,
        letterSpacing: '0.15em',
        marginBottom: 6,
        textTransform: 'uppercase',
      }}>
        {speaker}
      </div>
      <div style={{
        fontSize: 22,
        color: INK,
        fontWeight: 500,
        lineHeight: 1.35,
        letterSpacing: '-0.01em',
      }}>
        {text}
      </div>
    </div>
  );
}

function SceneCarla() {
  const { localTime, duration } = useSprite();

  // Phone ring establishing (0 → 1.2s)
  const ringT = clamp(localTime / 1.0, 0, 1);
  const ringEased = Easing.easeOutCubic(ringT);

  // Orb zooms in (1.0s)
  const orbAppearT = clamp((localTime - 0.6) / 0.9, 0, 1);
  const orbEased = Easing.easeOutBack(orbAppearT);

  // Connection label
  const connectStart = 0.3;
  const connectT = clamp((localTime - connectStart) / 0.5, 0, 1);

  // Transcript timings — after connection, lines appear
  const transcriptStart = 1.8;
  const lines = [
    { at: 0.0, speaker: 'CARLA', color: ORANGE, text: '"Hola Mario, soy Carla de idme SL."' },
    { at: 1.8, speaker: 'MARIO', color: MUTED, text: '"Sí, dígame."' },
    { at: 3.0, speaker: 'CARLA', color: ORANGE, text: '"Le llamo por su factura de € 1.250, con vencimiento el 3 de mayo."' },
    { at: 5.0, speaker: 'MARIO', color: MUTED, text: '"Ah, sí… ¿puedo pagar ahora por Bizum?"' },
  ];

  // Which line is "active" (driving waveform)
  const activeSpeaker = (() => {
    const t = localTime - transcriptStart;
    let current = 'CARLA';
    for (const l of lines) {
      if (t >= l.at) current = l.speaker;
    }
    return current;
  })();

  // Exit
  const exitStart = duration - 0.7;
  const exitT = clamp((localTime - exitStart) / 0.7, 0, 1);
  const exitOpacity = 1 - Easing.easeInCubic(exitT);

  return (
    <div style={{ position: 'absolute', inset: 0, opacity: exitOpacity }}>
      {/* Top bar: call status */}
      <div style={{
        position: 'absolute',
        top: 80, left: '50%',
        transform: `translateX(-50%) translateY(${(1 - ringEased) * -12}px)`,
        opacity: ringEased,
        display: 'flex', alignItems: 'center', gap: 14,
        padding: '10px 20px',
        background: PANEL,
        border: `1px solid ${LINE}`,
        borderRadius: 999,
        fontFamily: MONO,
        fontSize: 13,
        color: INK,
        letterSpacing: '0.1em',
      }}>
        <div style={{
          width: 8, height: 8,
          borderRadius: '50%',
          background: ORANGE,
          boxShadow: `0 0 12px ${ORANGE}`,
          opacity: 0.6 + 0.4 * Math.sin(localTime * 4),
        }}/>
        <span>LLAMADA EN CURSO</span>
        <span style={{ color: MUTED }}>·</span>
        <span style={{ color: MUTED }}>
          {formatCallTime(Math.max(0, localTime - 0.3))}
        </span>
      </div>

      {/* Left: Orb */}
      <div style={{
        position: 'absolute',
        left: 260, top: '50%',
        transform: `translateY(-50%) scale(${orbEased})`,
        opacity: orbAppearT,
      }}>
        <CarlaOrb localTime={localTime} size={280} />
        <div style={{
          marginTop: 48,
          textAlign: 'center',
          fontFamily: CAVEAT,
          fontSize: 64,
          color: ORANGE,
          lineHeight: 1,
        }}>
          Carla
        </div>
        <div style={{
          textAlign: 'center',
          marginTop: 4,
          fontFamily: MONO,
          fontSize: 12,
          color: MUTED,
          letterSpacing: '0.2em',
        }}>
          AGENTE DE IA
        </div>
      </div>

      {/* Center-right: Transcript + waveform */}
      <div style={{
        position: 'absolute',
        left: 720, top: 220,
        width: 960,
      }}>
        {/* Waveform at top of transcript area */}
        <div style={{
          opacity: clamp((localTime - 1.5) / 0.6, 0, 1),
          marginBottom: 36,
        }}>
          <Waveform
            localTime={localTime}
            width={520}
            height={80}
            bars={56}
            active={true}
          />
        </div>

        {/* Lines */}
        <div>
          {lines.map((l, i) => {
            const lineLocal = localTime - transcriptStart - l.at;
            const enter = clamp(lineLocal / 0.5, 0, 1);
            const visible = lineLocal >= 0;
            return (
              <TranscriptLine
                key={i}
                speaker={l.speaker}
                color={l.color}
                text={l.text}
                visible={visible}
                enter={Easing.easeOutCubic(enter)}
              />
            );
          })}
        </div>
      </div>
    </div>
  );
}

function formatCallTime(t) {
  const m = Math.floor(t / 60);
  const s = Math.floor(t % 60);
  return `${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`;
}

Object.assign(window, {
  Waveform, CarlaOrb, TranscriptLine, SceneCarla, formatCallTime,
});
