// LUNARO demo walkthrough — wizard-style narrated product tour
// Scenes (times in seconds):
//   0  – 5    Intro / logo
//   5  – 11   Today screen (hero)
//   11 – 17   Cycle-synced plan
//   17 – 23   Cycle screen (ring)
//   23 – 29   Workout detail (library)
//   29 – 35   Progress & PRs
//   35 – 41   Integrations
//   41 – 48   Outro / founding rate

const BLUE = '#3DA5FF';
const BLUE_DEEP = '#1A7AE0';
const BG = '#050505';
const CARD = '#141414';
const BORDER = '#262626';
const MUTED = '#A1A1A1';

// ── Device frame ────────────────────────────────────────────────────────────
function Phone({ children, x = 0, y = 0, scale = 1 }) {
  return (
    <div style={{
      position: 'absolute',
      left: x, top: y,
      transform: `scale(${scale})`,
      transformOrigin: 'top left',
      width: 360, height: 760,
      borderRadius: 44,
      background: '#0A0A0A',
      border: '10px solid #1A1A1A',
      boxShadow: '0 40px 100px rgba(0,0,0,0.7), 0 0 0 1px rgba(61,165,255,0.08)',
      overflow: 'hidden',
      fontFamily: 'Inter, sans-serif',
    }}>
      {/* notch */}
      <div style={{
        position: 'absolute', top: 8, left: '50%', transform: 'translateX(-50%)',
        width: 100, height: 26, borderRadius: 20, background: '#000', zIndex: 20,
      }}/>
      {/* status bar */}
      <div style={{
        position: 'absolute', top: 12, left: 22, right: 22, display: 'flex',
        justifyContent: 'space-between', fontSize: 12, color: '#fff', fontWeight: 600, zIndex: 10,
      }}>
        <span>9:41</span>
        <span style={{ display: 'flex', gap: 5, alignItems: 'center' }}>
          <span style={{ fontSize: 10 }}>●●●●</span>
          <span>􀋨</span>
        </span>
      </div>
      <div style={{ position: 'absolute', inset: '44px 0 0 0' }}>
        {children}
      </div>
    </div>
  );
}

// ── Callout bubble ──────────────────────────────────────────────────────────
function Callout({ x, y, width = 320, children, direction = 'right', progress = 1 }) {
  const dx = direction === 'right' ? -20 : 20;
  return (
    <div style={{
      position: 'absolute',
      left: x, top: y,
      width,
      opacity: progress,
      transform: `translateX(${(1 - progress) * dx}px)`,
      pointerEvents: 'none',
    }}>
      {children}
    </div>
  );
}

function CalloutCard({ label, title, body, color = BLUE }) {
  return (
    <div style={{
      background: 'rgba(12,14,20,0.92)',
      backdropFilter: 'blur(12px)',
      border: `1px solid ${color}55`,
      borderRadius: 20,
      padding: '18px 20px',
      boxShadow: `0 20px 40px rgba(0,0,0,0.5), 0 0 0 1px ${color}22`,
    }}>
      <div style={{
        fontSize: 10, fontWeight: 700, letterSpacing: '0.26em',
        textTransform: 'uppercase', color, marginBottom: 10,
      }}>{label}</div>
      <div style={{
        fontFamily: 'Urbanist, sans-serif',
        fontWeight: 700, fontSize: 22, lineHeight: 1.15,
        letterSpacing: '-0.01em', color: '#fff', marginBottom: 8,
      }}>{title}</div>
      <div style={{ fontSize: 13, lineHeight: 1.5, color: MUTED }}>{body}</div>
    </div>
  );
}

// ── Pointer line from callout to target ─────────────────────────────────────
function Pointer({ x1, y1, x2, y2, progress = 1, color = BLUE }) {
  const len = Math.hypot(x2 - x1, y2 - y1);
  const visible = len * progress;
  return (
    <svg style={{ position: 'absolute', inset: 0, width: 1280, height: 720, pointerEvents: 'none' }}>
      <defs>
        <marker id="arrow" markerWidth="8" markerHeight="8" refX="4" refY="4" orient="auto">
          <circle cx="4" cy="4" r="3" fill={color}/>
        </marker>
      </defs>
      <line x1={x1} y1={y1} x2={x2} y2={y2}
        stroke={color} strokeWidth="1.5" strokeDasharray={`${visible} ${len}`}
        strokeLinecap="round" markerEnd="url(#arrow)" opacity="0.85"/>
    </svg>
  );
}

