// scenes.jsx — TapeScript launch video scenes.
// Depends on animations.jsx + shared.jsx.

const lerp = (a, b, t) => a + (b - a) * clamp(t, 0, 1);
const stagger = (localTime, start, dur) => clamp((localTime - start) / dur, 0, 1);

// ════════════════════════════════════════════════════════════════════════
// SCENE 1 — The idea
// ════════════════════════════════════════════════════════════════════════
function SceneIdea() {
  const { localTime } = useSprite();
  const typeP = clamp((localTime - 0.7) / 3.3, 0, 1);
  const idea = "Buy the breakout above the prior-day high during the NY session — exit at a 2R target or the session close.";
  const kP = Easing.easeOutCubic(stagger(localTime, 0.1, 0.6));
  return (
    <Scene>
      <div style={{ position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column',
        alignItems: 'center', justifyContent: 'center', gap: 44, padding: '0 200px' }}>
        <Kicker style={{ opacity: kP, transform: `translateY(${(1 - kP) * 10}px)` }}>
          Every strategy starts as an idea
        </Kicker>
        <div style={{ width: 1120, maxWidth: '100%' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 20,
            opacity: clamp((localTime - 0.4) / 0.4, 0, 1) }}>
            <div style={{ width: 30, height: 30, borderRadius: 8, border: `1px solid ${COL.line}`,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontFamily: MONO, fontSize: 14, color: COL.dim }}>›</div>
            <div style={{ fontFamily: MONO, fontSize: 14, letterSpacing: '0.24em',
              textTransform: 'uppercase', color: COL.dimmer }}>your idea — in plain english</div>
          </div>
          <Panel style={{ padding: '40px 46px', borderRadius: 18 }}>
            <Typer text={idea} progress={typeP} style={{
              fontFamily: DISP, fontSize: 46, lineHeight: 1.34, color: COL.vanilla,
              fontWeight: 400, letterSpacing: '-0.01em' }} />
          </Panel>
        </div>
      </div>
    </Scene>
  );
}

// ════════════════════════════════════════════════════════════════════════
// SCENE 2 — Compile into executable logic
// ════════════════════════════════════════════════════════════════════════
const CODE_LINES = [
  { t: '// strategy.logic — generated by TapeScript', c: 'comment' },
  { t: 'strategy("ORB · NY Session", overlay = true)', c: 'code' },
  { t: '', c: 'blank' },
  { t: 'session = time(period, "0930-1600", "America/New_York")', c: 'code' },
  { t: 'pdh     = security(ticker, "D", high[1])', c: 'code' },
  { t: '', c: 'blank' },
  { t: 'long = crossover(close, pdh) and session', c: 'code' },
  { t: 'stop = close - atr(14)', c: 'code' },
  { t: 'tgt  = close + (close - stop) * 2.0', c: 'code' },
  { t: '', c: 'blank' },
  { t: 'if long', c: 'code' },
  { t: '    entry("L", long)', c: 'code' },
  { t: '    exit("X", stop = stop, limit = tgt)', c: 'code' },
];
const FORMATS = ['Plain English', 'Pine Script', 'Python', 'Research notes'];

