// scenes/Scene1_Before.jsx
// 0 → 4.3s — The "before": scattered emails, relances, missing files.
// Frame: desktop-ish cluttered canvas. Papers/emails stack, labels flash,
// a red "Relance #3" stamps in, then everything dissolves toward the cut.

function Scene1_Before({ start = 0, end = 4.3 }) {
  return (
    <Sprite start={start} end={end}>
      <SceneBg color={FP.bg}>
        <SubtleGrain />

        {/* Faint columns of filename chatter — sets the scene */}
        <FilenameRain />

        {/* Center title that fades early */}
        <Sprite start={start + 0.2} end={start + 2.6}>
          <TitleBefore />
        </Sprite>

        {/* Stack of emails */}
        <EmailStack stageStart={start} />

        {/* Relance #3 stamp — thumps in */}
        <Sprite start={start + 2.0} end={end}>
          <RelanceStamp />
        </Sprite>

        {/* End wipe: lime bar sweeps across to transition to scene 2 */}
        <Sprite start={end - 0.6} end={end}>
          <WipeOut />
        </Sprite>

        <Sprite start={start + 0.4} end={end - 0.2}>
          <Caption text="Relancer, chercher, recompter." accent="Chaque fois." />
        </Sprite>
      </SceneBg>
    </Sprite>
  );
}

function TitleBefore() {
  const { localTime, duration } = useSprite();
  const fadeIn  = Easing.easeOutCubic(clamp(localTime / 0.5, 0, 1));
  const fadeOut = Easing.easeInCubic(clamp((localTime - (duration - 0.4)) / 0.4, 0, 1));
  const opacity = fadeIn * (1 - fadeOut);
  return (
    <div style={{
      position: 'absolute', inset: 0,
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      opacity,
    }}>
      <div style={{
        fontFamily: SANS, color: FP.text,
        fontSize: 92, fontWeight: 500, letterSpacing: '-0.03em',
        textAlign: 'center', lineHeight: 1.0,
      }}>
        Collecter des documents,<br/>
        <span style={{ fontFamily: SERIF, fontStyle: 'italic', color: FP.muted }}>c'est compliqué.</span>
      </div>
    </div>
  );
}

// Scrolling columns of filename-like strings in the bg — monospace, low opacity
function FilenameRain() {
  const t = useTime();
  const lines = [
    'bilan_2024_v3_FINAL.pdf',
    'IMG_2931.jpg',
    'kbis.pdf',
    'releve_BNP_janv.pdf',
    'attestation URSSAF.pdf',
    'passeport_Dupont.jpg',
    'pièce manquante',
    'Re: votre dossier',
    '[Relance] Documents manquants',
    'WhatsApp_IMG.jpeg',
    'scan_rectoverso.pdf',
    'tva_trim_3.xlsx',
    'contrat_signé.pdf',
    'justif_domicile.pdf',
    'Fwd: Fwd: Fwd: bilan',
    'capture d\'écran 2024-04-12 à 15h32.png',
  ];
  const cols = [
    { x: 60,   delay: 0,   speed: 70, lines: lines.slice(0, 8) },
    { x: 380,  delay: 0.3, speed: 60, lines: lines.slice(4, 14) },
    { x: 1420, delay: 0.1, speed: 65, lines: lines.slice(6, 16) },
    { x: 1700, delay: 0.4, speed: 55, lines: lines.slice(2, 12) },
  ];
  return (
    <div style={{ position: 'absolute', inset: 0, pointerEvents: 'none' }}>
      {cols.map((col, i) => {
        const offset = ((t + col.delay) * col.speed) % 800;
        return (
          <div key={i} style={{
            position: 'absolute',
            left: col.x, top: -200,
            transform: `translateY(${offset}px)`,
            fontFamily: MONO, fontSize: 13,
            color: 'rgba(255,255,255,0.14)',
            lineHeight: 2.2,
            whiteSpace: 'nowrap',
          }}>
            {col.lines.map((l, j) => <div key={j}>{l}</div>)}
            {col.lines.map((l, j) => <div key={'b'+j}>{l}</div>)}
          </div>
        );
      })}
    </div>
  );
}