// ── Ambient particles backdrop ──────────────────────────────────────────────
function Particles() {
  const time = useTime();
  const dots = React.useMemo(() => Array.from({ length: 70 }, (_, i) => ({
    x: (i * 73) % 1280,
    y: (i * 47) % 720,
    s: 0.5 + ((i * 13) % 10) / 10 * 1.8,
    o: 0.1 + ((i * 17) % 10) / 10 * 0.5,
    ph: (i * 0.7) % (Math.PI * 2),
  })), []);
  return (
    <div style={{ position: 'absolute', inset: 0, pointerEvents: 'none' }}>
      {dots.map((d, i) => (
        <div key={i} style={{
          position: 'absolute',
          left: d.x, top: d.y + Math.sin(time * 0.5 + d.ph) * 8,
          width: d.s, height: d.s, borderRadius: '50%',
          background: '#fff',
          opacity: d.o * (0.6 + 0.4 * Math.sin(time + d.ph)),
        }}/>
      ))}
    </div>
  );
}

// ── Chrome: logo + timecode ─────────────────────────────────────────────────
function Chrome() {
  const { time, duration } = useTimeline();
  const tc = (s) => {
    const m = Math.floor(s / 60);
    const ss = Math.floor(s % 60);
    return `${String(m).padStart(2,'0')}:${String(ss).padStart(2,'0')}`;
  };
  return (
    <>
      <div style={{
        position: 'absolute', top: 28, left: 36,
        fontFamily: 'Urbanist, sans-serif', fontWeight: 800,
        letterSpacing: '0.24em', fontSize: 16, color: BLUE,
      }}>LUNARO</div>
      <div style={{
        position: 'absolute', top: 28, right: 36,
        display: 'flex', alignItems: 'center', gap: 12,
        fontSize: 11, letterSpacing: '0.24em', textTransform: 'uppercase',
        color: MUTED, fontFamily: 'Inter, sans-serif',
      }}>
        <span style={{
          width: 7, height: 7, borderRadius: '50%', background: '#EF4444',
          opacity: 0.5 + 0.5 * Math.sin(time * 4),
        }}/>
        REC · Product Tour
        <span style={{
          fontFamily: 'ui-monospace, monospace', color: '#fff',
          marginLeft: 8, fontWeight: 600,
        }}>{tc(time)} / {tc(duration)}</span>
      </div>
    </>
  );
}

// ── Caption / lower-third ───────────────────────────────────────────────────
function Caption({ eyebrow, title, sub, progress = 1 }) {
  return (
    <div style={{
      position: 'absolute',
      left: 60, bottom: 56,
      maxWidth: 580,
      opacity: progress,
      transform: `translateY(${(1 - progress) * 16}px)`,
    }}>
      <div style={{
        fontSize: 11, fontWeight: 700, letterSpacing: '0.28em',
        textTransform: 'uppercase', color: BLUE, marginBottom: 14,
      }}>{eyebrow}</div>
      <div style={{
        fontFamily: 'Urbanist, sans-serif',
        fontWeight: 800, fontSize: 56, lineHeight: 0.98,
        letterSpacing: '-0.03em', color: '#fff', marginBottom: 14,
      }}>{title}</div>
      {sub && <div style={{ fontSize: 17, lineHeight: 1.5, color: '#D4D4D4', maxWidth: 520 }}>{sub}</div>}
    </div>
  );
}

// ── Progress dots ───────────────────────────────────────────────────────────
const SCENE_COUNT = 8;
function SceneDots({ current }) {
  return (
    <div style={{
      position: 'absolute', bottom: 28, right: 40,
      display: 'flex', gap: 6,
    }}>
      {Array.from({ length: SCENE_COUNT }).map((_, i) => (
        <span key={i} style={{
          width: i === current ? 22 : 6, height: 6, borderRadius: 3,
          background: i <= current ? BLUE : '#262626',
          transition: 'width 400ms ease, background 400ms ease',
        }}/>
      ))}
    </div>
  );
}

// ═════════════════════════════════════════════════════════════════════════════
// SCREENS
// ═════════════════════════════════════════════════════════════════════════════