function SceneCompile() {
  const { localTime } = useSprite();
  const kP = Easing.easeOutCubic(stagger(localTime, 0.1, 0.6));
  return (
    <Scene>
      <div style={{ position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column',
        alignItems: 'center', justifyContent: 'center', gap: 30, padding: '0 180px' }}>
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 22,
          opacity: kP, transform: `translateY(${(1 - kP) * 10}px)` }}>
          <Kicker>TapeScript compiles it into executable logic</Kicker>
          <div style={{ display: 'flex', gap: 12 }}>
            {FORMATS.map((f, i) => {
              const on = stagger(localTime, 0.5 + i * 0.12, 0.4);
              const active = i === 0;
              return (
                <div key={f} style={{
                  opacity: on, transform: `translateY(${(1 - on) * 8}px)`,
                  fontFamily: MONO, fontSize: 15, letterSpacing: '0.04em',
                  padding: '9px 16px', borderRadius: 999,
                  border: `1px solid ${active ? 'rgba(244,238,223,0.35)' : COL.line}`,
                  color: active ? COL.vanilla : COL.dim,
                  background: active ? 'rgba(244,238,223,0.06)' : 'transparent',
                  display: 'flex', alignItems: 'center', gap: 8 }}>
                  {active && <span style={{ fontSize: 13 }}>✓</span>}{f}
                </div>
              );
            })}
          </div>
        </div>
        <Panel style={{ width: 1080, padding: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '16px 22px',
            borderBottom: `1px solid ${COL.line}` }}>
            {[0, 1, 2].map(i => <div key={i} style={{ width: 11, height: 11, borderRadius: 99,
              border: `1px solid ${COL.line}` }} />)}
            <div style={{ marginLeft: 12, fontFamily: MONO, fontSize: 14, color: COL.dim }}>strategy.logic</div>
            <div style={{ marginLeft: 'auto', fontFamily: MONO, fontSize: 13, color: COL.dimmer,
              letterSpacing: '0.1em' }}>COMPILED</div>
          </div>
          <div style={{ padding: '26px 30px', fontFamily: MONO, fontSize: 21, lineHeight: 1.65 }}>
            {CODE_LINES.map((ln, i) => {
              const rp = stagger(localTime, 0.9 + i * 0.14, 0.45);
              if (ln.c === 'blank') return <div key={i} style={{ height: '1.65em' }} />;
              return (
                <div key={i} style={{ opacity: rp, transform: `translateX(${(1 - rp) * 12}px)`,
                  color: ln.c === 'comment' ? COL.dimmer : 'rgba(244,238,223,0.9)',
                  fontStyle: ln.c === 'comment' ? 'italic' : 'normal', whiteSpace: 'pre' }}>
                  {ln.t}
                </div>
              );
            })}
          </div>
        </Panel>
      </div>
    </Scene>
  );
}

// ════════════════════════════════════════════════════════════════════════
// SCENE 3 — Backtest on real data
// ════════════════════════════════════════════════════════════════════════
function Stat({ label, value, p }) {
  const op = clamp(p, 0, 1);
  return (
    <div style={{ opacity: op, transform: `translateY(${(1 - op) * 10}px)`,
      borderTop: `1px solid ${COL.line}`, padding: '16px 0' }}>
      <div style={{ fontFamily: MONO, fontSize: 13, letterSpacing: '0.18em',
        textTransform: 'uppercase', color: COL.dim, marginBottom: 8 }}>{label}</div>
      <div style={{ fontFamily: DISP, fontSize: 40, fontWeight: 500, color: COL.vanilla,
        letterSpacing: '-0.02em', fontVariantNumeric: 'tabular-nums' }}>{value}</div>
    </div>
  );
}

