// Scene 1 — The chaos: paper, WhatsApp messages, Excel fragments flying.
// Message: "Así se coordinan hoy las obras". Ends with everything collapsing
// into a single dark frame as ObraPlanner takes over.

function SceneProblem({ start, end }) {
  return (
    <Sprite start={start} end={end}>
      {({ localTime, progress }) => (
        <div style={{
          position: 'absolute', inset: 0,
          background: `radial-gradient(80% 70% at 50% 55%, #1a2238 0%, ${OP_COLORS.bg} 60%)`,
          overflow: 'hidden',
        }}>
          {/* Subtle grid */}
          <div style={{
            position: 'absolute', inset: 0,
            backgroundImage: `linear-gradient(${OP_COLORS.border} 1px, transparent 1px),
                              linear-gradient(90deg, ${OP_COLORS.border} 1px, transparent 1px)`,
            backgroundSize: '48px 48px',
            opacity: 0.25,
            maskImage: 'radial-gradient(circle at center, black 40%, transparent 75%)',
          }} />

          {/* Floating artifacts — paper, WhatsApp bubbles, Excel fragments */}
          <ChaosArtifact kind="paper" x={170} y={140} rot={-8}  startAt={0.0} />
          <ChaosArtifact kind="wa"    x={820} y={110} rot={5}   startAt={0.25} />
          <ChaosArtifact kind="xls"   x={1380} y={200} rot={-4} startAt={0.5} />
          <ChaosArtifact kind="paper" x={260} y={620} rot={7}   startAt={0.75} />
          <ChaosArtifact kind="wa"    x={1180} y={580} rot={-6} startAt={1.0} />
          <ChaosArtifact kind="xls"   x={700} y={680} rot={3}   startAt={1.25} />
          <ChaosArtifact kind="paper" x={1440} y={640} rot={9}  startAt={1.5} />
          <ChaosArtifact kind="wa"    x={540} y={340} rot={-3}  startAt={1.75} />

          {/* Big headline — slams in over the chaos */}
          <Headline localTime={localTime} duration={end - start} />

          {/* Final chaos collapse — everything pulled toward center */}
          <CollapseOverlay localTime={localTime} duration={end - start} />
        </div>
      )}
    </Sprite>
  );
}

// Artifact: a piece of paper, whatsapp chat, or Excel fragment.
function ChaosArtifact({ kind, x, y, rot, startAt }) {
  const { localTime, duration } = useSprite();
  const exitStart = duration - 1.0; // pull into center at end

  // Entry
  const entryT = clamp((localTime - startAt) / 0.4, 0, 1);
  const entry = Easing.easeOutCubic(entryT);

  // Collapse (pulled to center)
  const exitT = clamp((localTime - exitStart) / 1.0, 0, 1);
  const exit = Easing.easeInCubic(exitT);

  // Center of canvas
  const cx = 960, cy = 540;

  // Idle float
  const idle = Math.sin((localTime + startAt * 4) * 1.2) * 6;

  const dx = (cx - x) * exit;
  const dy = (cy - y) * exit;
  const scale = entry * (1 - exit * 0.8);
  const opacity = entry * (1 - exit);

  return (
    <div style={{
      position: 'absolute',
      left: x, top: y + idle,
      transform: `translate(${dx}px, ${dy}px) rotate(${rot - exit * 45}deg) scale(${scale})`,
      opacity,
      transformOrigin: 'center',
      willChange: 'transform, opacity',
      filter: 'drop-shadow(0 20px 40px rgba(0,0,0,0.45))',
    }}>
      {kind === 'paper' && <PaperCard />}
      {kind === 'wa' && <WhatsAppBubble />}
      {kind === 'xls' && <ExcelFragment />}
    </div>
  );
}

function PaperCard() {
  return (
    <div style={{
      width: 260, height: 190,
      background: '#f8f5ee',
      borderRadius: 4,
      padding: '18px 20px',
      fontFamily: "'Kalam', 'Caveat', cursive",
      color: '#2a2420',
      fontSize: 17,
      lineHeight: 1.35,
      transform: 'translateY(0)',
      position: 'relative',
    }}>
      <div style={{
        borderBottom: '1px solid #d9cfbf', paddingBottom: 6, marginBottom: 10,
        fontWeight: 700, color: '#1b1510', fontSize: 19,
      }}>
        Obra — Av. San Martín
      </div>
      <div>• Ruiz → albañil</div>
      <div>• Gómez → hormigón</div>
      <div>• López → falta</div>
      <div style={{ fontSize: 14, color: '#8a6f4a', marginTop: 8 }}>
        camioneta: Torres
      </div>
      {/* Coffee stain */}
      <div style={{
        position: 'absolute', top: 14, right: 18,
        width: 28, height: 28, borderRadius: '50%',
        background: 'radial-gradient(circle at 40% 40%, rgba(120,70,30,0.35) 0%, rgba(120,70,30,0.1) 70%, transparent 100%)',
      }} />
    </div>
  );
}