function ScreenToday() {
  return (
    <div style={{ padding: '16px 20px', color: '#fff', height: '100%', overflow: 'hidden' }}>
      <div style={{ fontSize: 12, color: MUTED, letterSpacing: '0.2em', textTransform: 'uppercase' }}>Friday · Apr 24</div>
      <div style={{ fontFamily: 'Inter', fontWeight: 700, fontSize: 26, marginTop: 6, letterSpacing: '-0.02em' }}>
        Good morning, Sydney
      </div>
      {/* phase banner */}
      <div style={{
        marginTop: 18,
        background: 'linear-gradient(135deg, #0D1522 0%, #132640 100%)',
        border: `1px solid ${BLUE}33`, borderRadius: 20, padding: 14,
        display: 'flex', alignItems: 'center', gap: 12,
      }}>
        <div style={{
          width: 42, height: 42, borderRadius: 14, background: `${BLUE}22`,
          color: BLUE, display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontSize: 18, fontWeight: 800,
        }}>✦</div>
        <div>
          <div style={{ fontSize: 12, color: BLUE, fontWeight: 600 }}>Follicular · Day 8</div>
          <div style={{ fontSize: 14, marginTop: 2 }}>Push for strength PRs today</div>
        </div>
      </div>
      {/* workout card */}
      <div style={{
        marginTop: 16, background: CARD, border: `1px solid ${BORDER}`,
        borderRadius: 20, padding: 16,
      }}>
        <div style={{ fontSize: 11, color: MUTED, letterSpacing: '0.2em', textTransform: 'uppercase' }}>Today's Session</div>
        <div style={{ fontSize: 18, fontWeight: 600, marginTop: 6 }}>Lower Body Power</div>
        <div style={{ display: 'flex', gap: 6, marginTop: 10, flexWrap: 'wrap' }}>
          {['Quads', 'Glutes', 'Hamstrings'].map(t => (
            <span key={t} style={{
              border: `1px solid ${BLUE}66`, color: BLUE, fontSize: 10, fontWeight: 500,
              padding: '3px 10px', borderRadius: 999,
            }}>{t}</span>
          ))}
        </div>
        <div style={{
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          marginTop: 14, paddingTop: 12, borderTop: `1px solid ${BORDER}`,
        }}>
          <span style={{ fontSize: 12, color: MUTED }}>50 min · Intermediate</span>
          <span style={{
            background: BLUE, color: '#041225', fontWeight: 700, fontSize: 12,
            padding: '8px 16px', borderRadius: 10,
          }}>Start</span>
        </div>
      </div>
      {/* stats tri */}
      <div style={{ display: 'flex', gap: 8, marginTop: 14 }}>
        {[
          ['Sleep', '7h 23m'],
          ['Stress', 'Low'],
          ['Water', '6 / 8'],
        ].map(([k, v]) => (
          <div key={k} style={{
            flex: 1, background: '#1A1A1A', borderRadius: 12, padding: 10,
          }}>
            <div style={{ fontSize: 10, color: MUTED, letterSpacing: '0.16em', textTransform: 'uppercase' }}>{k}</div>
            <div style={{ fontSize: 14, fontWeight: 600, marginTop: 6 }}>{v}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

function ScreenPlan() {
  return (
    <div style={{ padding: '16px 20px', color: '#fff', height: '100%' }}>
      <div style={{ fontSize: 20, fontWeight: 600 }}>This Week</div>
      <div style={{ fontSize: 12, color: MUTED, marginTop: 2 }}>Adapted to follicular phase</div>
      <div style={{ marginTop: 16, display: 'flex', flexDirection: 'column', gap: 8 }}>
        {[
          ['MON', 'Upper Power', 'done', '#3DA5FF'],
          ['TUE', 'Zone 2 Run · 40m', 'done', '#3DA5FF'],
          ['WED', 'Lower Power', 'today', BLUE],
          ['THU', 'Mobility', 'upcoming', '#262626'],
          ['FRI', 'Full Body · Heavy', 'upcoming', '#262626'],
          ['SAT', 'Long Run · 60m', 'upcoming', '#262626'],
          ['SUN', 'Rest', 'upcoming', '#262626'],
        ].map(([d, w, s, c], i) => (
          <div key={i} style={{
            background: s === 'today' ? `${BLUE}12` : CARD,
            border: `1px solid ${s === 'today' ? BLUE + '66' : BORDER}`,
            borderRadius: 14, padding: '10px 14px',
            display: 'flex', alignItems: 'center', gap: 14,
          }}>
            <div style={{
              width: 32, fontSize: 11, color: s === 'upcoming' ? MUTED : '#fff',
              fontWeight: 600, letterSpacing: '0.1em',
            }}>{d}</div>
            <div style={{ flex: 1, fontSize: 14, color: s === 'upcoming' ? MUTED : '#fff' }}>{w}</div>
            <div style={{
              width: 8, height: 8, borderRadius: '50%', background: c,
              opacity: s === 'done' ? 0.5 : 1,
            }}/>
          </div>
        ))}
      </div>
    </div>
  );
}

function ScreenCycle() {
  const time = useTime();
  const phases = [
    { name: 'Menstrual',  color: '#F43F5E', days: 5 },
    { name: 'Follicular', color: BLUE,      days: 6 },
    { name: 'Ovulation',  color: '#FBBF24', days: 5 },
    { name: 'Luteal',     color: '#A78BFA', days: 12 },
  ];
  const total = 28;
  const R = 108;
  const circ = 2 * Math.PI * R;
  let offset = 0;
  return (
    <div style={{ padding: '20px 20px 0', color: '#fff', height: '100%' }}>
      <div style={{ fontSize: 20, fontWeight: 600 }}>Your Cycle</div>
      <div style={{ fontSize: 12, color: MUTED, marginTop: 2 }}>28-day tracking</div>
      <div style={{ position: 'relative', margin: '20px auto 0', width: 260, height: 260 }}>
        <svg width="260" height="260" style={{ transform: 'rotate(-90deg)' }}>
          <circle cx="130" cy="130" r={R} fill="none" stroke="#1A1A1A" strokeWidth="14"/>
          {phases.map((p, i) => {
            const frac = p.days / total;
            const dash = `${circ * frac} ${circ}`;
            const dashOff = -offset * circ;
            offset += frac;
            return (
              <circle key={i} cx="130" cy="130" r={R} fill="none"
                stroke={p.color} strokeWidth="14" strokeLinecap="round"
                strokeDasharray={dash} strokeDashoffset={dashOff}
                opacity={Math.min(1, time * 0.4)}/>
            );
          })}
        </svg>
        {/* current day dot */}
        <div style={{
          position: 'absolute', top: '50%', left: '50%',
          transform: `translate(-50%, -50%) rotate(${(8/28) * 360 - 90}deg) translateX(${R}px)`,
        }}>
          <div style={{
            width: 18, height: 18, borderRadius: '50%', background: BLUE,
            boxShadow: `0 0 0 ${4 + 4 * Math.sin(time * 3.5)}px ${BLUE}40`,
          }}/>
        </div>
        <div style={{
          position: 'absolute', inset: 0, display: 'flex',
          flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
        }}>
          <div style={{ fontSize: 12, color: MUTED, letterSpacing: '0.22em', textTransform: 'uppercase' }}>Day</div>
          <div style={{ fontFamily: 'Urbanist', fontWeight: 800, fontSize: 68, lineHeight: 1, color: '#fff' }}>8</div>
          <div style={{ fontSize: 12, color: BLUE, fontWeight: 600, marginTop: 6 }}>Follicular</div>
        </div>
      </div>
      <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 20, padding: '0 6px' }}>
        {phases.map(p => (
          <div key={p.name} style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4 }}>
            <span style={{ width: 8, height: 8, borderRadius: 999, background: p.color }}/>
            <span style={{ fontSize: 9, color: MUTED }}>{p.name}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

function ScreenWorkout() {
  const time = useTime();
  const secs = Math.floor(time * 2) % 180;
  const mm = String(Math.floor(secs / 60)).padStart(2, '0');
  const ss = String(secs % 60).padStart(2, '0');
  return (
    <div style={{ padding: '16px 20px', color: '#fff', height: '100%' }}>
      <div style={{ fontSize: 11, color: MUTED, letterSpacing: '0.22em', textTransform: 'uppercase' }}>Exercise 3 of 6</div>
      <div style={{ fontSize: 22, fontWeight: 700, marginTop: 6, letterSpacing: '-0.01em' }}>Back Squat</div>
      <div style={{
        marginTop: 14, borderRadius: 20, overflow: 'hidden',
        height: 180, background: 'linear-gradient(135deg, #0D1828 0%, #1A2B44 100%)',
        border: `1px solid ${BORDER}`, position: 'relative',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>
        <div style={{
          fontFamily: 'Urbanist', fontWeight: 800, fontSize: 14,
          color: BLUE, letterSpacing: '0.3em', position: 'absolute', top: 12, left: 14,
        }}>DEMO · 0:{String(Math.floor(time * 4) % 60).padStart(2, '0')}</div>
        <svg width="90" height="90" viewBox="0 0 24 24" fill={BLUE} opacity="0.4">
          <path d="M8 5.5v13l11-6.5-11-6.5z"/>
        </svg>
      </div>
      <div style={{ marginTop: 14 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 8, fontSize: 12, color: MUTED }}>
          <span>Sets</span><span>Weight</span><span>Reps</span>
        </div>
        {[
          [1, '95 lb', '8', true],
          [2, '115 lb', '6', true],
          [3, '135 lb', '5', false],
          [4, '135 lb', '5', false],
        ].map(([n, w, r, done]) => (
          <div key={n} style={{
            display: 'flex', justifyContent: 'space-between', alignItems: 'center',
            padding: '10px 12px', marginTop: 6, borderRadius: 10,
            background: done ? '#1A1A1A' : `${BLUE}18`,
            border: done ? 'none' : `1px solid ${BLUE}55`,
          }}>
            <span style={{ fontSize: 13, fontWeight: 600 }}>Set {n}</span>
            <span style={{ fontSize: 13, color: done ? MUTED : '#fff', fontWeight: done ? 500 : 700 }}>{w}</span>
            <span style={{ fontSize: 13, color: done ? MUTED : '#fff', fontWeight: done ? 500 : 700 }}>{r}</span>
            <span style={{
              width: 20, height: 20, borderRadius: '50%',
              background: done ? BLUE : 'transparent',
              border: done ? 'none' : `1.5px solid ${BLUE}`,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontSize: 10, color: '#041225', fontWeight: 800,
            }}>{done ? '✓' : ''}</span>
          </div>
        ))}
      </div>
      <div style={{
        marginTop: 14, padding: 14, background: CARD,
        border: `1px solid ${BORDER}`, borderRadius: 14,
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      }}>
        <span style={{ fontSize: 12, color: MUTED }}>Rest</span>
        <span style={{ fontFamily: 'ui-monospace, monospace', fontSize: 22, fontWeight: 700, color: BLUE }}>{mm}:{ss}</span>
      </div>
    </div>
  );
}

function ScreenProgress() {
  const time = useTime();
  const prog = Math.min(1, Math.max(0, (time - 29) / 4));
  const bars = [
    { lbl: 'Squat', val: 135, pr: '+15 lb', h: 70 },
    { lbl: 'Deadlift', val: 185, pr: '+20 lb', h: 92 },
    { lbl: 'Bench', val: 85,  pr: '+10 lb', h: 48 },
    { lbl: 'OHP',    val: 65,  pr: '+5 lb', h: 38 },
    { lbl: 'Row',    val: 95,  pr: '+8 lb', h: 55 },
  ];
  return (
    <div style={{ padding: '16px 20px', color: '#fff', height: '100%' }}>
      <div style={{ fontSize: 20, fontWeight: 600 }}>Progress</div>
      <div style={{ fontSize: 12, color: MUTED, marginTop: 2 }}>Last 30 days</div>
      <div style={{
        marginTop: 18, background: CARD, border: `1px solid ${BORDER}`,
        borderRadius: 18, padding: 16,
      }}>
        <div style={{ fontSize: 11, color: MUTED, letterSpacing: '0.2em', textTransform: 'uppercase' }}>Strength PRs</div>
        <div style={{
          display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between',
          gap: 8, marginTop: 16, height: 110,
        }}>
          {bars.map((b, i) => (
            <div key={b.lbl} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6 }}>
              <div style={{
                width: '100%',
                height: b.h * prog,
                background: `linear-gradient(180deg, ${BLUE} 0%, ${BLUE_DEEP} 100%)`,
                borderRadius: '6px 6px 0 0',
                opacity: 0.3 + 0.7 * Math.min(1, prog * (0.5 + i * 0.15)),
              }}/>
              <span style={{ fontSize: 10, color: MUTED, fontWeight: 500 }}>{b.lbl}</span>
            </div>
          ))}
        </div>
      </div>
      <div style={{ marginTop: 14, display: 'flex', flexDirection: 'column', gap: 8 }}>
        {[
          ['135 lb Squat PR', 'New personal best', BLUE],
          ['5k under 28min', 'Fastest this cycle', '#A78BFA'],
          ['3 sessions this week', 'Plan on track', '#FBBF24'],
        ].map(([t, s, c], i) => (
          <div key={i} style={{
            display: 'flex', alignItems: 'center', gap: 12,
            background: CARD, border: `1px solid ${BORDER}`, borderLeft: `3px solid ${c}`,
            borderRadius: 14, padding: 12,
          }}>
            <div style={{
              width: 36, height: 36, borderRadius: 10, background: `${c}22`,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontSize: 16, color: c, fontWeight: 800,
            }}>★</div>
            <div>
              <div style={{ fontSize: 14, fontWeight: 600 }}>{t}</div>
              <div style={{ fontSize: 11, color: MUTED, marginTop: 2 }}>{s}</div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

function ScreenIntegrations() {
  return (
    <div style={{ padding: '16px 20px', color: '#fff', height: '100%' }}>
      <div style={{ fontSize: 20, fontWeight: 600 }}>Connected</div>
      <div style={{ fontSize: 12, color: MUTED, marginTop: 2 }}>Your data, one source of truth</div>
      <div style={{ marginTop: 18, display: 'flex', flexDirection: 'column', gap: 8 }}>
        {[
          ['Apple Health', 'Sleep · HR · Steps', true, '#FF3B30'],
          ['Oura Ring',    'HRV · Temp · Readiness', true, '#8F93A8'],
          ['Garmin',       'GPS · Pace · Zones', true, '#0070C0'],
          ['Whoop',        'Recovery · Strain', false, '#FFFFFF'],
          ['MyFitnessPal', 'Nutrition logging', false, '#0072CE'],
        ].map(([n, d, on, c], i) => (
          <div key={i} style={{
            background: CARD, border: `1px solid ${BORDER}`, borderRadius: 14,
            padding: 12, display: 'flex', alignItems: 'center', gap: 12,
          }}>
            <div style={{
              width: 40, height: 40, borderRadius: 12, background: '#1A1A1A',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              color: c, fontWeight: 800, fontSize: 12,
            }}>{n.slice(0, 2).toUpperCase()}</div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 14, fontWeight: 600 }}>{n}</div>
              <div style={{ fontSize: 11, color: MUTED, marginTop: 2 }}>{d}</div>
            </div>
            <div style={{
              width: 40, height: 22, borderRadius: 999,
              background: on ? BLUE : '#262626', position: 'relative',
            }}>
              <div style={{
                position: 'absolute', top: 2, left: on ? 20 : 2,
                width: 18, height: 18, borderRadius: '50%',
                background: on ? '#041225' : '#fff',
                transition: 'left 200ms',
              }}/>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

// ═════════════════════════════════════════════════════════════════════════════
// MAIN SCENE
// ═════════════════════════════════════════════════════════════════════════════

function DemoScene() {
  const time = useTime();

  // scene boundaries
  const scenes = [
    { start: 0,  end: 5,  idx: 0 },
    { start: 5,  end: 11, idx: 1 },
    { start: 11, end: 17, idx: 2 },
    { start: 17, end: 23, idx: 3 },
    { start: 23, end: 29, idx: 4 },
    { start: 29, end: 35, idx: 5 },
    { start: 35, end: 41, idx: 6 },
    { start: 41, end: 48, idx: 7 },
  ];
  const current = scenes.find(s => time >= s.start && time < s.end) || scenes[scenes.length - 1];

  // ease helper for in/out per scene
  const sceneProgress = (s, fadeIn = 0.6, fadeOut = 0.6) => {
    if (time < s.start) return 0;
    if (time > s.end) return 0;
    const t = time - s.start;
    const dur = s.end - s.start;
    const inP  = Math.min(1, t / fadeIn);
    const outP = Math.min(1, (dur - t) / fadeOut);
    return Easing.easeOutCubic(Math.max(0, Math.min(inP, outP)));
  };

  return (
    <div style={{ position: 'absolute', inset: 0, background: BG, overflow: 'hidden' }}>
      {/* background particles + gradient */}
      <div style={{
        position: 'absolute', inset: 0,
        background: `radial-gradient(ellipse 900px 500px at 50% 20%, ${BLUE}14, transparent 60%),
                     radial-gradient(ellipse 700px 400px at 80% 100%, ${BLUE}0a, transparent 60%),
                     linear-gradient(180deg, #0D1018 0%, #050505 70%)`,
      }}/>
      <Particles/>

      {/* grid backdrop */}
      <div style={{
        position: 'absolute', inset: 0, opacity: 0.04,
        backgroundImage: `linear-gradient(${BLUE}88 1px, transparent 1px),
                          linear-gradient(90deg, ${BLUE}88 1px, transparent 1px)`,
        backgroundSize: '60px 60px',
      }}/>

      {/* ── SCENE 0 — Intro */}
      <Sprite start={0} end={5.4}>
        <IntroScene/>
      </Sprite>

      {/* ── SCENE 1 — Today */}
      <Sprite start={5} end={11.4}>
        <SceneWithPhone
          progress={sceneProgress(scenes[1])}
          eyebrow="01 · HOME"
          title="Your day, built around your body."
          sub="LUNARO opens on Today — a single screen that reflects your current phase, the session that fits it, and the signals behind the plan."
          screen={<ScreenToday/>}
          callouts={[
            { x: 720, y: 160, label: 'Phase-aware banner', title: 'Follicular · Day 8',
              body: 'Guidance shifts with your cycle — every day, not just once a plan.',
              pointerFrom: { x: 720, y: 260 }, pointerTo: { x: 635, y: 238 } },
            { x: 720, y: 380, label: 'Session card', title: 'Matched to today',
              body: 'The workout you see is the one your body is ready for — pulled from your plan and tuned to phase.',
              pointerFrom: { x: 720, y: 450 }, pointerTo: { x: 635, y: 390 } },
          ]}
        />
      </Sprite>

      {/* ── SCENE 2 — Plan */}
      <Sprite start={11} end={17.4}>
        <SceneWithPhone
          progress={sceneProgress(scenes[2])}
          eyebrow="02 · PLAN"
          title="A plan that shifts, not slips."
          sub="Your week is written once and then re-tuned every time your data changes. Strength days go to follicular and ovulation. Zone-2 and mobility to luteal and menstrual."
          screen={<ScreenPlan/>}
          callouts={[
            { x: 720, y: 180, label: 'Completed', title: 'What you\'ve already logged',
              body: 'Green dots = session done. LUNARO remembers load and rolls it into next week\'s prescription.',
              pointerFrom: { x: 720, y: 240 }, pointerTo: { x: 630, y: 240 } },
            { x: 720, y: 400, label: 'Today', title: 'Highlighted row',
              body: 'One tap opens the full workout. The highlight moves forward as days pass.',
              pointerFrom: { x: 720, y: 460 }, pointerTo: { x: 630, y: 360 } },
          ]}
        />
      </Sprite>

      {/* ── SCENE 3 — Cycle ring */}
      <Sprite start={17} end={23.4}>
        <SceneWithPhone
          progress={sceneProgress(scenes[3])}
          eyebrow="03 · CYCLE"
          title="One ring, four phases, every day."
          sub="The signature LUNARO viz. Each arc is a phase. The pulsing dot is today. Tap a phase to see what training it unlocks."
          screen={<ScreenCycle/>}
          callouts={[
            { x: 720, y: 180, label: 'Phase ring', title: 'Hormonal seasons, visualized',
              body: 'Menstrual · Follicular · Ovulation · Luteal — colored by semantic meaning, not gender stereotype.',
              pointerFrom: { x: 720, y: 240 }, pointerTo: { x: 635, y: 340 } },
            { x: 720, y: 420, label: 'Day marker', title: 'Pulses on current day',
              body: 'You always know where you are in your cycle without opening a calendar.',
              pointerFrom: { x: 720, y: 470 }, pointerTo: { x: 635, y: 420 } },
          ]}
        />
      </Sprite>

      {/* ── SCENE 4 — Workout detail */}
      <Sprite start={23} end={29.4}>
        <SceneWithPhone
          progress={sceneProgress(scenes[4])}
          eyebrow="04 · TRAIN"
          title="Built for mid-set, not mid-menu."
          sub="Form demo, set log, and rest timer in one screen. Thumb-reach weight entry. Haptic confirmation on every completed set."
          screen={<ScreenWorkout/>}
          callouts={[
            { x: 720, y: 150, label: 'Form demo', title: 'Loops while you set up',
              body: 'Tap once to expand. Never loses your place in the session.',
              pointerFrom: { x: 720, y: 220 }, pointerTo: { x: 635, y: 200 } },
            { x: 720, y: 350, label: 'Set progress', title: 'Next set surfaced in accent',
              body: 'No scrolling to find your place — the active set is always the lit one.',
              pointerFrom: { x: 720, y: 410 }, pointerTo: { x: 635, y: 420 } },
          ]}
        />
      </Sprite>

      {/* ── SCENE 5 — Progress */}
      <Sprite start={29} end={35.4}>
        <SceneWithPhone
          progress={sceneProgress(scenes[5])}
          eyebrow="05 · PROGRESS"
          title="Proof your training is working."
          sub="PR trend, non-scale victories, and phase-aware performance curves — so recovery weeks don't look like regression."
          screen={<ScreenProgress/>}
          callouts={[
            { x: 720, y: 180, label: 'PR bars', title: 'Cycle-adjusted baseline',
              body: 'Heavy days compared against the right baseline, not last Tuesday.',
              pointerFrom: { x: 720, y: 250 }, pointerTo: { x: 635, y: 280 } },
            { x: 720, y: 420, label: 'Victories feed', title: 'Non-scale wins',
              body: 'PRs, consistency, and pace alongside the numbers that matter to you.',
              pointerFrom: { x: 720, y: 480 }, pointerTo: { x: 635, y: 470 } },
          ]}
        />
      </Sprite>

      {/* ── SCENE 6 — Integrations */}
      <Sprite start={35} end={41.4}>
        <SceneWithPhone
          progress={sceneProgress(scenes[6])}
          eyebrow="06 · CONNECT"
          title="Your wearables, one source of truth."
          sub="Apple Health, Oura, Garmin, Whoop, MyFitnessPal. LUNARO reads sleep, HRV, temperature, and load — and writes them back into tomorrow's plan."
          screen={<ScreenIntegrations/>}
          callouts={[
            { x: 720, y: 200, label: 'Already connected', title: 'Three taps to sync',
              body: 'Apple Health, Oura, Garmin. Your data flows in the moment you finish setup.',
              pointerFrom: { x: 720, y: 260 }, pointerTo: { x: 635, y: 230 } },
            { x: 720, y: 420, label: 'Ready to add', title: 'Expandable as you grow',
              body: 'Whoop and MyFitnessPal plug in next — no settings dig, no manual CSVs.',
              pointerFrom: { x: 720, y: 480 }, pointerTo: { x: 635, y: 430 } },
          ]}
        />
      </Sprite>

      {/* ── SCENE 7 — Outro */}
      <Sprite start={41} end={48}>
        <OutroScene progress={sceneProgress(scenes[7], 0.8, 0.8)}/>
      </Sprite>

      <Chrome/>
      <SceneDots current={current.idx}/>
    </div>
  );
}

// ── Intro scene ─────────────────────────────────────────────────────────────
function IntroScene() {
  const { localTime, progress } = useSprite();
  const t = localTime;
  const logoP = Easing.easeOutCubic(Math.min(1, t / 1.2));
  const subP = Easing.easeOutCubic(Math.min(1, Math.max(0, (t - 1.2) / 0.8)));
  const fadeOut = t > 4.5 ? 1 - (t - 4.5) / 0.8 : 1;
  const alpha = Math.max(0, Math.min(1, fadeOut));
  return (
    <div style={{
      position: 'absolute', inset: 0,
      display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
      opacity: alpha,
    }}>
      <div style={{
        fontSize: 11, letterSpacing: '0.4em', textTransform: 'uppercase',
        color: BLUE, fontWeight: 700, marginBottom: 28,
        opacity: logoP, transform: `translateY(${(1 - logoP) * 12}px)`,
      }}>A Product Tour · 00:45</div>
      <div style={{
        fontFamily: 'Urbanist, sans-serif', fontWeight: 800,
        fontSize: 160, letterSpacing: '0.18em', color: BLUE, lineHeight: 1,
        opacity: logoP, transform: `scale(${0.92 + logoP * 0.08})`,
        textShadow: `0 0 80px ${BLUE}55`,
      }}>LUNARO</div>
      <div style={{
        marginTop: 28, fontSize: 22, color: '#E4E4E4', fontWeight: 400,
        maxWidth: 720, textAlign: 'center', lineHeight: 1.4,
        opacity: subP, transform: `translateY(${(1 - subP) * 12}px)`,
      }}>Female endurance OS — training that moves with your body, not against it.</div>
    </div>
  );
}

// ── Outro scene ─────────────────────────────────────────────────────────────
function OutroScene({ progress }) {
  return (
    <div style={{
      position: 'absolute', inset: 0,
      display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
      opacity: progress,
    }}>
      <div style={{
        fontSize: 11, letterSpacing: '0.3em', textTransform: 'uppercase',
        color: BLUE, fontWeight: 700, marginBottom: 20,
      }}>Founding rate · Wave 01</div>
      <div style={{
        fontFamily: 'Urbanist, sans-serif', fontWeight: 800,
        fontSize: 92, lineHeight: 0.98, letterSpacing: '-0.03em',
        color: '#fff', textAlign: 'center', maxWidth: 960,
      }}>Lock in founder pricing.<br/><span style={{ color: BLUE, fontStyle: 'italic' }}>$14/mo, for life.</span></div>
      <div style={{
        marginTop: 32, display: 'flex', gap: 14, alignItems: 'center',
        padding: '14px 18px', borderRadius: 16,
        background: '#0A0A0A', border: `1px solid ${BLUE}55`,
      }}>
        <span style={{ fontSize: 10, color: MUTED, letterSpacing: '0.26em', textTransform: 'uppercase', fontWeight: 600 }}>Your code</span>
        <span style={{ fontFamily: 'ui-monospace, monospace', fontSize: 22, fontWeight: 700, letterSpacing: '0.12em' }}>first30</span>
        <span style={{
          padding: '10px 18px', borderRadius: 10, background: BLUE, color: '#041225',
          fontSize: 13, fontWeight: 700, letterSpacing: '0.04em',
        }}>Redeem →</span>
      </div>
      <div style={{ marginTop: 34, fontSize: 14, color: MUTED, letterSpacing: '0.2em', textTransform: 'uppercase' }}>lunaroco.ai</div>
    </div>
  );
}

// ── Scene wrapper: phone on left, callouts + caption ────────────────────────
function SceneWithPhone({ progress, eyebrow, title, sub, screen, callouts = [] }) {
  // phone slides in from left on scene entry
  const phoneX = 120 + (1 - progress) * -60;
  return (
    <div style={{ position: 'absolute', inset: 0, opacity: progress }}>
      {/* phone */}
      <div style={{ position: 'absolute', left: phoneX, top: 70 }}>
        <Phone scale={0.78}>
          {screen}
        </Phone>
      </div>

      {/* pointer lines */}
      {callouts.map((c, i) => c.pointerFrom && (
        <Pointer key={`p${i}`}
          x1={c.pointerFrom.x} y1={c.pointerFrom.y}
          x2={c.pointerTo.x} y2={c.pointerTo.y}
          progress={progress}/>
      ))}

      {/* callouts */}
      {callouts.map((c, i) => (
        <Callout key={i} x={c.x} y={c.y} width={320} progress={progress}>
          <CalloutCard label={c.label} title={c.title} body={c.body}/>
        </Callout>
      ))}

      {/* caption bottom-left */}
      <Caption eyebrow={eyebrow} title={title} sub={sub} progress={progress}/>
    </div>
  );
}

// ── Export to window so Stage can find components defined here ──────────────
Object.assign(window, {
  DemoScene, Phone, Callout, CalloutCard, Pointer, Particles, Chrome, Caption,
  SceneDots, ScreenToday, ScreenPlan, ScreenCycle, ScreenWorkout, ScreenProgress,
  ScreenIntegrations, IntroScene, OutroScene, SceneWithPhone,
});