function SceneBacktest() {
  const { localTime } = useSprite();
  const kP = Easing.easeOutCubic(stagger(localTime, 0.1, 0.6));
  const drawP = clamp((localTime - 0.8) / 3.2, 0, 1);
  const netRet = useCount(148.6, stagger(localTime, 2.4, 1.4));
  const wr = useCount(54.3, stagger(localTime, 2.6, 1.4));
  const pf = useCount(1.92, stagger(localTime, 2.8, 1.4));
  const trades = useCount(1284, stagger(localTime, 3.0, 1.4));
  const dd = useCount(11.4, stagger(localTime, 3.2, 1.4));
  const sharpe = useCount(2.14, stagger(localTime, 3.4, 1.4));
  return (
    <Scene>
      <div style={{ position: 'absolute', inset: 0, padding: '120px 150px',
        display: 'flex', flexDirection: 'column', gap: 36 }}>
        <Kicker style={{ opacity: kP, transform: `translateY(${(1 - kP) * 10}px)` }}>
          Backtested on real market data
        </Kicker>
        <div style={{ flex: 1, display: 'flex', gap: 36, minHeight: 0 }}>
          <Panel style={{ flex: '1 1 64%', padding: '30px 34px', display: 'flex', flexDirection: 'column' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 14 }}>
              <div style={{ fontFamily: MONO, fontSize: 14, letterSpacing: '0.16em',
                textTransform: 'uppercase', color: COL.dim }}>Equity curve · 5 yr · ES futures</div>
              <div style={{ fontFamily: MONO, fontSize: 14, color: COL.dimmer }}>2021 → 2026</div>
            </div>
            <div style={{ flex: 1, minHeight: 0 }}>
              <EquityCurve p={drawP} w={820} h={420} seed={11} />
            </div>
          </Panel>
          <div style={{ flex: '1 1 36%', display: 'grid', gridTemplateColumns: '1fr 1fr',
            columnGap: 40, alignContent: 'center' }}>
            <Stat label="Net return" value={`+${netRet.toFixed(1)}%`} p={stagger(localTime, 2.4, 0.5)} />
            <Stat label="Win rate" value={`${wr.toFixed(1)}%`} p={stagger(localTime, 2.6, 0.5)} />
            <Stat label="Profit factor" value={pf.toFixed(2)} p={stagger(localTime, 2.8, 0.5)} />
            <Stat label="Trades" value={Math.round(trades).toLocaleString()} p={stagger(localTime, 3.0, 0.5)} />
            <Stat label="Max drawdown" value={`−${dd.toFixed(1)}%`} p={stagger(localTime, 3.2, 0.5)} />
            <Stat label="Sharpe" value={sharpe.toFixed(2)} p={stagger(localTime, 3.4, 0.5)} />
          </div>
        </div>
      </div>
    </Scene>
  );
}

