// scenes.jsx — Rainwater explainer video scenes
// 3 minutes / editorial rhythm / mixed pearl + dark-terminal style
//
// All scenes are <Sprite start end> children of <Stage>.
// Palette comes from BRAND (Rainwater brand tokens, verified from src/lib/brand.ts).

const BRAND = {
  pearl: "#F4F2F0",
  pearlDeep: "#ECE7E0",
  ink: "#181515",
  inkSoft: "#55595E",
  inkMute: "rgba(85,89,94,0.62)",
  accent: "#92A4B6",
  accentDeep: "#73879F",
  accentSoft: "#CCD3DB",
  dark: "#0C1117",
  darkSurface: "#141B24",
  darkBorder: "rgba(146,164,182,0.18)",
  darkText: "#ECE7E0",
  darkMute: "rgba(236,231,224,0.55)",
  green: "#7FB28A",
  red:   "#C57A78",
};

const FONTS = {
  serif: "'Cormorant Garamond', 'Playfair Display', Georgia, serif",
  sans:  "'Inter', 'Helvetica Neue', system-ui, sans-serif",
  mono:  "'JetBrains Mono', ui-monospace, SFMono-Regular, monospace",
};

// ─── small helpers ──────────────────────────────────────────────────────────

function useEntryExit({ entry = 0.5, exit = 0.5, entryEase = Easing.easeOutCubic, exitEase = Easing.easeInCubic } = {}) {
  const { localTime, duration } = useSprite();
  const exitStart = Math.max(0, duration - exit);
  let opacity = 1;
  let rise = 0;
  if (localTime < entry) {
    const t = entryEase(clamp(localTime / entry, 0, 1));
    opacity = t;
    rise = (1 - t) * 18;
  } else if (localTime > exitStart) {
    const t = exitEase(clamp((localTime - exitStart) / exit, 0, 1));
    opacity = 1 - t;
    rise = -t * 10;
  }
  return { opacity, rise, localTime, duration };
}

// Subtle ambient "water" gradient that drifts — used on pearl scenes.
function AmbientPearl() {
  const { localTime } = useSprite();
  const drift = Math.sin(localTime * 0.35) * 2;
  return (
    <div style={{
      position:'absolute', inset:0,
      background:`radial-gradient(1200px 700px at ${50+drift}% ${30+drift*0.5}%, rgba(204,211,219,0.55) 0%, rgba(244,242,240,0) 55%),
                  linear-gradient(160deg, #faf8f6 0%, #f5f2ef 44%, #ebe8e4 100%)`,
    }}/>
  );
}
function AmbientDark() {
  const { localTime } = useSprite();
  const drift = Math.sin(localTime * 0.4) * 3;
  return (
    <div style={{
      position:'absolute', inset:0,
      background:`radial-gradient(900px 600px at ${40+drift}% ${70+drift*0.5}%, rgba(146,164,182,0.12) 0%, rgba(12,17,23,0) 55%),
                  linear-gradient(160deg, #0c1117 0%, #121923 44%, #0d141b 100%)`,
    }}/>
  );
}

// Grid of vertical rule lines — editorial framing device.
function RuleLines({ color = "rgba(85,89,94,0.12)", count = 12 }) {
  const lines = [];
  for (let i = 1; i < count; i++) {
    lines.push(
      <div key={i} style={{
        position:'absolute', top:0, bottom:0,
        left:`${(i/count)*100}%`, width:1, background:color,
      }}/>
    );
  }
  return <>{lines}</>;
}

// Spec label (monospace, small caps, tracked)
function SpecLabel({ children, color = BRAND.inkSoft, size = 13 }) {
  return (
    <span style={{
      fontFamily: FONTS.mono, fontSize: size,
      letterSpacing: '0.22em', textTransform:'uppercase',
      color,
    }}>{children}</span>
  );
}

// Thin corner ticks — editorial frame marks
function CornerTicks({ color = "rgba(85,89,94,0.4)", inset = 40, len = 28 }) {
  const tick = { position:'absolute', background:color };
  return (
    <>
      {/* TL */}
      <div style={{...tick, left:inset, top:inset, width:len, height:1}}/>
      <div style={{...tick, left:inset, top:inset, width:1, height:len}}/>
      {/* TR */}
      <div style={{...tick, right:inset, top:inset, width:len, height:1}}/>
      <div style={{...tick, right:inset, top:inset, width:1, height:len}}/>
      {/* BL */}
      <div style={{...tick, left:inset, bottom:inset, width:len, height:1}}/>
      <div style={{...tick, left:inset, bottom:inset, width:1, height:len}}/>
      {/* BR */}
      <div style={{...tick, right:inset, bottom:inset, width:len, height:1}}/>
      <div style={{...tick, right:inset, bottom:inset, width:1, height:len}}/>
    </>
  );
}

// Running header — always visible faint label at top
function RunningHeader({ label = "RAINWATER", chapter, idx, total, dark=false }) {
  const c = dark ? BRAND.darkMute : BRAND.inkMute;
  return (
    <div style={{
      position:'absolute', left:60, right:60, top:40,
      display:'flex', justifyContent:'space-between', alignItems:'center',
      fontFamily: FONTS.mono, fontSize:12, letterSpacing:'0.28em',
      textTransform:'uppercase', color:c,
    }}>
      <span>◇ {label}</span>
      <span>{chapter}</span>
      <span style={{fontVariantNumeric:'tabular-nums'}}>
        {String(idx).padStart(2,'0')} / {String(total).padStart(2,'0')}
      </span>
    </div>
  );
}