// Stack of email-like cards, skewed, landing one by one
function EmailStack({ stageStart }) {
  const t = useTime() - stageStart;
  const emails = [
    { subj: 'Re: Documents bilan 2024',           from: 'Vous',        when: 'Mar 14',  flag: 'relance',  x: 900, y: 340, r: -8,  delay: 0.8 },
    { subj: 'Pièces justificatives manquantes',   from: 'Client',      when: 'Mar 18',  flag: 'missing', x: 1100, y: 500, r: 6,   delay: 1.1 },
    { subj: 'Fwd: Fwd: scan KBIS',                from: 'Comptable',   when: 'Mar 20',  flag: '',        x: 780,  y: 560, r: -3,  delay: 1.35 },
    { subj: '[Relance #2] documents au 31/03',    from: 'Vous',        when: 'Mar 28',  flag: 'relance', x: 1240, y: 380, r: 5,   delay: 1.6 },
    { subj: 'Re: Re: attestation URSSAF',         from: 'Client',      when: 'Avr 02',  flag: 'missing', x: 1020, y: 640, r: -5,  delay: 1.85 },
  ];
  return (
    <div style={{ position: 'absolute', inset: 0, pointerEvents: 'none' }}>
      {emails.map((em, i) => {
        const appear = clamp((t - em.delay) / 0.35, 0, 1);
        const eased = Easing.easeOutBack(appear);
        const opacity = clamp((t - em.delay) / 0.25, 0, 1);
        if (opacity <= 0) return null;
        return (
          <div key={i} style={{
            position: 'absolute',
            left: em.x, top: em.y,
            width: 380, minHeight: 70,
            padding: '14px 16px',
            background: FP.card,
            border: `1px solid ${FP.border}`,
            borderRadius: 12,
            boxShadow: '0 12px 32px rgba(0,0,0,0.35)',
            transform: `rotate(${em.r}deg) translateY(${(1 - eased) * 40}px) scale(${0.85 + eased * 0.15})`,
            opacity,
            transformOrigin: 'top left',
          }}>
            <div style={{
              display: 'flex', justifyContent: 'space-between', alignItems: 'center',
              gap: 8, marginBottom: 6,
              fontFamily: SANS, fontSize: 12, color: FP.muted,
            }}>
              <span style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                <MailIcon size={13} color={FP.muted}/> {em.from}
              </span>
              <span style={{ fontFamily: MONO }}>{em.when}</span>
            </div>
            <div style={{
              fontFamily: SANS, fontSize: 15, fontWeight: 500,
              color: FP.text,
              overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
            }}>{em.subj}</div>
            {em.flag === 'relance' && (
              <div style={{ marginTop: 8 }}>
                <Badge variant="warn" icon={<AlertIcon size={11} color={FP.warn} />}>Relance</Badge>
              </div>
            )}
            {em.flag === 'missing' && (
              <div style={{ marginTop: 8 }}>
                <Badge variant="danger" icon={<DotIcon size={6} color={FP.danger} />}>Pièce manquante</Badge>
              </div>
            )}
          </div>
        );
      })}
    </div>
  );
}

function RelanceStamp() {
  const { localTime } = useSprite();
  // punchy thud: scale from 2.4 → 1 quickly with back overshoot, tilt held
  const p = clamp(localTime / 0.35, 0, 1);
  const eased = Easing.easeOutBack(p);
  const scale = 2.4 - 1.4 * eased;
  const opacity = clamp(localTime / 0.2, 0, 1);
  // slight jitter on impact
  const jitter = localTime < 0.35 ? Math.sin(localTime * 50) * (1 - p) * 4 : 0;

  return (
    <div style={{
      position: 'absolute',
      left: '50%', top: '50%',
      transform: `translate(-50%, -50%) rotate(-12deg) scale(${scale}) translateX(${jitter}px)`,
      opacity,
      pointerEvents: 'none',
    }}>
      <div style={{
        border: `4px solid ${FP.danger}`,
        color: FP.danger,
        padding: '14px 36px',
        borderRadius: 8,
        fontFamily: SANS,
        fontSize: 56,
        fontWeight: 700,
        letterSpacing: '0.04em',
        textTransform: 'uppercase',
        background: 'rgba(127,29,29,0.15)',
        boxShadow: '0 0 0 1px rgba(239,68,68,0.3)',
      }}>
        Relance · 3
      </div>
    </div>
  );
}

function WipeOut() {
  const { localTime, duration } = useSprite();
  const p = clamp(localTime / duration, 0, 1);
  const eased = Easing.easeInOutCubic(p);
  return (
    <div style={{
      position: 'absolute', inset: 0,
      background: FP.primary,
      transform: `translateX(${-100 + eased * 100}%)`,
      pointerEvents: 'none',
    }} />
  );
}

Object.assign(window, { Scene1_Before });