// ════════════════════════════════════════════════════════════════════════
// SCENE 4 — The research montage
// ════════════════════════════════════════════════════════════════════════
function Heatmap({ p }) {
  const cols = 9, rows = 6;
  const cells = [];
  const r = mulberry(42);
  for (let y = 0; y < rows; y++) for (let x = 0; x < cols; x++) {
    cells.push({ x, y, v: r() });
  }
  const best = cells.reduce((a, b) => (b.v > a.v ? b : a), cells[0]);
  return (
    <svg viewBox="0 0 290 190" style={{ width: '100%', height: '100%' }}>
      {cells.map((c, i) => {
        const cp = stagger(p, (c.x + c.y) * 0.02, 0.4);
        const isBest = c === best;
        return <rect key={i} x={c.x * 32 + 2} y={c.y * 31 + 2} width={29} height={28} rx={3}
          fill={COL.vanilla} opacity={(0.06 + c.v * 0.5) * cp}
          stroke={isBest ? COL.vanilla : 'none'} strokeWidth={isBest ? 2 : 0}
          style={{ strokeOpacity: cp }} />;
      })}
    </svg>
  );
}
function Bars({ p }) {
  const data = [['ASIA', 0.32], ['LON', 0.55], ['NY AM', 0.96], ['NY PM', 0.61]];
  return (
    <svg viewBox="0 0 290 190" style={{ width: '100%', height: '100%' }}>
      {data.map(([lab, v], i) => {
        const bp = stagger(p, i * 0.1, 0.5);
        const h = v * 150 * bp;
        const x = 20 + i * 68;
        return (
          <g key={lab}>
            <rect x={x} y={165 - h} width={44} height={h} rx={3}
              fill={COL.vanilla} opacity={i === 2 ? 0.92 : 0.3} />
            <text x={x + 22} y={183} textAnchor="middle" fontFamily={MONO} fontSize={12}
              fill={COL.dim}>{lab}</text>
          </g>
        );
      })}
    </svg>
  );
}
function Regimes({ p }) {
  const segs = [[0, 3, 0.85], [3, 1.4, 0.22], [4.4, 2.2, 0.85], [6.6, 1.1, 0.22], [7.7, 1.3, 0.55]];
  const labels = [['TREND', 0.85], ['CHOP', 0.22], ['VOL', 0.55]];
  return (
    <svg viewBox="0 0 290 190" style={{ width: '100%', height: '100%' }}>
      {segs.map((s, i) => {
        const sp = stagger(p, i * 0.08, 0.4);
        return <rect key={i} x={20 + s[0] * 28} y={56} width={s[1] * 28 - 4} height={46} rx={4}
          fill={COL.vanilla} opacity={s[2] * sp} />;
      })}
      {labels.map(([l, o], i) => (
        <g key={l} opacity={stagger(p, 0.5 + i * 0.1, 0.4)}>
          <rect x={20 + i * 92} y={130} width={12} height={12} rx={2} fill={COL.vanilla} opacity={o} />
          <text x={38 + i * 92} y={140} fontFamily={MONO} fontSize={12} fill={COL.dim}>{l}</text>
        </g>
      ))}
    </svg>
  );
}
function Scatter({ p }) {
  const r = mulberry(77);
  const pts = Array.from({ length: 46 }, () => ({ x: r(), y: r() * 0.85 + r() * 0.1 }));
  return (
    <svg viewBox="0 0 290 190" style={{ width: '100%', height: '100%' }}>
      <line x1={28} y1={165} x2={278} y2={165} stroke={COL.line} strokeWidth={1} />
      <line x1={28} y1={20} x2={28} y2={165} stroke={COL.line} strokeWidth={1} />
      {pts.map((pt, i) => {
        const dp = stagger(p, (pt.x) * 0.5, 0.5);
        return <circle key={i} cx={34 + pt.x * 240} cy={160 - pt.y * 135} r={3.4}
          fill={COL.vanilla} opacity={(0.3 + pt.y * 0.5) * dp} />;
      })}
      <text x={150} y={185} textAnchor="middle" fontFamily={MONO} fontSize={11} fill={COL.dimmer}>MAE →</text>
    </svg>
  );
}
function Robustness({ p }) {
  const lines = React.useMemo(() => Array.from({ length: 9 }, (_, i) => genEquity(60, 100 + i, 0.012, 0.07)), []);
  return (
    <svg viewBox="0 0 290 190" style={{ width: '100%', height: '100%' }}>
      {lines.map((pts, i) => {
        const path = pointsToPath(pts, 290, 180, 8);
        const dp = stagger(p, i * 0.05, 0.6);
        const isMain = i === 4;
        return <path key={i} d={path} fill="none" stroke={COL.vanilla}
          strokeWidth={isMain ? 2.4 : 1} opacity={(isMain ? 0.9 : 0.22) * dp}
          strokeLinecap="round" strokeDasharray={600} strokeDashoffset={600 * (1 - dp)} />;
      })}
    </svg>
  );
}
function PropFit({ p }) {
  const items = ['Daily-loss limit', 'Max drawdown', 'Profit target', 'Consistency rule'];
  const stampP = Easing.easeOutBack(stagger(p, 0.7, 0.5));
  return (
    <div style={{ width: '100%', height: '100%', display: 'flex', flexDirection: 'column',
      justifyContent: 'center', gap: 13, position: 'relative', padding: '0 6px' }}>
      {items.map((it, i) => {
        const ip = stagger(p, i * 0.12, 0.4);
        return (
          <div key={it} style={{ display: 'flex', alignItems: 'center', gap: 12,
            opacity: ip, transform: `translateX(${(1 - ip) * 10}px)` }}>
            <div style={{ width: 20, height: 20, borderRadius: 5, border: `1px solid ${COL.line}`,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontSize: 12, color: COL.vanilla }}>✓</div>
            <div style={{ fontFamily: MONO, fontSize: 15, color: COL.dim, whiteSpace: 'nowrap' }}>{it}</div>
          </div>
        );
      })}
      <div style={{ position: 'absolute', right: 4, bottom: 0, opacity: clamp(stampP, 0, 1),
        transform: `scale(${0.6 + stampP * 0.4}) rotate(-7deg)`,
        fontFamily: DISP, fontSize: 26, fontWeight: 600, letterSpacing: '0.1em',
        color: COL.vanilla, border: `2px solid ${COL.vanilla}`, padding: '4px 12px', borderRadius: 6 }}>
        PASS
      </div>
    </div>
  );
}