// Bottom timecode strip
function Timecode({ dark=false }) {
  const { time } = useTimeline();
  const c = dark ? BRAND.darkMute : BRAND.inkMute;
  const mm = String(Math.floor(time / 60)).padStart(2,'0');
  const ss = String(Math.floor(time % 60)).padStart(2,'0');
  const ff = String(Math.floor((time*30)%30)).padStart(2,'0');
  return (
    <div style={{
      position:'absolute', left:60, right:60, bottom:36,
      display:'flex', justifyContent:'space-between', alignItems:'center',
      fontFamily: FONTS.mono, fontSize:11, letterSpacing:'0.24em',
      textTransform:'uppercase', color:c,
    }}>
      <span>T — {mm}:{ss}:{ff}</span>
      <span>rainwater.run</span>
    </div>
  );
}

// Kinetic reveal line — word-by-word reveal with gentle rise
function KineticLine({ words, startDelay = 0, perWord = 0.12, style = {} }) {
  const { localTime } = useSprite();
  return (
    <div style={{ display:'block', wordSpacing:'0.15em', ...style }}>
      {words.map((w, i) => {
        const t = clamp((localTime - (startDelay + i*perWord)) / 0.5, 0, 1);
        const eased = Easing.easeOutCubic(t);
        const isLast = i === words.length - 1;
        return (
          <React.Fragment key={i}>
            <span style={{
              display:'inline-block',
              opacity: eased,
              transform:`translateY(${(1-eased)*14}px)`,
              marginRight: isLast ? 0 : '0.28em',
              willChange:'transform, opacity',
            }}>{w}</span>
            {!isLast && <span>{' '}</span>}
          </React.Fragment>
        );
      })}
    </div>
  );
}

// Counter that tweens from 0 → value
function CountUp({ to, start=0, dur=1.2, prefix='', suffix='', decimals=0, style={} }) {
  const { localTime } = useSprite();
  const t = Easing.easeOutCubic(clamp((localTime - start) / dur, 0, 1));
  const v = to * t;
  const formatted = decimals > 0 ? v.toFixed(decimals) : Math.round(v).toLocaleString();
  return <span style={{fontVariantNumeric:'tabular-nums', ...style}}>{prefix}{formatted}{suffix}</span>;
}

// ════════════════════════════════════════════════════════════════════════════
// SCENE 1 — COLD OPEN (0.0 – 9.0s)
// "An agent that watches the market so you don't have to."
// ════════════════════════════════════════════════════════════════════════════

function Scene1_ColdOpen() {
  const { localTime } = useSprite();
  return (
    <div style={{position:'absolute', inset:0, background: BRAND.pearl, color: BRAND.ink, fontFamily: FONTS.sans}}>
      <AmbientPearl/>
      <CornerTicks/>
      <RunningHeader chapter="INTRO" idx={1} total={9}/>
      <Timecode/>

      {/* Center column */}
      <div style={{position:'absolute', left:0, right:0, top:'38%', textAlign:'center'}}>
        <div style={{marginBottom:20, opacity: clamp(localTime/0.7,0,1)}}>
          <SpecLabel>For savers, not traders</SpecLabel>
        </div>

        <div style={{fontFamily: FONTS.serif, fontSize:96, lineHeight:1.02, fontWeight:400, letterSpacing:'-0.01em', color: BRAND.ink}}>
          <KineticLine
            words={["A","smarter","place"]}
            startDelay={0.6} perWord={0.14}
          />
          <div style={{fontStyle:'italic', color: BRAND.accentDeep, marginTop:8}}>
            <KineticLine
              words={["to","park","your","money."]}
              startDelay={1.8} perWord={0.14}
            />
          </div>
        </div>

        <div style={{marginTop:56, opacity: clamp((localTime-3.8)/0.8,0,1)}}>
          <SpecLabel size={11}>◇ Rainwater · rainwater.run</SpecLabel>
        </div>
      </div>
    </div>
  );
}

// ════════════════════════════════════════════════════════════════════════════
// SCENE 2 — THE TIME PROBLEM (9.0 – 22.0s)
// Bloomberg-quiet: opportunity cost of staring at charts.
// ════════════════════════════════════════════════════════════════════════════

function Scene2_TimeProblem() {
  const { localTime } = useSprite();
  // Clock hand rotation
  const angle = localTime * 60; // slow sweep
  return (
    <div style={{position:'absolute', inset:0, background: BRAND.dark, color: BRAND.darkText, fontFamily: FONTS.sans}}>
      <AmbientDark/>
      <RuleLines count={16} color="rgba(146,164,182,0.06)"/>
      <CornerTicks color="rgba(146,164,182,0.35)"/>
      <RunningHeader chapter="WHY PEOPLE MISS OUT" idx={2} total={9} dark/>
      <Timecode dark/>

      {/* Left: clock */}
      <div style={{position:'absolute', left:90, top:'50%', transform:'translateY(-50%)'}}>
        <div style={{position:'relative', width:280, height:280}}>
          {/* outer ring */}
          <div style={{position:'absolute', inset:0, borderRadius:'50%', border:`1px solid ${BRAND.darkBorder}`}}/>
          <div style={{position:'absolute', inset:18, borderRadius:'50%', border:`1px solid rgba(146,164,182,0.1)`}}/>
          {/* ticks */}
          {Array.from({length:60}).map((_,i)=>{
            const a = (i/60)*360;
            const major = i % 5 === 0;
            return (
              <div key={i} style={{
                position:'absolute', left:'50%', top:'50%',
                width:1, height: major ? 14 : 6,
                background: major ? BRAND.accent : 'rgba(146,164,182,0.35)',
                transformOrigin:'center 130px',
                transform:`translate(-50%, -50%) rotate(${a}deg) translateY(-125px)`,
              }}/>
            );
          })}
          {/* minute hand */}
          <div style={{
            position:'absolute', left:'50%', top:'50%',
            width:2, height:105, background: BRAND.accentSoft,
            transformOrigin:'center top',
            transform:`translate(-50%, 0) rotate(${angle}deg)`,
          }}/>
          {/* hour hand */}
          <div style={{
            position:'absolute', left:'50%', top:'50%',
            width:3, height:72, background: BRAND.accent,
            transformOrigin:'center top',
            transform:`translate(-50%, 0) rotate(${angle*0.3}deg)`,
          }}/>
          <div style={{position:'absolute', left:'50%', top:'50%', width:10, height:10, background:BRAND.accent, borderRadius:'50%', transform:'translate(-50%,-50%)'}}/>
        </div>
      </div>

      {/* Right: copy — scaled up for the average saver */}
      <div style={{position:'absolute', left:'42%', right:100, top:'50%', transform:'translateY(-50%)', paddingLeft:40}}>
        <div style={{marginBottom:24, opacity: clamp(localTime/0.6,0,1)}}>
          <SpecLabel color={BRAND.accent}>01 — A better way to grow your money</SpecLabel>
        </div>
        <div style={{fontFamily: FONTS.serif, fontSize:104, lineHeight:1.02, fontWeight:400, letterSpacing:'-0.02em'}}>
          <KineticLine
            words={["Your","savings","account"]}
            startDelay={0.8} perWord={0.12}
          />
          <div style={{fontStyle:'italic', color: BRAND.accent, marginTop:6}}>
            <KineticLine
              words={["barely","grows."]}
              startDelay={1.9} perWord={0.12}
            />
          </div>
        </div>

        <div style={{marginTop:40, opacity: clamp((localTime-4.2)/0.8,0,1), fontFamily: FONTS.sans, fontSize:26, lineHeight:1.5, color: BRAND.darkMute, maxWidth:680}}>
          Saving for a home, a car, or retirement shouldn't mean settling for 4%. MISTER goes to work while you do.
        </div>
      </div>
    </div>
  );
}