function WhatsAppBubble() {
  return (
    <div style={{
      width: 280,
      background: '#0b141a',
      borderRadius: 14,
      padding: 14,
      fontFamily: SANS,
      color: '#e9edef',
      fontSize: 14,
      border: '1px solid rgba(255,255,255,0.04)',
    }}>
      <div style={{
        display: 'flex', alignItems: 'center', gap: 10, marginBottom: 10,
        paddingBottom: 10, borderBottom: '1px solid rgba(255,255,255,0.06)',
      }}>
        <div style={{ width: 28, height: 28, borderRadius: '50%', background: '#00a884', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 13, fontWeight: 700 }}>O</div>
        <div style={{ fontSize: 13, fontWeight: 600 }}>Obras — grupo</div>
      </div>
      <div style={{
        background: '#202c33', borderRadius: 8, padding: '8px 10px',
        lineHeight: 1.4, marginBottom: 6,
      }}>
        Buen día, ¿quién va hoy a la obra del puerto?
      </div>
      <div style={{
        background: '#005c4b', borderRadius: 8, padding: '8px 10px',
        lineHeight: 1.4, marginLeft: 24, color: '#e9edef',
      }}>
        yo creo que Ruiz, pero no sé la camioneta
      </div>
      <div style={{ textAlign: 'right', color: '#8696a0', fontSize: 11, marginTop: 4 }}>07:42</div>
    </div>
  );
}

function ExcelFragment() {
  const rows = [
    ['Ruiz',  'OK', '8', '—'],
    ['Gómez', '?',  '?', '?'],
    ['López', '—', '—', 'falta'],
    ['Torres','OK', '8', 'chofer'],
  ];
  return (
    <div style={{
      width: 300,
      background: '#ffffff',
      borderRadius: 4,
      fontFamily: MONO,
      fontSize: 12,
      color: '#1f2a1a',
      overflow: 'hidden',
      border: '1px solid #bcbcbc',
    }}>
      <div style={{
        background: '#107c41', color: '#fff',
        padding: '6px 10px', fontSize: 12, fontWeight: 600,
        fontFamily: SANS, letterSpacing: '0.02em',
        display: 'flex', justifyContent: 'space-between',
      }}>
        <span>quincena-marzo.xlsx</span>
        <span style={{ opacity: 0.7 }}>editado</span>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: '1.2fr 0.6fr 0.6fr 1fr' }}>
        {['Personal','L','M','obs'].map((h, i) => (
          <div key={i} style={{ background: '#e8efe3', padding: '5px 8px', borderBottom: '1px solid #bcbcbc', fontWeight: 700 }}>{h}</div>
        ))}
        {rows.flatMap((r, ri) => r.map((c, ci) => (
          <div key={`${ri}-${ci}`} style={{
            padding: '5px 8px',
            borderBottom: '1px solid #e0e0e0',
            borderLeft: ci > 0 ? '1px solid #e0e0e0' : 'none',
            background: c === '?' ? '#fff5cc' : c === 'falta' ? '#ffd4d4' : '#fff',
          }}>{c}</div>
        )))}
      </div>
    </div>
  );
}

function Headline({ localTime, duration }) {
  // Line 1 appears first, line 2 shortly after
  const l1T = clamp((localTime - 0.6) / 0.5, 0, 1);
  const l2T = clamp((localTime - 1.3) / 0.5, 0, 1);
  const subT = clamp((localTime - 2.2) / 0.5, 0, 1);

  // Exit as everything collapses
  const exitT = clamp((localTime - (duration - 1.0)) / 0.8, 0, 1);
  const exit = Easing.easeInCubic(exitT);
  const outY = -30 * exit;
  const outOp = 1 - exit;

  return (
    <div style={{
      position: 'absolute', inset: 0,
      display: 'flex', flexDirection: 'column',
      alignItems: 'center', justifyContent: 'center',
      pointerEvents: 'none',
      fontFamily: SANS,
      opacity: outOp,
      transform: `translateY(${outY}px)`,
    }}>
      <div style={{
        fontSize: 22, fontWeight: 600, letterSpacing: '0.25em',
        color: OP_COLORS.red, textTransform: 'uppercase',
        opacity: Easing.easeOutCubic(l1T),
        transform: `translateY(${(1 - Easing.easeOutCubic(l1T)) * 12}px)`,
        marginBottom: 28,
        textShadow: '0 0 24px rgba(239,68,68,0.4)',
      }}>
        El caos de cada mañana
      </div>
      <div style={{
        fontSize: 124, fontWeight: 800, letterSpacing: '-0.04em',
        color: OP_COLORS.text, lineHeight: 0.95,
        opacity: Easing.easeOutCubic(l2T),
        transform: `translateY(${(1 - Easing.easeOutCubic(l2T)) * 24}px)`,
        textAlign: 'center',
      }}>
        Papel. WhatsApp.
      </div>
      <div style={{
        fontSize: 124, fontWeight: 800, letterSpacing: '-0.04em',
        color: OP_COLORS.text, lineHeight: 0.95,
        opacity: Easing.easeOutCubic(subT),
        transform: `translateY(${(1 - Easing.easeOutCubic(subT)) * 24}px)`,
        textAlign: 'center',
        background: `linear-gradient(90deg, ${OP_COLORS.amber}, ${OP_COLORS.red})`,
        WebkitBackgroundClip: 'text',
        WebkitTextFillColor: 'transparent',
      }}>
        Excel sueltos.
      </div>
    </div>
  );
}

function CollapseOverlay({ localTime, duration }) {
  const exitT = clamp((localTime - (duration - 0.6)) / 0.6, 0, 1);
  return (
    <div style={{
      position: 'absolute', inset: 0,
      background: OP_COLORS.bg,
      opacity: Easing.easeInCubic(exitT),
      pointerEvents: 'none',
    }} />
  );
}

Object.assign(window, { SceneProblem });