const TILES = [
  { k: 'Parameter sweep', sub: '4,320 combinations', Viz: Heatmap },
  { k: 'Session edge', sub: 'when it actually pays', Viz: Bars },
  { k: 'Market regimes', sub: 'trend · chop · volatility', Viz: Regimes },
  { k: 'MAE / MFE', sub: 'pain vs. reward per trade', Viz: Scatter },
  { k: 'Robustness', sub: '2,000 Monte-Carlo paths', Viz: Robustness },
  { k: 'Prop-firm fit', sub: 'rules checked automatically', Viz: PropFit },
];

function SceneMontage() {
  const { localTime } = useSprite();
  const kP = Easing.easeOutCubic(stagger(localTime, 0.1, 0.6));
  return (
    <Scene>
      <div style={{ position: 'absolute', inset: 0, padding: '96px 130px',
        display: 'flex', flexDirection: 'column', gap: 30 }}>
        <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between',
          opacity: kP, transform: `translateY(${(1 - kP) * 10}px)` }}>
          <Kicker>The research you'd never run by hand</Kicker>
          <div style={{ fontFamily: MONO, fontSize: 14, color: COL.dimmer, letterSpacing: '0.14em', whiteSpace: 'nowrap' }}>
            6 ANALYSES · RUN IN PARALLEL
          </div>
        </div>
        <div style={{ flex: 1, display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)',
          gridTemplateRows: '1fr 1fr', gap: 26, minHeight: 0 }}>
          {TILES.map((tile, i) => {
            const start = 0.4 + i * 0.5;
            const enter = Easing.easeOutCubic(stagger(localTime, start, 0.5));
            const vizP = stagger(localTime, start + 0.2, 1.3);
            const Viz = tile.Viz;
            return (
              <Panel key={tile.k} style={{ padding: '20px 22px', display: 'flex', flexDirection: 'column',
                opacity: enter, transform: `translateY(${(1 - enter) * 22}px) scale(${lerp(0.97, 1, enter)})` }}>
                <div style={{ marginBottom: 10 }}>
                  <div style={{ fontFamily: DISP, fontSize: 23, fontWeight: 500, color: COL.vanilla,
                    letterSpacing: '-0.01em' }}>{tile.k}</div>
                  <div style={{ fontFamily: MONO, fontSize: 13, color: COL.dimmer,
                    letterSpacing: '0.04em', marginTop: 3 }}>{tile.sub}</div>
                </div>
                <div style={{ flex: 1, minHeight: 0 }}><Viz p={vizP} /></div>
              </Panel>
            );
          })}
        </div>
      </div>
    </Scene>
  );
}