// ════════════════════════════════════════════════════════════════════════════
// SCENE 3 — WHAT RAINWATER IS (22.0 – 36.0s)
// MISTER runs the logic on QQQ options. You copy.
// ════════════════════════════════════════════════════════════════════════════

function Scene3_WhatItIs() {
  const { localTime } = useSprite();
  return (
    <div style={{position:'absolute', inset:0, background: BRAND.pearl, color: BRAND.ink, fontFamily: FONTS.sans}}>
      <AmbientPearl/>
      <CornerTicks/>
      <RunningHeader chapter="WHAT RAINWATER IS" idx={3} total={9}/>
      <Timecode/>

      {/* Big serif statement */}
      <div style={{position:'absolute', left:120, right:120, top:'11%'}}>
        <div style={{marginBottom:28, opacity: clamp(localTime/0.6,0,1)}}>
          <SpecLabel>02 — Definition</SpecLabel>
        </div>
        <div style={{fontFamily: FONTS.serif, fontSize:152, lineHeight:1.0, letterSpacing:'-0.02em', fontWeight:400}}>
          <KineticLine words={["Put","your","money"]} startDelay={0.7} perWord={0.12}/>
          <div>
            <KineticLine words={["to","work."]} startDelay={1.5} perWord={0.12} style={{color: BRAND.accentDeep, fontStyle:'italic'}}/>
          </div>
        </div>
      </div>

      {/* Three spec cards — large, fill the lower half */}
      <div style={{position:'absolute', left:120, right:120, top:540, bottom:110, display:'grid', gridTemplateColumns:'repeat(3, 1fr)', gap:28}}>
        {[
          {k:"WHAT IT TRADES", v:"QQQ",   sub:"The biggest tech stocks, in one ticker", foot:"◇ the stuff you already know"},
          {k:"WHO'S DRIVING",  v:"MISTER", sub:"The operator reading the market every second", foot:"◇ logic, not emotion"},
          {k:"WHAT YOU DO",    v:"Nothing", sub:"Trades show up in your own account", foot:"◇ you keep your money, we send signals"},
        ].map((c,i)=>{
          const t = clamp((localTime - (3.0 + i*0.25)) / 0.7, 0, 1);
          const eased = Easing.easeOutCubic(t);
          return (
            <div key={i} style={{
              opacity:eased,
              transform:`translateY(${(1-eased)*24}px)`,
              padding:'40px 42px 42px',
              background:'rgba(255,255,255,0.65)',
              border:`1px solid ${BRAND.accentSoft}`,
              borderRadius:2,
              display:'flex',
              flexDirection:'column',
              justifyContent:'space-between',
              minHeight: 340,
              position:'relative',
              overflow:'hidden',
            }}>
              {/* corner index */}
              <div style={{position:'absolute', top:18, right:22, fontFamily: FONTS.mono, fontSize:11, color: BRAND.inkMute, letterSpacing:'0.22em'}}>
                0{i+1} / 03
              </div>
              <div>
                <div style={{marginBottom:22}}>
                  <SpecLabel size={15}>{c.k}</SpecLabel>
                </div>
                <div style={{fontFamily: FONTS.serif, fontSize:108, lineHeight:0.98, color: BRAND.ink, letterSpacing:'-0.025em', fontWeight:400}}>
                  {c.v}
                </div>
                <div style={{marginTop:22, fontFamily: FONTS.serif, fontStyle:'italic', fontSize:32, color: BRAND.accentDeep, letterSpacing:'0', lineHeight:1.3}}>
                  {c.sub}
                </div>
              </div>
              <div style={{marginTop:28, paddingTop:16, borderTop:`1px solid ${BRAND.accentSoft}`, fontFamily: FONTS.mono, fontSize:15, color: BRAND.inkMute, letterSpacing:'0.16em', textTransform:'uppercase'}}>
                {c.foot}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

// ════════════════════════════════════════════════════════════════════════════
// SCENE 4 — HOW IT WORKS, 3 STEPS (36.0 – 58.0s)
// Sign in → Connect broker → Trades copy
// ════════════════════════════════════════════════════════════════════════════

function Scene4_ThreeSteps() {
  const { localTime } = useSprite();
  const steps = [
    { n:"01", label:"SIGN UP",        head:"Join the club.",              sub:"Sign in with Discord. Takes 10 seconds.",           t0:0.3 },
    { n:"02", label:"LINK YOUR ACCOUNT", head:"Connect your brokerage.",        sub:"Your money stays in your account. We never hold it.",  t0:2.2 },
    { n:"03", label:"SIT BACK",    head:"MISTER does the work.", sub:"When he buys, you buy. Same trade, same second.", t0:4.1 },
  ];
  return (
    <div style={{position:'absolute', inset:0, background: BRAND.dark, color: BRAND.darkText, fontFamily: FONTS.sans}}>
      <AmbientDark/>
      <RuleLines count={18} color="rgba(146,164,182,0.05)"/>
      <CornerTicks color="rgba(146,164,182,0.35)"/>
      <RunningHeader chapter="HOW YOU START" idx={4} total={9} dark/>
      <Timecode dark/>

      <div style={{position:'absolute', left:120, top:130}}>
        <SpecLabel color={BRAND.accent}>03 — Three steps</SpecLabel>
      </div>

      {/* Horizontal step ladder */}
      <div style={{position:'absolute', left:120, right:120, top:220, bottom:140, display:'flex', flexDirection:'column', justifyContent:'space-between'}}>
        {steps.map((s, i) => {
          const t = clamp((localTime - s.t0) / 0.7, 0, 1);
          const eased = Easing.easeOutCubic(t);
          return (
            <div key={i} style={{
              display:'grid', gridTemplateColumns:'200px 1fr auto', gap:56, alignItems:'center',
              borderTop: i===0 ? 'none' : `1px solid ${BRAND.darkBorder}`,
              paddingTop: i===0 ? 0 : 36,
              opacity: eased,
              transform:`translateX(${(1-eased)*-30}px)`,
            }}>
              <div style={{fontFamily: FONTS.serif, fontSize:140, lineHeight:1, color: BRAND.accent, fontStyle:'italic', letterSpacing:'-0.02em'}}>
                {s.n}
              </div>
              <div>
                <div style={{marginBottom:14}}>
                  <SpecLabel color={BRAND.accentSoft} size={16}>{s.label}</SpecLabel>
                </div>
                <div style={{fontFamily: FONTS.serif, fontSize:72, lineHeight:1.05, letterSpacing:'-0.015em'}}>
                  {s.head}
                </div>
                <div style={{marginTop:14, fontFamily: FONTS.sans, fontSize:28, lineHeight:1.4, color: BRAND.darkMute, maxWidth:780}}>
                  {s.sub}
                </div>
              </div>
              <div style={{fontFamily: FONTS.mono, fontSize:15, color: BRAND.darkMute, letterSpacing:'0.24em', writingMode:'vertical-rl', transform:'rotate(180deg)'}}>
                {i === 0 ? "FREE TO JOIN" : i === 1 ? "YOUR MONEY, YOUR BANK" : "AUTOMATIC"}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

// ════════════════════════════════════════════════════════════════════════════
// SCENE 5 — YOUR FUNDS, YOUR BROKER (58.0 – 78.0s)
// No custody. No lock-up. Monthly. Cancel anytime.
// ════════════════════════════════════════════════════════════════════════════

function Scene5_NoCustody() {
  const { localTime } = useSprite();
  // Animate signal dots fanning from center to three brokers
  return (
    <div style={{position:'absolute', inset:0, background: BRAND.pearl, color: BRAND.ink, fontFamily: FONTS.sans}}>
      <AmbientPearl/>
      <CornerTicks/>
      <RunningHeader chapter="CUSTODY · LOCK-UP" idx={5} total={9}/>
      <Timecode/>

      {/* Headline top-left */}
      <div style={{position:'absolute', left:120, top:130, maxWidth:720}}>
        <div style={{marginBottom:20, opacity: clamp(localTime/0.6,0,1)}}>
          <SpecLabel>04 — We never touch your money</SpecLabel>
        </div>
        <div style={{fontFamily: FONTS.serif, fontSize:68, lineHeight:1.04, letterSpacing:'-0.015em'}}>
          <KineticLine words={["Your","money","stays","with","your","bank."]} startDelay={0.7} perWord={0.11}/>
          <div style={{color: BRAND.accentDeep, fontStyle:'italic', marginTop:6}}>
            <KineticLine words={["We","never","hold","a","single","dollar."]} startDelay={2.0} perWord={0.11}/>
          </div>
        </div>
      </div>

      {/* Diagram: large, centered lane */}
      <div style={{position:'absolute', left:120, right:120, top:380, bottom:200}}>
        <FundsDiagram localTime={localTime}/>
      </div>

      {/* Three guarantees bar — larger */}
      <div style={{position:'absolute', left:120, right:120, bottom:70, display:'flex', gap:56, justifyContent:'space-between', fontFamily: FONTS.mono, fontSize:18, letterSpacing:'0.2em', textTransform:'uppercase', color: BRAND.inkSoft}}>
        {[
          ["YOUR BANK HOLDS IT", "We never touch your money"],
          ["CANCEL ANYTIME", "Monthly. No contract."],
          ["$99 / MONTH", "One price. That's it."],
        ].map(([k,v], i) => {
          const t = clamp((localTime - (6.5 + i*0.25)) / 0.5, 0, 1);
          const eased = Easing.easeOutCubic(t);
          return (
            <div key={i} style={{flex:1, borderTop:`1px solid ${BRAND.inkSoft}`, paddingTop:18, opacity:eased, transform:`translateY(${(1-eased)*10}px)`}}>
              <div style={{color: BRAND.ink, fontWeight:500, fontSize:22}}>{k}</div>
              <div style={{marginTop:8, textTransform:'none', letterSpacing:'0.04em', fontSize:18, color: BRAND.inkMute}}>{v}</div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

function FundsDiagram({ localTime }) {
  // Single large lane: MISTER → secure link → PUBLIC
  const active = clamp((localTime - 2.8) / 0.8, 0, 1);
  const p = clamp((localTime - 3.2) / 1.8, 0, 1);
  const pEase = Easing.easeInOutCubic(p);

  const W = 1680, H = 340;
  const laneStart = 320, laneEnd = W - 320;
  const midX = (laneStart + laneEnd) / 2;
  const y = H / 2;
  const px = laneStart + (laneEnd - laneStart) * pEase;

  return (
    <div style={{position:'relative', width:'100%', opacity: active}}>
      <svg viewBox={`0 0 ${W} ${H}`} style={{width:'100%', height:'auto', display:'block'}} preserveAspectRatio="xMidYMid meet">
        <defs>
          <linearGradient id="laneGrad" x1="0" x2="1" y1="0" y2="0">
            <stop offset="0%" stopColor={BRAND.accentSoft}/>
            <stop offset="50%" stopColor={BRAND.accent}/>
            <stop offset="100%" stopColor={BRAND.accentDeep}/>
          </linearGradient>
        </defs>

        {/* lane track */}
        <line x1={laneStart} x2={laneEnd} y1={y} y2={y}
          stroke="url(#laneGrad)" strokeWidth="3"/>

        {/* tick marks */}
        {Array.from({length:28}).map((_,i)=>{
          const tx = laneStart + i * (laneEnd - laneStart) / 27;
          return <line key={i} x1={tx} x2={tx} y1={y-10} y2={y+10} stroke={BRAND.accentSoft} strokeWidth="1"/>;
        })}

        {/* mid joint */}
        <circle cx={midX} cy={y} r="10" fill={BRAND.accentDeep}/>
        <circle cx={midX} cy={y} r="24" fill="none" stroke={BRAND.accentDeep} strokeWidth="1" opacity="0.35"/>

        {/* pulse */}
        {p > 0 && p < 1 && (
          <>
            <circle cx={px} cy={y} r="14" fill={BRAND.accentDeep}/>
            <circle cx={px} cy={y} r="30" fill={BRAND.accent} opacity="0.25"/>
          </>
        )}
      </svg>

      {/* Left node: MISTER */}
      <div style={{
        position:'absolute', left:0, top:'50%', transform:'translateY(-50%)',
        padding:'28px 38px', background: BRAND.ink, color: BRAND.pearl,
        fontFamily: FONTS.mono, fontSize:26, letterSpacing:'0.22em', textTransform:'uppercase',
      }}>
        ◇ MISTER
        <div style={{fontSize:16, color: BRAND.accentSoft, letterSpacing:'0.14em', textTransform:'none', marginTop:8}}>
          sends the trade signal
        </div>
      </div>

      {/* Middle pill */}
      <div style={{
        position:'absolute', left:'50%', top:'50%', transform:'translate(-50%, calc(-50% - 90px))',
        padding:'16px 30px', border:`1.5px solid ${BRAND.accentDeep}`, background:'rgba(255,255,255,0.9)',
        fontFamily: FONTS.mono, fontSize:18, letterSpacing:'0.24em', textTransform:'uppercase', color: BRAND.accentDeep,
      }}>secure link</div>

      {/* Right node: PUBLIC */}
      <div style={{
        position:'absolute', right:0, top:'50%', transform:'translateY(-50%)',
        padding:'28px 38px', background:'rgba(255,255,255,0.9)', border:`1.5px solid ${BRAND.accentDeep}`,
        fontFamily: FONTS.mono, fontSize:26, letterSpacing:'0.22em', color: BRAND.ink, textAlign:'right',
      }}>
        PUBLIC
        <div style={{fontSize:16, color: BRAND.inkMute, letterSpacing:'0.14em', textTransform:'none', marginTop:8}}>
          your account · your money
        </div>
      </div>
    </div>
  );
}

// ════════════════════════════════════════════════════════════════════════════
// SCENE 6 — SUB-SECOND EXECUTION (78.0 – 98.0s)
// Everyone fills at the same time. Terminal vibe.
// ════════════════════════════════════════════════════════════════════════════

function Scene6_Execution() {
  const { localTime } = useSprite();
  return (
    <div style={{position:'absolute', inset:0, background: BRAND.dark, color: BRAND.darkText, fontFamily: FONTS.sans}}>
      <AmbientDark/>
      <CornerTicks color="rgba(146,164,182,0.35)"/>
      <RunningHeader chapter="EXECUTION" idx={6} total={9} dark/>
      <Timecode dark/>

      {/* Big mono latency readout */}
      <div style={{position:'absolute', left:120, top:'24%', right:120}}>
        <div style={{marginBottom:20, opacity: clamp(localTime/0.6,0,1)}}>
          <SpecLabel color={BRAND.accent}>05 — Hands-free trading</SpecLabel>
        </div>
        <div style={{fontFamily: FONTS.serif, fontSize:64, lineHeight:1.04, letterSpacing:'-0.015em'}}>
          <KineticLine words={["MISTER","trades","for","you."]} startDelay={0.7} perWord={0.13}/>
          <div style={{color: BRAND.accent, fontStyle:'italic', marginTop:4}}>
            <KineticLine words={["You","do","nothing."]} startDelay={2.1} perWord={0.14}/>
          </div>
        </div>
      </div>

      {/* Terminal log */}
      <div style={{position:'absolute', left:120, right:120, bottom:130}}>
        <ExecutionLog localTime={localTime}/>
      </div>
    </div>
  );
}

function ExecutionLog({ localTime }) {
  const t0 = 2.5;
  const rows = [
    { d:0.00, who:"MISTER",  msg:"Spotted a move in QQQ options · BUYING" },
    { d:0.12, who:"AUTO-TRADE", msg:"Executing the trade for you · no action needed" },
    { d:0.28, who:"BROKER",  msg:"Order placed in your account automatically" },
    { d:0.51, who:"FILLED",  msg:"Your account → bought at $1.47 · hands-free"  , g:true},
    { d:0.58, who:"FILLED",  msg:"Another user → bought at $1.47"  , g:true},
    { d:0.71, who:"FILLED",  msg:"Another user → bought at $1.47"  , g:true},
    { d:0.83, who:"DONE",    msg:"Everyone is in · you didn't lift a finger"},
  ];

  return (
    <div style={{
      background: BRAND.darkSurface, border:`1px solid ${BRAND.darkBorder}`,
      padding:'24px 28px', fontFamily: FONTS.mono, fontSize:15, lineHeight:1.7,
    }}>
      <div style={{display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:14, color: BRAND.darkMute, fontSize:11, letterSpacing:'0.22em', textTransform:'uppercase'}}>
        <span>◇ LIVE TRADE FEED</span>
        <span>4:31 PM ET</span>
      </div>
      {rows.map((r, i) => {
        const appear = clamp((localTime - (t0 + r.d*1.5)) / 0.25, 0, 1);
        return (
          <div key={i} style={{opacity: appear, display:'grid', gridTemplateColumns:'70px 140px 1fr', gap:20, color: r.g ? BRAND.green : BRAND.darkText}}>
            <span style={{color: BRAND.darkMute, fontVariantNumeric:'tabular-nums'}}>+{r.d.toFixed(2)}s</span>
            <span style={{color: BRAND.accent}}>{r.who}</span>
            <span>{r.msg}</span>
          </div>
        );
      })}
    </div>
  );
}

// ════════════════════════════════════════════════════════════════════════════
// SCENE 7 — BACKTEST vs FORWARD TEST (98.0 – 122.0s)
// Two equity curves, side by side. Results match.
// ════════════════════════════════════════════════════════════════════════════

function Scene7_BacktestVsForward() {
  const { localTime } = useSprite();
  return (
    <div style={{position:'absolute', inset:0, background: BRAND.pearl, color: BRAND.ink, fontFamily: FONTS.sans}}>
      <AmbientPearl/>
      <CornerTicks/>
      <RunningHeader chapter="PROOF" idx={7} total={9}/>
      <Timecode/>

      <div style={{position:'absolute', left:120, top:130, maxWidth:820}}>
        <div style={{marginBottom:18, opacity: clamp(localTime/0.6,0,1)}}>
          <SpecLabel>06 — Does it actually work?</SpecLabel>
        </div>
        <div style={{fontFamily: FONTS.serif, fontSize:60, lineHeight:1.04, letterSpacing:'-0.015em'}}>
          <KineticLine words={["We","tested","it","on","history."]} startDelay={0.6} perWord={0.12}/>
          <div style={{color: BRAND.accentDeep, fontStyle:'italic', marginTop:4}}>
            <KineticLine words={["It","still","works."]} startDelay={1.8} perWord={0.14}/>
          </div>
        </div>
      </div>

      {/* Two panels */}
      <div style={{position:'absolute', left:120, right:120, bottom:90, top:340, display:'grid', gridTemplateColumns:'1fr 1fr', gap:32}}>
        <EquityPanel
          title="PAST" subtitle="Tested on 5+ years of real market data"
          localTime={localTime - 2.4}
          seed={1}
        />
        <EquityPanel
          title="PRESENT" subtitle="Live trades, running right now"
          localTime={localTime - 2.8}
          seed={2}
        />
      </div>
    </div>
  );
}

function EquityPanel({ title, subtitle, localTime, seed }) {
  // Deterministic wiggly-but-up equity curve
  const N = 80;
  const points = React.useMemo(() => {
    const pts = [];
    let v = 0;
    for (let i = 0; i < N; i++) {
      // slight randomness by seed but monotonic-ish
      const noise = Math.sin(i * 0.5 + seed * 2.1) * 0.6 + Math.sin(i * 1.3 + seed) * 0.3;
      v += 0.35 + noise * 0.18;
      pts.push(Math.max(0, v));
    }
    const max = Math.max(...pts);
    return pts.map((p,i) => [i/(N-1), p/max]);
  }, [seed]);

  const W = 560, H = 280, pad = 16;
  const reveal = Easing.easeOutCubic(clamp(localTime / 1.8, 0, 1));
  const cutoff = Math.floor(points.length * reveal);
  const path = points.slice(0, cutoff+1).map(([x,y], i) => {
    const X = pad + x * (W - pad*2);
    const Y = H - pad - y * (H - pad*2);
    return `${i===0?'M':'L'}${X.toFixed(1)},${Y.toFixed(1)}`;
  }).join(' ');
  const areaPath = path + ` L${(pad + ((cutoff)/(N-1))*(W-pad*2)).toFixed(1)},${H-pad} L${pad},${H-pad} Z`;

  return (
    <div style={{
      padding:'24px 26px 28px',
      background:'rgba(255,255,255,0.55)',
      border:`1px solid ${BRAND.accentSoft}`,
      display:'flex', flexDirection:'column', gap:14,
    }}>
      <div style={{display:'flex', justifyContent:'space-between', alignItems:'baseline'}}>
        <SpecLabel>{title}</SpecLabel>
        <div style={{fontFamily: FONTS.mono, fontSize:11, color: BRAND.inkMute, letterSpacing:'0.18em'}}>{subtitle}</div>
      </div>

      <svg viewBox={`0 0 ${W} ${H}`} style={{width:'100%', height:'auto'}}>
        {/* gridlines */}
        {[0.25, 0.5, 0.75].map(g => (
          <line key={g} x1={pad} x2={W-pad} y1={pad + g*(H-pad*2)} y2={pad + g*(H-pad*2)} stroke="rgba(85,89,94,0.08)" strokeDasharray="2 4"/>
        ))}
        <path d={areaPath} fill={`rgba(146,164,182,0.18)`}/>
        <path d={path} fill="none" stroke={BRAND.accentDeep} strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/>
        {/* endpoint dot */}
        {cutoff < N && (
          <circle cx={pad + points[cutoff][0]*(W-pad*2)} cy={H - pad - points[cutoff][1]*(H-pad*2)} r="3" fill={BRAND.accentDeep}/>
        )}
      </svg>

      {/* metric strip */}
      <div style={{display:'grid', gridTemplateColumns:'repeat(3, 1fr)', gap:12, marginTop:4, paddingTop:14, borderTop:`1px solid ${BRAND.accentSoft}`}}>
        {title === "PAST" ? (
          <>
            <Metric label="TRADES" value={<CountUp to={294} start={0.2} dur={1.4}/>}/>
            <Metric label="WIN RATE" value={<><CountUp to={77.2} start={0.3} dur={1.4} decimals={1}/>%</>}/>
            <Metric label="PROFIT RATIO" value={<CountUp to={3.47} start={0.4} dur={1.4} decimals={2}/>}/>
          </>
        ) : (
          <>
            <Metric label="WIN RATE" value={<><CountUp to={76.1} start={0.3} dur={1.4} decimals={1}/>%</>}/>
            <Metric label="PROFIT RATIO" value={<CountUp to={3.31} start={0.4} dur={1.4} decimals={2}/>}/>
            <Metric label="MATCHES PAST" value="✓"/>
          </>
        )}
      </div>
    </div>
  );
}

function Metric({ label, value }) {
  return (
    <div>
      <div style={{fontFamily: FONTS.mono, fontSize:10, letterSpacing:'0.22em', color: BRAND.inkMute, textTransform:'uppercase'}}>{label}</div>
      <div style={{fontFamily: FONTS.serif, fontSize:32, lineHeight:1, marginTop:6, color: BRAND.ink}}>{value}</div>
    </div>
  );
}

// ════════════════════════════════════════════════════════════════════════════
// SCENE 8 — LIVE TRACK RECORD (122.0 – 148.0s)
// 294 trades · 77.2% WR · 3.47 PF · +$24,758
// ════════════════════════════════════════════════════════════════════════════

function Scene8_TrackRecord() {
  const { localTime } = useSprite();
  return (
    <div style={{position:'absolute', inset:0, background: BRAND.dark, color: BRAND.darkText, fontFamily: FONTS.sans}}>
      <AmbientDark/>
      <RuleLines count={20} color="rgba(146,164,182,0.05)"/>
      <CornerTicks color="rgba(146,164,182,0.4)"/>
      <RunningHeader chapter="THE RESULTS" idx={8} total={9} dark/>
      <Timecode dark/>

      {/* Label + benchmark */}
      <div style={{position:'absolute', left:120, top:130}}>
        <SpecLabel color={BRAND.accent}>07 — What MISTER made so far</SpecLabel>
      </div>

      <div style={{position:'absolute', left:120, right:120, top:200, display:'grid', gridTemplateColumns:'1.2fr 1fr', gap:64}}>

        {/* Left: headline P&L */}
        <div>
          <div style={{fontFamily: FONTS.mono, fontSize:11, letterSpacing:'0.24em', color: BRAND.darkMute, textTransform:'uppercase', marginBottom:10}}>
            Money made
          </div>
          <div style={{fontFamily: FONTS.serif, fontSize:180, lineHeight:0.95, color: BRAND.pearl, letterSpacing:'-0.03em', fontWeight:400}}>
            +$<CountUp to={24758} start={0.5} dur={2.4}/>
          </div>
          <div style={{fontFamily: FONTS.serif, fontStyle:'italic', fontSize:32, color: BRAND.accent, marginTop:10}}>
            across 294 completed trades.
          </div>

          <div style={{marginTop:36, fontFamily: FONTS.sans, fontSize:18, color: BRAND.darkMute, maxWidth:500, lineHeight:1.55}}>
            Every single trade is logged and posted daily. These numbers come straight from the brokerage — not a slide.
          </div>
        </div>

        {/* Right: stat grid */}
        <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:2, background: BRAND.darkBorder, border:`1px solid ${BRAND.darkBorder}`}}>
          {[
            {k:"WIN RATE",    v:<><CountUp to={77.2} start={0.8} dur={1.6} decimals={1}/><span style={{fontFamily:FONTS.sans, fontSize:34}}>%</span></>, sub:"227 wins · 67 losses"},
            {k:"PROFIT RATIO", v:<CountUp to={3.47} start={0.9} dur={1.6} decimals={2}/>, sub:"wins vs. losses"},
            {k:"BIGGEST DIP", v:<><span style={{fontFamily:FONTS.sans, fontSize:34}}>$</span><CountUp to={573.6} start={1.0} dur={1.6} decimals={2}/></>, sub:"worst stretch"},
            {k:"TRADES",      v:<CountUp to={294} start={1.1} dur={1.6}/>, sub:"finished so far"},
          ].map((s,i) => {
            const t = clamp((localTime - (1.3 + i*0.15)) / 0.5, 0, 1);
            const eased = Easing.easeOutCubic(t);
            return (
              <div key={i} style={{
                padding:'28px 26px', background: BRAND.darkSurface,
                opacity:eased, transform:`translateY(${(1-eased)*10}px)`,
              }}>
                <div style={{fontFamily: FONTS.mono, fontSize:10, letterSpacing:'0.24em', color: BRAND.darkMute, marginBottom:14}}>
                  {s.k}
                </div>
                <div style={{fontFamily: FONTS.serif, fontSize:54, lineHeight:1, color: BRAND.pearl, letterSpacing:'-0.02em'}}>
                  {s.v}
                </div>
                <div style={{marginTop:10, fontFamily: FONTS.mono, fontSize:10, color: BRAND.darkMute, letterSpacing:'0.08em'}}>
                  {s.sub}
                </div>
              </div>
            );
          })}
        </div>
      </div>

      {/* Small print */}
      <div style={{position:'absolute', left:120, right:120, bottom:80, fontFamily: FONTS.mono, fontSize:11, letterSpacing:'0.2em', textTransform:'uppercase', color: BRAND.darkMute, display:'flex', justifyContent:'space-between'}}>
        <span>◇ updated daily from the brokerage</span>
        <span>refreshed · 16:15 ET</span>
      </div>
    </div>
  );
}

// ════════════════════════════════════════════════════════════════════════════
// SCENE 9 — PRICING & CTA (148.0 – 180.0s)
// Free Intel via Discord → Copy Trade $99/mo
// ════════════════════════════════════════════════════════════════════════════

function Scene9_CTA() {
  const { localTime } = useSprite();
  return (
    <div style={{position:'absolute', inset:0, background: BRAND.pearl, color: BRAND.ink, fontFamily: FONTS.sans}}>
      <AmbientPearl/>
      <CornerTicks/>
      <RunningHeader chapter="HOW TO START" idx={9} total={9}/>
      <Timecode/>

      {/* Headline */}
      <div style={{position:'absolute', left:120, right:120, top:'14%'}}>
        <div style={{marginBottom:18, opacity: clamp(localTime/0.6,0,1)}}>
          <SpecLabel>08 — Two ways to start</SpecLabel>
        </div>
        <div style={{fontFamily: FONTS.serif, fontSize:90, lineHeight:1.02, letterSpacing:'-0.02em'}}>
          <KineticLine words={["Start","free.","Pay","when"]} startDelay={0.6} perWord={0.12}/>
          <div style={{color: BRAND.accentDeep, fontStyle:'italic'}}>
            <KineticLine words={["you","want","the","trades."]} startDelay={1.7} perWord={0.12}/>
          </div>
        </div>
      </div>

      {/* Two plan cards */}
      <div style={{position:'absolute', left:120, right:120, bottom:140, display:'grid', gridTemplateColumns:'1fr 1fr', gap:32}}>
        <PlanCard
          appearAt={2.2} localTime={localTime}
          tag="FREE" price="$0" cadence="" title="Daily tips on Discord"
          body="Morning rundown, simple calculator, daily watchlist, stock breakdowns. Join the Discord and it's all yours — forever free."
          cta="JOIN THE DISCORD"
          dark={false}
        />
        <PlanCard
          appearAt={2.5} localTime={localTime}
          tag="AUTO-TRADE" price="$99" cadence="/mo" title="MISTER trades for you"
          body="Trades show up in your own brokerage automatically. Cancel anytime. Your money never leaves your bank."
          cta="START AT rainwater.run"
          dark={true}
        />
      </div>
    </div>
  );
}

function PlanCard({ tag, price, cadence, title, body, cta, appearAt, localTime, dark }) {
  const t = clamp((localTime - appearAt) / 0.8, 0, 1);
  const eased = Easing.easeOutCubic(t);
  const bg = dark ? BRAND.ink : 'rgba(255,255,255,0.6)';
  const fg = dark ? BRAND.pearl : BRAND.ink;
  const mute = dark ? 'rgba(244,242,240,0.6)' : BRAND.inkSoft;
  const border = dark ? 'rgba(244,242,240,0.16)' : BRAND.accentSoft;
  return (
    <div style={{
      padding:'36px 38px 34px',
      background: bg, color: fg, border:`1px solid ${border}`,
      display:'flex', flexDirection:'column', justifyContent:'space-between',
      minHeight:320,
      opacity:eased, transform:`translateY(${(1-eased)*16}px)`,
    }}>
      <div>
        <div style={{display:'flex', justifyContent:'space-between', alignItems:'baseline'}}>
          <span style={{fontFamily: FONTS.mono, fontSize:11, letterSpacing:'0.26em', color: mute}}>{tag}</span>
          <span style={{fontFamily: FONTS.mono, fontSize:11, letterSpacing:'0.2em', color: mute}}>◇</span>
        </div>

        <div style={{marginTop:22, display:'flex', alignItems:'baseline', gap:6}}>
          <div style={{fontFamily: FONTS.serif, fontSize:88, lineHeight:1, letterSpacing:'-0.02em'}}>{price}</div>
          <div style={{fontFamily: FONTS.mono, fontSize:18, color: mute, letterSpacing:'0.1em'}}>{cadence}</div>
        </div>

        <div style={{marginTop:22, fontFamily: FONTS.serif, fontSize:28, fontStyle:'italic', color: dark ? BRAND.accentSoft : BRAND.accentDeep}}>
          {title}
        </div>

        <div style={{marginTop:16, fontFamily: FONTS.sans, fontSize:16, lineHeight:1.55, color: mute, maxWidth:480}}>
          {body}
        </div>
      </div>

      <div style={{marginTop:26, paddingTop:20, borderTop:`1px solid ${border}`, display:'flex', justifyContent:'space-between', alignItems:'center'}}>
        <span style={{fontFamily: FONTS.mono, fontSize:12, letterSpacing:'0.24em', color: fg}}>→ {cta}</span>
        <span style={{fontFamily: FONTS.mono, fontSize:10, letterSpacing:'0.18em', color: mute}}>
          {dark ? "YOUR MONEY STAYS WITH YOUR BANK" : "NO CREDIT CARD"}
        </span>
      </div>
    </div>
  );
}

// ════════════════════════════════════════════════════════════════════════════
// DISCLAIMER STRIP — always visible bottom, very subtle
// ════════════════════════════════════════════════════════════════════════════
// (Disclaimer baked into final scene to stay honest.)

// ─── Export scenes map ──────────────────────────────────────────────────────
Object.assign(window, {
  BRAND, FONTS,
  Scene1_ColdOpen, Scene2_TimeProblem, Scene3_WhatItIs,
  Scene4_ThreeSteps, Scene5_NoCustody, Scene6_Execution,
  Scene7_BacktestVsForward, Scene8_TrackRecord, Scene9_CTA,
});