// ════════════════════════════════════════════════════════════════════════
// SCENE 5 — The verdict
// ════════════════════════════════════════════════════════════════════════
const VERDICTS = [
  { k: 'What works', t: 'The edge concentrates in the first 90 minutes of the NY session.' },
  { k: 'What fails', t: 'It bleeds out in low-volatility, range-bound regimes.' },
  { k: 'What to do next', t: 'Tighten the stop to 1.4R and skip the Asia session entirely.' },
];
function SceneVerdict() {
  const { localTime } = useSprite();
  const kP = Easing.easeOutCubic(stagger(localTime, 0.1, 0.6));
  return (
    <Scene>
      <div style={{ position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column',
        justifyContent: 'center', padding: '0 150px', gap: 30 }}>
        <Kicker style={{ opacity: kP, transform: `translateY(${(1 - kP) * 10}px)` }}>
          Then it tells you what it found
        </Kicker>
        <div style={{ display: 'flex', flexDirection: 'column' }}>
          {VERDICTS.map((v, i) => {
            const start = 0.7 + i * 0.85;
            const ep = Easing.easeOutCubic(stagger(localTime, start, 0.6));
            return (
              <div key={v.k} style={{ display: 'flex', alignItems: 'flex-start', gap: 46,
                padding: '34px 0', borderTop: i === 0 ? 'none' : `1px solid ${COL.line}`,
                opacity: ep, transform: `translateY(${(1 - ep) * 16}px)` }}>
                <div style={{ width: 280, flexShrink: 0, fontFamily: MONO, fontSize: 16,
                  letterSpacing: '0.2em', textTransform: 'uppercase', color: COL.dim, paddingTop: 12 }}>
                  {v.k}
                </div>
                <div style={{ fontFamily: DISP, fontSize: 50, lineHeight: 1.22, color: COL.vanilla,
                  fontWeight: 400, letterSpacing: '-0.018em', textWrap: 'pretty' }}>{v.t}</div>
              </div>
            );
          })}
        </div>
      </div>
    </Scene>
  );
}

// ════════════════════════════════════════════════════════════════════════
// SCENE 6 — Logo + CTA
// ════════════════════════════════════════════════════════════════════════
function SceneLogo() {
  const { localTime } = useSprite();
  const markP = Easing.easeOutCubic(stagger(localTime, 0.3, 0.9));
  const lineP = stagger(localTime, 1.1, 0.8);
  const tagP = Easing.easeOutCubic(stagger(localTime, 1.5, 0.8));
  const ctaP = Easing.easeOutCubic(stagger(localTime, 2.7, 0.9));
  return (
    <Scene zoomFrom={1.0} zoomTo={1.05}>
      <div style={{ position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column',
        alignItems: 'center', justifyContent: 'center', gap: 30 }}>
        <div style={{ opacity: markP, transform: `translateY(${(1 - markP) * 14}px)`,
          fontFamily: DISP, fontSize: 132, fontWeight: 600, color: COL.vanilla,
          letterSpacing: '-0.04em', position: 'relative' }}>
          TapeScript
          <span style={{ fontSize: 34, verticalAlign: 'top', marginLeft: 6, fontWeight: 400,
            color: COL.dim }}>™</span>
        </div>
        <div style={{ width: lerp(0, 560, lineP), height: 1, background: COL.line }} />
        <div style={{ opacity: tagP, transform: `translateY(${(1 - tagP) * 10}px)`,
          fontFamily: DISP, fontSize: 34, fontWeight: 400, color: COL.dim,
          letterSpacing: '-0.01em', textAlign: 'center' }}>
          Build smarter strategies. Test deeper. Find real edge.
        </div>
        <div style={{ opacity: ctaP, transform: `translateY(${(1 - ctaP) * 12}px)`, marginTop: 34,
          display: 'flex', alignItems: 'center', gap: 16, padding: '20px 38px', borderRadius: 999,
          border: `1px solid rgba(244,238,223,0.4)`, background: 'rgba(244,238,223,0.04)' }}>
          <span style={{ fontFamily: DISP, fontSize: 27, fontWeight: 500, color: COL.vanilla,
            letterSpacing: '-0.01em' }}>Build smarter strategies with TapeScript</span>
          <span style={{ fontFamily: MONO, fontSize: 24, color: COL.vanilla }}>→</span>
        </div>
      </div>
    </Scene>
  );
}

Object.assign(window, {
  SceneIdea, SceneCompile, SceneBacktest, SceneMontage, SceneVerdict, SceneLogo,
});
