// onboarding.jsx — First-entry flow: splash → carousel → auth → setup → reveal

const { useState: useStateO, useEffect: useEffectO, useRef: useRefO } = React;
const { Card, Chip, DisplayHeading, Icon } = window.LAUNCH_SCREENS_1;

// Genre options — for selection step
const GENRES = [
  { id: 'pop',       l: 'POP',           pal: ['#C72820', '#FBBF24'] },
  { id: 'rb',        l: 'R&B / SOUL',    pal: ['#7A5AE0', '#C72820'] },
  { id: 'hiphop',    l: 'HIP HOP / RAP', pal: ['#0A0A0A', '#C72820'] },
  { id: 'electronic',l: 'ELECTRONIC',    pal: ['#CAFF33', '#7A5AE0'] },
  { id: 'indie',     l: 'INDIE / ALT',   pal: ['#FBBF24', '#7A5AE0'] },
  { id: 'country',   l: 'COUNTRY',       pal: ['#C72820', '#FBBF24'] },
  { id: 'rock',      l: 'ROCK',          pal: ['#0A0A0A', '#7A5AE0'] },
  { id: 'jazz',      l: 'JAZZ / NEO',    pal: ['#7A5AE0', '#FBBF24'] },
];

const GOALS = [
  { id: 'release',  l: 'Release my first single',  icon: '🎵' },
  { id: 'grow',     l: 'Grow my audience',         icon: '📈' },
  { id: 'monetize', l: 'Make money from music',    icon: '💰' },
  { id: 'craft',    l: 'Sharpen my craft',         icon: '🎙' },
  { id: 'collab',   l: 'Find collaborators',       icon: '🤝' },
  { id: 'label',    l: 'Get signed',               icon: '⭐' },
];

const EXPERIENCE = [
  { id: 'starting',  l: 'Just starting out',           sub: 'Less than 6 months in' },
  { id: 'demoing',   l: 'Making demos',                sub: '6 months — 2 years' },
  { id: 'releasing', l: 'Released a few tracks',       sub: '2+ years, some music out' },
  { id: 'building',  l: 'Building real momentum',      sub: 'Touring, streams, fans' },
];

// ────────────────────────────────────────────────────────
// 0. SPLASH — pure black with the LAUNCH logo, modern + minimal
// ────────────────────────────────────────────────────────
function SplashScreen({ theme, onContinue }) {
  // Auto-advance after the entry animation
  useEffectO(() => {
    const t = setTimeout(onContinue, 3200);
    return () => clearTimeout(t);
  }, [onContinue]);

  return (
    <div onClick={onContinue} style={{
      width: '100%', height: '100%', cursor: 'pointer',
      background: '#000', position: 'relative', overflow: 'hidden',
      display: 'flex', flexDirection: 'column',
      alignItems: 'center', justifyContent: 'center',
    }}>
      {/* Faint star drift — purely atmospheric */}
      <svg width="100%" height="100%" viewBox="0 0 400 880" preserveAspectRatio="none"
        style={{ position: 'absolute', inset: 0, opacity: 0.5, pointerEvents: 'none' }}>
        {Array.from({ length: 50 }, (_, i) => {
          const x = (i * 71) % 400;
          const y = (i * 137) % 880;
          const r = (i % 7 === 0) ? 1.6 : (i % 3 === 0) ? 1 : 0.5;
          return (
            <circle key={i} cx={x} cy={y} r={r} fill="#fff"
              opacity={(i % 4) * 0.18 + 0.3}
              style={{ animation: `splashTwinkle ${2 + (i % 4)}s ${(i % 5) * 0.4}s infinite ease-in-out` }}
            />
          );
        })}
      </svg>

      {/* Soft red bloom anchored where the flame is */}
      <div style={{
        position: 'absolute',
        width: 440, height: 440, borderRadius: '50%',
        left: '50%', top: '50%',
        transform: 'translate(-62%, -38%)',
        background: 'radial-gradient(circle, rgba(199,40,32,0.35) 0%, rgba(199,40,32,0) 60%)',
        filter: 'blur(8px)',
        animation: 'splashBloom 2.4s ease-out',
        pointerEvents: 'none',
      }} />

      {/* Logo — the hero */}
      <div style={{
        position: 'relative', zIndex: 2,
        width: '88%', maxWidth: 360,
        animation: 'splashLogoIn 1.1s cubic-bezier(.16,.84,.28,1) both',
      }}>
        <img
          src="assets/launch-logo.png"
          alt="LAUNCH"
          style={{
            width: '100%', height: 'auto', display: 'block',
            filter: 'drop-shadow(0 16px 40px rgba(199,40,32,0.35)) drop-shadow(0 4px 16px rgba(0,0,0,0.6))',
          }}
        />
      </div>

      {/* Tagline */}
      <div style={{
        position: 'absolute', bottom: 110,
        left: 0, right: 0, textAlign: 'center', zIndex: 2,
        animation: 'splashTagIn 0.8s 0.7s ease both',
      }}>
        <div style={{
          fontFamily: 'JetBrains Mono, monospace', fontSize: 11,
          color: '#C72820', letterSpacing: 6, fontWeight: 700,
        }}>★ ARTIST DEVELOPMENT CO ★</div>
        <div style={{
          fontFamily: '"Space Grotesk", system-ui, sans-serif', fontSize: 13,
          color: 'rgba(255,255,255,0.55)', letterSpacing: 0.5,
          marginTop: 10, fontStyle: 'italic',
        }}>
          For artists who don't wait to be discovered.
        </div>
      </div>

      {/* Loader bar */}
      <div style={{
        position: 'absolute', bottom: 50, left: 0, right: 0,
        display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 10,
      }}>
        <div style={{
          width: 140, height: 2, borderRadius: 99,
          background: 'rgba(255,255,255,0.08)', overflow: 'hidden', position: 'relative',
        }}>
          <div style={{
            position: 'absolute', top: 0, left: 0, height: '100%',
            background: '#C72820',
            animation: 'splashProgress 3s ease-out forwards',
          }} />
        </div>
        <div style={{
          fontFamily: 'JetBrains Mono, monospace', fontSize: 9,
          color: 'rgba(255,255,255,0.35)', letterSpacing: 3, fontWeight: 600,
        }}>IGNITION · TAP TO SKIP</div>
      </div>

      <style>{`
        @keyframes splashLogoIn {
          0%   { transform: scale(0.6) translateY(40px); opacity: 0; filter: blur(8px); }
          60%  { opacity: 1; filter: blur(0); }
          100% { transform: scale(1) translateY(0); opacity: 1; }
        }
        @keyframes splashBloom {
          0%   { opacity: 0; transform: translate(-62%, -38%) scale(0.5); }
          60%  { opacity: 1; transform: translate(-62%, -38%) scale(1.05); }
          100% { opacity: 0.8; transform: translate(-62%, -38%) scale(1); }
        }
        @keyframes splashTagIn { from { opacity: 0; transform: translateY(8px); } to { opacity: 1; transform: translateY(0); } }
        @keyframes splashProgress { from { width: 0% } to { width: 100% } }
        @keyframes splashTwinkle { 0%, 100% { opacity: 0.3 } 50% { opacity: 0.9 } }
        @keyframes launchScaleIn { from { transform: scale(0.9); opacity: 0 } to { transform: scale(1); opacity: 1 } }
        @keyframes launchFadeIn { from { opacity: 0 } to { opacity: 1 } }
        @keyframes launchSlideUp { from { transform: translateY(20px); opacity: 0 } to { transform: translateY(0); opacity: 1 } }
      `}</style>
    </div>
  );
}

// ────────────────────────────────────────────────────────
// 1. WELCOME CAROUSEL — 3 swipeable value-prop slides
// ────────────────────────────────────────────────────────
function WelcomeCarousel({ theme, onContinue, onSignIn }) {
  const [step, setStep] = useStateO(0);

  const slides = [
    {
      kicker: '★ WHY LAUNCH',
      title: <>FROM<br/>BEDROOM<br/>TO <span style={{ color: theme.accent }}>BILLBOARD.</span></>,
      blurb: 'A development company built for artists in their twenties. Lessons, mentors, and a squad that actually wants you to win.',
      art: 'rocket',
    },
    {
      kicker: '★ REAL MENTORS',
      title: <>SIGNED PROS.<br/><span style={{ color: theme.accent }}>HONEST</span><br/>FEEDBACK.</>,
      blurb: '4× Grammy producers. Top 40 songwriters. A&R reps from the labels you actually want to be on. Coaching, not influencer fluff.',
      art: 'orbit',
    },
    {
      kicker: '★ THE SQUAD',
      title: <>BUILD WITH<br/>2K+ ARTISTS<br/><span style={{ color: theme.accent }}>LIKE YOU.</span></>,
      blurb: 'Drop tracks. Get feedback. Climb the leaderboard. Find your collaborators before you find your label.',
      art: 'constellation',
    },
  ];

  const cur = slides[step];

  // Art renderers
  const renderArt = (kind) => {
    if (kind === 'rocket') {
      return (
        <svg viewBox="0 0 240 200" width="100%" height="220">
          <defs>
            <linearGradient id="trail" x1="0" y1="0" x2="0" y2="1">
              <stop offset="0%" stopColor={theme.accent} stopOpacity="0"/>
              <stop offset="100%" stopColor={theme.accent} stopOpacity="0.6"/>
            </linearGradient>
            <radialGradient id="planet" cx="35%" cy="35%">
              <stop offset="0%" stopColor="#7AA8FF"/>
              <stop offset="100%" stopColor="#0B1030"/>
            </radialGradient>
          </defs>
          {/* stars */}
          {[[30,40,1],[200,60,1.2],[60,160,1],[180,150,0.8],[120,30,0.7]].map(([x,y,r], i) =>
            <circle key={i} cx={x} cy={y} r={r} fill="#fff" opacity="0.7"/>)}
          {/* planet */}
          <circle cx="190" cy="160" r="34" fill="url(#planet)"/>
          {/* trail */}
          <rect x="115" y="120" width="10" height="80" fill="url(#trail)" rx="5"/>
          {/* rocket body */}
          <path d="M120 30 L100 110 L140 110 Z" fill="#fff" stroke="#0A0A0A" strokeWidth="2.5"/>
          <circle cx="120" cy="70" r="8" fill={theme.accent}/>
          {/* fins */}
          <path d="M100 110 L88 130 L108 122 Z" fill={theme.accent}/>
          <path d="M140 110 L152 130 L132 122 Z" fill={theme.accent}/>
          {/* flame */}
          <path d="M108 122 L120 145 L132 122" fill="#FBBF24"/>
          <path d="M114 128 L120 140 L126 128" fill={theme.accent}/>
        </svg>
      );
    }
    if (kind === 'orbit') {
      return (
        <svg viewBox="0 0 240 200" width="100%" height="220">
          <defs>
            <radialGradient id="sun" cx="50%" cy="50%">
              <stop offset="0%" stopColor="#FBBF24"/>
              <stop offset="60%" stopColor={theme.accent}/>
              <stop offset="100%" stopColor="#7A1A0A"/>
            </radialGradient>
          </defs>
          {/* orbit rings */}
          <ellipse cx="120" cy="100" rx="100" ry="38" fill="none" stroke="rgba(255,255,255,0.15)" strokeWidth="1"/>
          <ellipse cx="120" cy="100" rx="70" ry="26" fill="none" stroke="rgba(255,255,255,0.2)" strokeWidth="1"/>
          {/* sun */}
          <circle cx="120" cy="100" r="32" fill="url(#sun)"/>
          {/* small planets / mentors */}
          {[
            { x: 220, y: 100, r: 8, c: '#7A5AE0' },
            { x: 50, y: 100, r: 7, c: '#CAFF33' },
            { x: 120, y: 62, r: 6, c: '#FBBF24' },
            { x: 170, y: 126, r: 5, c: '#C72820' },
          ].map((p, i) => (
            <g key={i}>
              <circle cx={p.x} cy={p.y} r={p.r + 4} fill={p.c} opacity="0.2"/>
              <circle cx={p.x} cy={p.y} r={p.r} fill={p.c}/>
            </g>
          ))}
          {/* stars */}
          {[[30,30,0.8],[210,40,1],[40,170,0.7],[200,170,0.9]].map(([x,y,r], i) =>
            <circle key={i} cx={x} cy={y} r={r} fill="#fff" opacity="0.6"/>)}
        </svg>
      );
    }
    // constellation
    return (
      <svg viewBox="0 0 240 200" width="100%" height="220">
        {/* connecting lines */}
        <path d="M40,60 L90,40 L130,80 L180,50 L210,100 L160,140 L100,150 L50,120 Z M90,40 L130,80 L100,150 M180,50 L160,140"
          fill="none" stroke={theme.accent} strokeWidth="1" opacity="0.4" strokeDasharray="2,3"/>
        {/* member nodes */}
        {[
          [40,60,'SV','#CAFF33'],
          [90,40,'KP','#C72820'],
          [130,80,'TM','#7A5AE0'],
          [180,50,'IL','#FBBF24'],
          [210,100,'MS','#C72820'],
          [160,140,'JE','#22C55E'],
          [100,150,'NB','#EC4899'],
          [50,120,'RL','#06B6D4'],
        ].map(([x,y,lbl,c], i) => (
          <g key={i}>
            <circle cx={x} cy={y} r="14" fill={c} stroke="#0A0A0A" strokeWidth="1.5"/>
            <text x={x} y={y+4} textAnchor="middle" fontFamily="Anton" fontSize="11" fill="#0A0A0A">{lbl}</text>
          </g>
        ))}
      </svg>
    );
  };

  return (
    <div style={{
      width: '100%', height: '100%', background: '#0A0A0A',
      position: 'relative', display: 'flex', flexDirection: 'column',
      overflow: 'hidden',
    }}>
      {/* bg gradient */}
      <div style={{
        position: 'absolute', inset: 0,
        background: `radial-gradient(circle at 30% 20%, ${theme.accent}25 0%, transparent 60%)`,
      }} />
      {/* stars */}
      <svg width="100%" height="100%" viewBox="0 0 400 880" preserveAspectRatio="none"
        style={{ position: 'absolute', inset: 0, opacity: 0.5 }}>
        {Array.from({ length: 50 }, (_, i) => {
          const x = (i * 71) % 400;
          const y = (i * 157) % 880;
          const r = (i % 5 === 0) ? 1.2 : 0.6;
          return <circle key={i} cx={x} cy={y} r={r} fill="#fff" opacity={(i % 4) * 0.2 + 0.4}/>;
        })}
      </svg>

      {/* Skip / sign in */}
      <div style={{
        paddingTop: 58, paddingLeft: 18, paddingRight: 18,
        display: 'flex', justifyContent: 'space-between',
        position: 'relative', zIndex: 2,
      }}>
        <div style={{
          fontFamily: 'JetBrains Mono, monospace', fontSize: 11,
          color: theme.accent, letterSpacing: 2, fontWeight: 700,
        }}>LAUNCH<span style={{ color: '#fff' }}>.</span></div>
        <button onClick={onSignIn} style={{
          background: 'transparent', border: '1px solid rgba(255,255,255,0.15)',
          color: '#fff', borderRadius: 99,
          fontFamily: 'JetBrains Mono, monospace', fontSize: 10, fontWeight: 700,
          letterSpacing: 1, padding: '7px 12px', cursor: 'pointer',
          textTransform: 'uppercase',
        }}>SIGN IN</button>
      </div>

      {/* Art */}
      <div style={{ padding: '20px 18px 0', position: 'relative', zIndex: 2 }} key={step + '-art'}>
        <div style={{ animation: 'launchSlideUp 0.5s ease' }}>
          {renderArt(cur.art)}
        </div>
      </div>

      {/* Copy */}
      <div style={{ padding: '20px 24px', flex: 1, position: 'relative', zIndex: 2 }} key={step + '-text'}>
        <div style={{ animation: 'launchSlideUp 0.5s ease 0.1s both' }}>
          <div style={{
            fontFamily: 'JetBrains Mono, monospace', fontSize: 10,
            color: theme.accent, letterSpacing: 2, fontWeight: 700,
          }}>{cur.kicker}</div>
          <div style={{
            fontFamily: theme.fontDisplay, fontSize: 48, color: '#fff',
            letterSpacing: 0.5, lineHeight: 0.92,
            marginTop: 16, textTransform: 'uppercase',
          }}>{cur.title}</div>
          <div style={{
            fontFamily: theme.fontBody, fontSize: 15, color: 'rgba(255,255,255,0.7)',
            marginTop: 18, lineHeight: 1.5,
          }}>{cur.blurb}</div>
        </div>
      </div>

      {/* Dots + CTA */}
      <div style={{
        padding: '0 24px 30px', position: 'relative', zIndex: 2,
        display: 'flex', flexDirection: 'column', gap: 18,
      }}>
        <div style={{ display: 'flex', justifyContent: 'center', gap: 6 }}>
          {slides.map((_, i) => (
            <div key={i} style={{
              width: i === step ? 28 : 8, height: 8, borderRadius: 99,
              background: i === step ? theme.accent : 'rgba(255,255,255,0.2)',
              transition: 'width .25s',
            }} />
          ))}
        </div>
        <button
          onClick={() => step < slides.length - 1 ? setStep(step + 1) : onContinue()}
          style={{
            width: '100%', background: theme.accent, color: theme.onAccent,
            border: 'none', borderRadius: 14,
            fontFamily: theme.fontDisplay, fontSize: 16, letterSpacing: 1,
            padding: '18px', cursor: 'pointer', textTransform: 'uppercase',
          }}>
          {step < slides.length - 1 ? 'NEXT →' : 'LET\'S GO →'}
        </button>
      </div>
    </div>
  );
}

// ────────────────────────────────────────────────────────
// 2. AUTH — sign up / sign in
// ────────────────────────────────────────────────────────
function AuthScreen({ theme, mode = 'signup', onContinue, onBack, onSwitchMode, onOAuth, busy, errorMsg, noticeMsg }) {
  const [email, setEmail] = useStateO('');
  const [password, setPassword] = useStateO('');
  const [name, setName] = useStateO('');
  const [handle, setHandle] = useStateO('');
  const [keepSignedIn, setKeepSignedIn] = useStateO(true);

  const inputStyle = {
    width: '100%', padding: '14px 16px', borderRadius: 12,
    background: 'rgba(255,255,255,0.06)', border: '1px solid rgba(255,255,255,0.12)',
    color: '#fff', fontFamily: theme.fontBody, fontSize: 15,
    outline: 'none', boxSizing: 'border-box',
  };

  return (
    <div style={{
      width: '100%', height: '100%', background: '#0A0A0A',
      position: 'relative', overflow: 'auto', color: '#fff',
    }}>
      {/* stars */}
      <svg width="100%" height="100%" viewBox="0 0 400 880" preserveAspectRatio="none"
        style={{ position: 'absolute', inset: 0, opacity: 0.4, pointerEvents: 'none' }}>
        {Array.from({ length: 40 }, (_, i) => {
          const x = (i * 53) % 400;
          const y = (i * 113) % 880;
          const r = (i % 5 === 0) ? 1.2 : 0.6;
          return <circle key={i} cx={x} cy={y} r={r} fill="#fff" opacity={(i % 4) * 0.2 + 0.4}/>;
        })}
      </svg>

      {/* Top bar */}
      <div style={{
        paddingTop: 58, paddingLeft: 18, paddingRight: 18,
        display: 'flex', justifyContent: 'space-between', alignItems: 'center',
        position: 'relative',
      }}>
        <button onClick={onBack} style={{
          width: 38, height: 38, borderRadius: 12,
          background: 'rgba(255,255,255,0.08)', border: '1px solid rgba(255,255,255,0.12)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          cursor: 'pointer',
        }}>
          <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
            <path d="M9 2L4 7l5 5" stroke="#fff" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
        </button>
        <div style={{
          fontFamily: 'JetBrains Mono, monospace', fontSize: 10,
          color: 'rgba(255,255,255,0.5)', letterSpacing: 1, fontWeight: 700,
        }}>{mode === 'signup' ? 'CREATE ACCOUNT' : 'WELCOME BACK'}</div>
        <div style={{ width: 38 }} />
      </div>

      {/* Hero */}
      <div style={{ padding: '20px 24px 0', position: 'relative' }}>
        <div style={{
          fontFamily: 'JetBrains Mono, monospace', fontSize: 11,
          color: theme.accent, letterSpacing: 2, fontWeight: 700,
        }}>★ {mode === 'signup' ? 'STEP 1 OF 4' : 'BOARDING PASS'}</div>
        <div style={{
          fontFamily: theme.fontDisplay, fontSize: 40, color: '#fff',
          letterSpacing: 0.5, lineHeight: 0.92,
          marginTop: 8, textTransform: 'uppercase',
        }}>
          {mode === 'signup'
            ? <>LET'S GET<br/>YOU <span style={{ color: theme.accent }}>IN</span>.</>
            : <>WELCOME<br/><span style={{ color: theme.accent }}>BACK</span>.</>}
        </div>
      </div>

      {/* OAuth */}
      <div style={{ padding: '24px 24px 0', position: 'relative', display: 'flex', flexDirection: 'column', gap: 10 }}>
        {[
          { l: 'CONTINUE WITH APPLE', p: 'apple', icon: (
            <svg width="18" height="18" viewBox="0 0 24 24" fill="#fff">
              <path d="M17.05 12.04c-.03-2.91 2.38-4.3 2.49-4.37-1.36-1.99-3.48-2.27-4.23-2.3-1.8-.18-3.51 1.06-4.43 1.06-.91 0-2.32-1.03-3.81-1.01-1.96.03-3.77 1.14-4.78 2.89-2.04 3.55-.52 8.79 1.46 11.66.97 1.4 2.12 2.98 3.62 2.92 1.46-.06 2.01-.94 3.78-.94 1.76 0 2.27.94 3.81.91 1.57-.03 2.57-1.43 3.53-2.84 1.11-1.62 1.57-3.19 1.6-3.27-.03-.02-3.07-1.18-3.04-4.71zM14.13 3.6c.81-.98 1.36-2.34 1.21-3.69-1.17.05-2.59.78-3.42 1.76-.75.87-1.41 2.26-1.23 3.59 1.3.1 2.63-.66 3.44-1.66z"/>
            </svg>
          )},
          { l: 'CONTINUE WITH GOOGLE', p: 'google', icon: (
            <svg width="18" height="18" viewBox="0 0 24 24">
              <path d="M22 12.27c0-.79-.07-1.54-.2-2.27H12v4.3h5.6c-.24 1.3-.97 2.4-2.07 3.14v2.61h3.35c1.96-1.8 3.12-4.46 3.12-7.78z" fill="#4285F4"/>
              <path d="M12 22.5c2.8 0 5.16-.93 6.88-2.52l-3.35-2.6c-.93.62-2.12.99-3.53.99-2.71 0-5-1.83-5.83-4.29H2.74v2.69A10 10 0 0012 22.5z" fill="#34A853"/>
              <path d="M6.17 14.08A6 6 0 015.85 12c0-.72.12-1.42.32-2.08V7.23H2.74A10 10 0 002 12c0 1.61.38 3.13 1.05 4.48l3.12-2.4z" fill="#FBBC05"/>
              <path d="M12 5.7c1.53 0 2.9.53 3.97 1.55l2.97-2.97C17.16 2.6 14.8 1.5 12 1.5a10 10 0 00-8.96 5.73l3.12 2.4C6.96 7.36 9.29 5.7 12 5.7z" fill="#EA4335"/>
            </svg>
          )},
        ].map((opt, i) => (
          <button key={i} onClick={() => onOAuth && onOAuth(opt.p)} style={{
            display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10,
            padding: '14px 18px', borderRadius: 12,
            background: 'rgba(255,255,255,0.06)', border: '1px solid rgba(255,255,255,0.12)',
            color: '#fff', fontFamily: 'JetBrains Mono, monospace', fontSize: 12, fontWeight: 700,
            letterSpacing: 1, cursor: 'pointer',
          }}>{opt.icon}{opt.l}</button>
        ))}
      </div>

      {/* Divider */}
      <div style={{
        padding: '20px 24px 0', display: 'flex', alignItems: 'center', gap: 12,
        position: 'relative',
      }}>
        <div style={{ flex: 1, height: 1, background: 'rgba(255,255,255,0.1)' }} />
        <span style={{
          fontFamily: 'JetBrains Mono, monospace', fontSize: 9,
          color: 'rgba(255,255,255,0.4)', letterSpacing: 1, fontWeight: 700,
        }}>OR EMAIL</span>
        <div style={{ flex: 1, height: 1, background: 'rgba(255,255,255,0.1)' }} />
      </div>

      {/* Form */}
      <div style={{ padding: '20px 24px 0', position: 'relative', display: 'flex', flexDirection: 'column', gap: 12 }}>
        {mode === 'signup' && (
          <div>
            <label style={{
              fontFamily: 'JetBrains Mono, monospace', fontSize: 10, color: 'rgba(255,255,255,0.5)',
              letterSpacing: 1, fontWeight: 700, display: 'block', marginBottom: 6,
            }}>YOUR NAME</label>
            <input
              value={name}
              onChange={e => setName(e.target.value)}
              placeholder="e.g. Maya Stokes"
              style={inputStyle}
            />
          </div>
        )}
        {mode === 'signup' && (
          <div>
            <label style={{
              fontFamily: 'JetBrains Mono, monospace', fontSize: 10, color: 'rgba(255,255,255,0.5)',
              letterSpacing: 1, fontWeight: 700, display: 'block', marginBottom: 6,
            }}>YOUR @HANDLE</label>
            <div style={{ position: 'relative' }}>
              <span style={{
                position: 'absolute', left: 16, top: '50%', transform: 'translateY(-50%)',
                color: 'rgba(255,255,255,0.5)', fontFamily: theme.fontBody, fontSize: 15,
              }}>@</span>
              <input
                value={handle}
                onChange={e => setHandle(e.target.value.replace(/\s/g, '.').toLowerCase())}
                placeholder="your.name"
                style={{ ...inputStyle, paddingLeft: 32 }}
              />
            </div>
          </div>
        )}
        <div>
          <label style={{
            fontFamily: 'JetBrains Mono, monospace', fontSize: 10, color: 'rgba(255,255,255,0.5)',
            letterSpacing: 1, fontWeight: 700, display: 'block', marginBottom: 6,
          }}>EMAIL</label>
          <input
            value={email}
            onChange={e => setEmail(e.target.value)}
            placeholder="you@email.com"
            type="email"
            style={inputStyle}
          />
        </div>
        <div>
          <label style={{
            fontFamily: 'JetBrains Mono, monospace', fontSize: 10, color: 'rgba(255,255,255,0.5)',
            letterSpacing: 1, fontWeight: 700, display: 'block', marginBottom: 6,
          }}>PASSWORD</label>
          <input
            value={password}
            onChange={e => setPassword(e.target.value)}
            placeholder={mode === 'signup' ? 'At least 6 characters' : 'Your password'}
            type="password"
            style={inputStyle}
          />
        </div>
        {errorMsg && (
          <div style={{
            fontFamily: theme.fontBody, fontSize: 12, color: '#FF6B6B',
            background: 'rgba(255,107,107,0.1)', border: '1px solid rgba(255,107,107,0.3)',
            borderRadius: 10, padding: '10px 12px', lineHeight: 1.4,
          }}>{errorMsg}</div>
        )}
        {noticeMsg && (
          <div style={{
            fontFamily: theme.fontBody, fontSize: 12, color: '#22C55E',
            background: 'rgba(34,197,94,0.1)', border: '1px solid rgba(34,197,94,0.3)',
            borderRadius: 10, padding: '10px 12px', lineHeight: 1.4,
            display: 'flex', alignItems: 'flex-start', gap: 8,
          }}><span style={{ flexShrink: 0 }}>📧</span><span>{noticeMsg}</span></div>
        )}
        <button
          onClick={() => !busy && onContinue({ keepSignedIn, handle, name, email, password })}
          style={{
            width: '100%', background: theme.accent, color: theme.onAccent,
            border: 'none', borderRadius: 14,
            fontFamily: theme.fontDisplay, fontSize: 16, letterSpacing: 1,
            padding: '16px', cursor: busy ? 'wait' : 'pointer', textTransform: 'uppercase',
            marginTop: 6, opacity: busy ? 0.7 : 1,
          }}>
          {busy ? 'ONE SEC…' : (mode === 'signup' ? 'CREATE ACCOUNT →' : 'SIGN IN →')}
        </button>

        {/* Keep me signed in */}
        <button
          onClick={() => setKeepSignedIn(v => !v)}
          style={{
            display: 'flex', alignItems: 'center', gap: 10,
            background: 'transparent', border: 'none', padding: '4px 0',
            cursor: 'pointer', marginTop: 4, alignSelf: 'flex-start',
          }}>
          <div style={{
            width: 22, height: 22, borderRadius: 7,
            background: keepSignedIn ? theme.accent : 'transparent',
            border: keepSignedIn ? 'none' : '1.5px solid rgba(255,255,255,0.35)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            flexShrink: 0,
          }}>
            {keepSignedIn && (
              <svg width="12" height="12" viewBox="0 0 14 14" fill="none">
                <path d="M2 7l3.5 3.5L12 4" stroke={theme.onAccent} strokeWidth="2.6" strokeLinecap="round" strokeLinejoin="round"/>
              </svg>
            )}
          </div>
          <div style={{ textAlign: 'left' }}>
            <div style={{
              fontFamily: theme.fontBody, fontSize: 13, color: '#fff', fontWeight: 600,
            }}>Keep me signed in</div>
            <div style={{
              fontFamily: 'JetBrains Mono, monospace', fontSize: 9,
              color: 'rgba(255,255,255,0.45)', letterSpacing: 0.5, fontWeight: 600,
              marginTop: 2,
            }}>SKIP THE LOGIN NEXT TIME · UNCHECK ON SHARED DEVICES</div>
          </div>
        </button>
      </div>

      {/* Switch mode */}
      <div style={{
        padding: '24px 24px 30px', textAlign: 'center', position: 'relative',
      }}>
        <button onClick={onSwitchMode} style={{
          background: 'transparent', border: 'none', cursor: 'pointer',
          fontFamily: theme.fontBody, fontSize: 13, color: 'rgba(255,255,255,0.6)',
        }}>
          {mode === 'signup'
            ? <>Already have an account? <span style={{ color: theme.accent, fontWeight: 600 }}>Sign in</span></>
            : <>New to Launch? <span style={{ color: theme.accent, fontWeight: 600 }}>Create account</span></>}
        </button>
      </div>
    </div>
  );
}

// ────────────────────────────────────────────────────────
// 3. SETUP STEPS — genre, experience, goal
// ────────────────────────────────────────────────────────
function SetupScreen({ theme, onContinue, onBack }) {
  const [step, setStep] = useStateO(0);
  const [genres, setGenres] = useStateO([]);
  const [experience, setExperience] = useStateO(null);
  const [goals, setGoals] = useStateO([]);

  const steps = ['genre', 'experience', 'goal'];
  const cur = steps[step];

  // Toggle an id in/out of a multi-select array.
  const toggle = (setFn) => (id) =>
    setFn(prev => prev.includes(id) ? prev.filter(x => x !== id) : [...prev, id]);
  const toggleGenre = toggle(setGenres);
  const toggleGoal = toggle(setGoals);

  const advance = () => {
    if (step < steps.length - 1) setStep(step + 1);
    // Keep `genre`/`goal` (first pick) for backward compatibility, and pass
    // the full multi-select arrays as `genres`/`goals`.
    else onContinue({ genre: genres[0], experience, goal: goals[0], genres, goals });
  };

  const canAdvance = (cur === 'genre' && genres.length > 0) ||
                     (cur === 'experience' && experience) ||
                     (cur === 'goal' && goals.length > 0);

  return (
    <div style={{
      width: '100%', height: '100%', background: theme.bg,
      position: 'relative', display: 'flex', flexDirection: 'column',
      overflow: 'hidden',
    }}>
      {/* Top bar */}
      <div style={{
        paddingTop: 58, paddingLeft: 18, paddingRight: 18, paddingBottom: 12,
        display: 'flex', alignItems: 'center', gap: 12,
      }}>
        <button onClick={() => step > 0 ? setStep(step - 1) : onBack()} style={{
          width: 38, height: 38, borderRadius: 12,
          background: theme.surface, border: `1px solid ${theme.border}`,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          cursor: 'pointer', flexShrink: 0,
        }}>
          <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
            <path d="M9 2L4 7l5 5" stroke={theme.text} strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
        </button>
        {/* Progress */}
        <div style={{ flex: 1, display: 'flex', gap: 4 }}>
          {steps.map((_, i) => (
            <div key={i} style={{
              flex: 1, height: 4, borderRadius: 99,
              background: i <= step ? theme.accent : theme.surface2,
            }} />
          ))}
        </div>
        <div style={{
          fontFamily: 'JetBrains Mono, monospace', fontSize: 10,
          color: theme.muted, letterSpacing: 1, fontWeight: 700,
        }}>{step + 2}/4</div>
      </div>

      {/* Step content */}
      <div style={{ flex: 1, padding: '4px 18px 0', overflowY: 'auto' }} className="launch-scroll">
        {cur === 'genre' && (
          <>
            <div style={{
              fontFamily: 'JetBrains Mono, monospace', fontSize: 11,
              color: theme.accent, letterSpacing: 2, fontWeight: 700,
            }}>★ YOUR SOUND</div>
            <DisplayHeading theme={theme} size={36} style={{ marginTop: 6 }}>
              WHAT DO YOU<br/>MAKE?
            </DisplayHeading>
            <div style={{
              fontFamily: theme.fontBody, fontSize: 13, color: theme.muted,
              marginTop: 8, marginBottom: 18,
            }}>Pick every genre you make. You can refine later.</div>
            <div style={{
              display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 10,
            }}>
              {GENRES.map(g => {
                const on = genres.includes(g.id);
                return (
                  <button key={g.id} onClick={() => toggleGenre(g.id)} style={{
                    padding: 0, border: 'none', cursor: 'pointer',
                    borderRadius: 14, overflow: 'hidden', textAlign: 'left',
                    position: 'relative', aspectRatio: '1.2',
                    background: `linear-gradient(135deg, ${g.pal[0]} 0%, ${g.pal[1]} 100%)`,
                    boxShadow: on ? `0 0 0 3px ${theme.text}, 0 0 0 5px ${theme.accent}` : 'none',
                    transition: 'box-shadow .15s',
                  }}>
                    <div style={{
                      position: 'absolute', inset: 0, padding: 12,
                      display: 'flex', flexDirection: 'column', justifyContent: 'space-between',
                    }}>
                      {on && (
                        <div style={{
                          width: 24, height: 24, borderRadius: 99,
                          background: '#fff', alignSelf: 'flex-end',
                          display: 'flex', alignItems: 'center', justifyContent: 'center',
                        }}>
                          <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
                            <path d="M2 7l3.5 3.5L12 4" stroke="#0A0A0A" strokeWidth="2.6" strokeLinecap="round" strokeLinejoin="round"/>
                          </svg>
                        </div>
                      )}
                      <div style={{
                        fontFamily: theme.fontDisplay, fontSize: 22, color: '#0A0A0A',
                        letterSpacing: 0.3, lineHeight: 0.95, textTransform: 'uppercase',
                        marginTop: 'auto',
                      }}>{g.l}</div>
                    </div>
                  </button>
                );
              })}
            </div>
          </>
        )}

        {cur === 'experience' && (
          <>
            <div style={{
              fontFamily: 'JetBrains Mono, monospace', fontSize: 11,
              color: theme.accent, letterSpacing: 2, fontWeight: 700,
            }}>★ YOUR ORBIT</div>
            <DisplayHeading theme={theme} size={36} style={{ marginTop: 6 }}>
              WHERE YOU<br/>AT NOW?
            </DisplayHeading>
            <div style={{
              fontFamily: theme.fontBody, fontSize: 13, color: theme.muted,
              marginTop: 8, marginBottom: 18,
            }}>Honesty unlocks better matches.</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
              {EXPERIENCE.map(e => {
                const on = experience === e.id;
                return (
                  <button key={e.id} onClick={() => setExperience(e.id)} style={{
                    padding: 16, borderRadius: 14, textAlign: 'left',
                    border: on ? `2px solid ${theme.accent}` : `1px solid ${theme.border}`,
                    background: on ? `${theme.accent}15` : theme.surface,
                    cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 12,
                  }}>
                    <div style={{
                      width: 22, height: 22, borderRadius: 99,
                      background: on ? theme.accent : 'transparent',
                      border: on ? 'none' : `1.5px solid ${theme.faint}`,
                      display: 'flex', alignItems: 'center', justifyContent: 'center',
                      flexShrink: 0,
                    }}>
                      {on && <svg width="10" height="10" viewBox="0 0 14 14" fill="none">
                        <path d="M2 7l3.5 3.5L12 4" stroke={theme.onAccent} strokeWidth="2.6" strokeLinecap="round" strokeLinejoin="round"/>
                      </svg>}
                    </div>
                    <div>
                      <div style={{
                        fontFamily: theme.fontDisplay, fontSize: 18, color: theme.text,
                        letterSpacing: 0.2, lineHeight: 1, textTransform: 'uppercase',
                      }}>{e.l}</div>
                      <div style={{
                        fontFamily: theme.fontMono, fontSize: 10, color: theme.muted,
                        letterSpacing: 0.5, marginTop: 4, fontWeight: 600,
                      }}>{e.sub.toUpperCase()}</div>
                    </div>
                  </button>
                );
              })}
            </div>
          </>
        )}

        {cur === 'goal' && (
          <>
            <div style={{
              fontFamily: 'JetBrains Mono, monospace', fontSize: 11,
              color: theme.accent, letterSpacing: 2, fontWeight: 700,
            }}>★ YOUR MISSION</div>
            <DisplayHeading theme={theme} size={36} style={{ marginTop: 6 }}>
              WHAT'S YOUR<br/>NORTH STAR?
            </DisplayHeading>
            <div style={{
              fontFamily: theme.fontBody, fontSize: 13, color: theme.muted,
              marginTop: 8, marginBottom: 18,
            }}>Pick everything that matters to you right now.</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {GOALS.map(g => {
                const on = goals.includes(g.id);
                return (
                  <button key={g.id} onClick={() => toggleGoal(g.id)} style={{
                    padding: '14px 16px', borderRadius: 14, textAlign: 'left',
                    border: on ? `2px solid ${theme.accent}` : `1px solid ${theme.border}`,
                    background: on ? `${theme.accent}15` : theme.surface,
                    cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 12,
                  }}>
                    <div style={{
                      fontSize: 24, flexShrink: 0,
                    }}>{g.icon}</div>
                    <div style={{
                      flex: 1, fontFamily: theme.fontBody, fontSize: 15,
                      color: theme.text, fontWeight: 600,
                    }}>{g.l}</div>
                    {on && (
                      <div style={{
                        width: 22, height: 22, borderRadius: 99, background: theme.accent,
                        display: 'flex', alignItems: 'center', justifyContent: 'center',
                      }}>
                        <svg width="11" height="11" viewBox="0 0 14 14" fill="none">
                          <path d="M2 7l3.5 3.5L12 4" stroke={theme.onAccent} strokeWidth="2.6" strokeLinecap="round" strokeLinejoin="round"/>
                        </svg>
                      </div>
                    )}
                  </button>
                );
              })}
            </div>
          </>
        )}
      </div>

      {/* CTA */}
      <div style={{ padding: '12px 18px 30px' }}>
        <button
          onClick={advance}
          disabled={!canAdvance}
          style={{
            width: '100%',
            background: canAdvance ? theme.accent : theme.surface2,
            color: canAdvance ? theme.onAccent : theme.faint,
            border: 'none', borderRadius: 14,
            fontFamily: theme.fontDisplay, fontSize: 16, letterSpacing: 1,
            padding: '16px', cursor: canAdvance ? 'pointer' : 'not-allowed',
            textTransform: 'uppercase',
          }}>
          {step < steps.length - 1 ? 'NEXT →' : 'BUILD MY ROADMAP →'}
        </button>
      </div>
    </div>
  );
}

// ────────────────────────────────────────────────────────
// 4. REVEAL — "You're in" hype screen → enter app
// ────────────────────────────────────────────────────────
function RevealScreen({ theme, onEnter }) {
  return (
    <div style={{
      width: '100%', height: '100%', background: '#0A0A0A',
      position: 'relative', overflow: 'hidden',
      display: 'flex', flexDirection: 'column',
    }}>
      {/* dramatic bg */}
      <div style={{
        position: 'absolute', inset: 0,
        background: `radial-gradient(circle at 50% 30%, ${theme.accent}40 0%, transparent 50%)`,
      }} />
      {/* stars */}
      <svg width="100%" height="100%" viewBox="0 0 400 880" preserveAspectRatio="none"
        style={{ position: 'absolute', inset: 0, opacity: 0.6, pointerEvents: 'none' }}>
        {Array.from({ length: 60 }, (_, i) => {
          const x = (i * 47) % 400;
          const y = (i * 131) % 880;
          const r = (i % 5 === 0) ? 1.5 : 0.7;
          return <circle key={i} cx={x} cy={y} r={r} fill="#fff" opacity={(i % 4) * 0.2 + 0.4}/>;
        })}
      </svg>

      {/* Confetti-ish glyphs */}
      <svg width="100%" height="100%" viewBox="0 0 400 880" preserveAspectRatio="none"
        style={{ position: 'absolute', inset: 0, pointerEvents: 'none' }}>
        {[
          [60, 200, '#CAFF33'], [320, 180, '#FBBF24'], [80, 380, '#7A5AE0'],
          [310, 420, theme.accent], [40, 580, '#FBBF24'], [340, 600, '#CAFF33'],
        ].map(([x, y, c], i) => (
          <g key={i} transform={`translate(${x},${y}) rotate(${i * 47})`}>
            <path d={i % 2 === 0 ? "M0,-8 L2,-2 L8,0 L2,2 L0,8 L-2,2 L-8,0 L-2,-2 Z" : "M-6,-6 L6,6 M6,-6 L-6,6"}
              fill={i % 2 === 0 ? c : 'none'} stroke={c} strokeWidth="2" strokeLinecap="round"/>
          </g>
        ))}
      </svg>

      {/* Top */}
      <div style={{
        paddingTop: 90, padding: '90px 24px 0', position: 'relative',
        textAlign: 'center',
      }}>
        <div style={{
          fontFamily: 'JetBrains Mono, monospace', fontSize: 10,
          color: theme.accent, letterSpacing: 3, fontWeight: 700,
          animation: 'launchFadeIn 0.5s ease',
        }}>★ LIFTOFF CONFIRMED ★</div>
        <div style={{
          fontFamily: theme.fontDisplay, fontSize: 80, color: '#fff',
          letterSpacing: 0.5, lineHeight: 0.85,
          marginTop: 20, textTransform: 'uppercase',
          animation: 'launchScaleIn 0.6s 0.1s cubic-bezier(.2,.8,.2,1) both',
        }}>YOU'RE<br/><span style={{ color: theme.accent }}>IN.</span></div>
        <div style={{
          fontFamily: theme.fontBody, fontSize: 15, color: 'rgba(255,255,255,0.7)',
          marginTop: 18, lineHeight: 1.5,
          animation: 'launchFadeIn 0.6s 0.4s ease both',
        }}>
          Your roadmap is ready. Your squad is waiting.<br/>
          Day 1 starts now.
        </div>
      </div>

      {/* Stat strip */}
      <div style={{
        padding: '36px 24px 0', position: 'relative',
        animation: 'launchSlideUp 0.6s 0.5s ease both',
      }}>
        <div style={{
          display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8,
        }}>
          {[
            { n: '90', l: 'DAY\nPATH' },
            { n: '4', l: 'MENTORS\nMATCHED' },
            { n: '2K+', l: 'SQUAD\nMEMBERS' },
          ].map((s, i) => (
            <div key={i} style={{
              padding: 14, borderRadius: 14,
              background: 'rgba(255,255,255,0.06)', border: '1px solid rgba(255,255,255,0.12)',
              textAlign: 'center',
            }}>
              <div style={{
                fontFamily: theme.fontDisplay, fontSize: 30, color: '#fff',
                lineHeight: 1, letterSpacing: -0.5,
              }}>{s.n}</div>
              <div style={{
                fontFamily: 'JetBrains Mono, monospace', fontSize: 9, color: theme.accent,
                letterSpacing: 0.8, marginTop: 6, whiteSpace: 'pre-line',
                lineHeight: 1.3, fontWeight: 700,
              }}>{s.l}</div>
            </div>
          ))}
        </div>
      </div>

      {/* CTA */}
      <div style={{
        marginTop: 'auto', padding: '0 24px 40px', position: 'relative',
        animation: 'launchSlideUp 0.6s 0.7s ease both',
      }}>
        <button onClick={onEnter} style={{
          width: '100%', background: theme.accent, color: theme.onAccent,
          border: 'none', borderRadius: 14,
          fontFamily: theme.fontDisplay, fontSize: 18, letterSpacing: 1,
          padding: '18px', cursor: 'pointer', textTransform: 'uppercase',
          boxShadow: `0 12px 40px ${theme.accent}50`,
        }}>
          ENTER LAUNCH →
        </button>
      </div>
    </div>
  );
}

// ────────────────────────────────────────────────────────
// Welcome-back splash — for returning, already-signed-in users
// ────────────────────────────────────────────────────────
function WelcomeBackSplash({ theme, handle, onContinue }) {
  const user = (window.LAUNCH_USER && window.LAUNCH_USER.loadProfile()) || { streak: 0 };
  useEffectO(() => {
    const t = setTimeout(onContinue, 1800);
    return () => clearTimeout(t);
  }, [onContinue]);

  return (
    <div onClick={onContinue} style={{
      width: '100%', height: '100%', cursor: 'pointer',
      background: '#000', position: 'relative', overflow: 'hidden',
      display: 'flex', flexDirection: 'column',
      alignItems: 'center', justifyContent: 'center',
    }}>
      {/* stars */}
      <svg width="100%" height="100%" viewBox="0 0 400 880" preserveAspectRatio="none"
        style={{ position: 'absolute', inset: 0, opacity: 0.4, pointerEvents: 'none' }}>
        {Array.from({ length: 40 }, (_, i) => {
          const x = (i * 71) % 400;
          const y = (i * 137) % 880;
          const r = (i % 5 === 0) ? 1.2 : 0.5;
          return <circle key={i} cx={x} cy={y} r={r} fill="#fff" opacity={(i % 4) * 0.2 + 0.3}/>;
        })}
      </svg>

      {/* red bloom */}
      <div style={{
        position: 'absolute', width: 360, height: 360, borderRadius: '50%',
        left: '50%', top: '38%', transform: 'translate(-50%, -50%)',
        background: 'radial-gradient(circle, rgba(199,40,32,0.3) 0%, rgba(199,40,32,0) 60%)',
        filter: 'blur(6px)', animation: 'splashBloom 1.4s ease-out',
      }} />

      {/* Logo */}
      <div style={{
        position: 'relative', zIndex: 2,
        width: '70%', maxWidth: 280,
        animation: 'splashLogoIn 0.9s cubic-bezier(.16,.84,.28,1) both',
      }}>
        <img src="assets/launch-logo.png" alt="LAUNCH" style={{
          width: '100%', height: 'auto', display: 'block',
          filter: 'drop-shadow(0 12px 32px rgba(199,40,32,0.3))',
        }} />
      </div>

      {/* Welcome back */}
      <div style={{
        position: 'absolute', bottom: 120, left: 0, right: 0,
        textAlign: 'center', zIndex: 2,
        animation: 'splashTagIn 0.6s 0.4s ease both',
      }}>
        <div style={{
          fontFamily: 'JetBrains Mono, monospace', fontSize: 10,
          color: '#C72820', letterSpacing: 4, fontWeight: 700,
        }}>★ WELCOME BACK ★</div>
        <div style={{
          fontFamily: theme.fontDisplay, fontSize: 36, color: '#fff',
          letterSpacing: 0.5, marginTop: 14, textTransform: 'uppercase',
          lineHeight: 0.95,
        }}>
          @{handle}
        </div>
        <div style={{
          fontFamily: '"Space Grotesk", system-ui, sans-serif', fontSize: 13,
          color: 'rgba(255,255,255,0.5)', letterSpacing: 0.3,
          marginTop: 10, fontStyle: 'italic',
        }}>
          {user.streak > 1 ? `Day ${user.streak} of the streak. Let's go.` : "Let's get that streak started."}
        </div>
      </div>

      {/* Loader */}
      <div style={{
        position: 'absolute', bottom: 60, left: 0, right: 0,
        display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8,
      }}>
        <div style={{
          width: 100, height: 2, borderRadius: 99,
          background: 'rgba(255,255,255,0.08)', overflow: 'hidden', position: 'relative',
        }}>
          <div style={{
            position: 'absolute', top: 0, left: 0, height: '100%',
            background: '#C72820',
            animation: 'splashProgress 1.8s ease-out forwards',
          }} />
        </div>
        <div style={{
          fontFamily: 'JetBrains Mono, monospace', fontSize: 9,
          color: 'rgba(255,255,255,0.35)', letterSpacing: 3, fontWeight: 600,
        }}>SYNCING · TAP TO ENTER</div>
      </div>
    </div>
  );
}

// ────────────────────────────────────────────────────────
// Onboarding shell — orchestrates all 4 steps
// ────────────────────────────────────────────────────────
function OnboardingFlow({ theme, onDone }) {
  const U = window.LAUNCH_USER;
  // Returning user? Skip to a quick "welcome back" splash then app.
  const wasSignedIn = (() => {
    try { return localStorage.getItem('launch.signedIn') === '1'; } catch (e) { return false; }
  })();
  const savedHandle = (() => {
    try { return localStorage.getItem('launch.handle') || 'maya.sounds'; } catch (e) { return 'maya.sounds'; }
  })();

  const [phase, setPhase] = useStateO(wasSignedIn ? 'welcomeback' : 'splash');
  const [authMode, setAuthMode] = useStateO('signup');
  const [authData, setAuthData] = useStateO({ handle: '', name: '' });
  const [busy, setBusy] = useStateO(false);
  const [errorMsg, setErrorMsg] = useStateO('');
  const [noticeMsg, setNoticeMsg] = useStateO(''); // friendly (non-error) message, e.g. "check your email"

  // Normalize a typed name/handle into a clean handle.
  const cleanHandle = (h, n) => {
    let v = (h || '').trim().toLowerCase().replace(/^@/, '').replace(/\s+/g, '.');
    if (!v && n) v = n.trim().toLowerCase().replace(/\s+/g, '.');
    return v;
  };

  const finishAuth = async ({ keepSignedIn, handle, name, email, password }, isReturning) => {
    const h = cleanHandle(handle, name) || (email ? email.split('@')[0] : 'maya.sounds');
    setAuthData({ handle: h, name: (name || '').trim() });
    setErrorMsg('');
    setNoticeMsg('');

    try {
      if (keepSignedIn) {
        localStorage.setItem('launch.signedIn', '1');
        localStorage.setItem('launch.handle', h);
      } else {
        localStorage.removeItem('launch.signedIn');
      }
    } catch (e) {}

    // LIVE auth via Supabase
    if (U.isConfigured()) {
      if (isReturning && (!email || !password)) { setErrorMsg('Enter your email and password.'); return; }
      if (!isReturning && (!email || !password)) { setErrorMsg('Email and password are required.'); return; }
      setBusy(true);
      try {
        if (isReturning) {
          const { error } = await U.signIn({ email, password });
          if (error) { setErrorMsg(error.message || 'Could not sign in.'); setBusy(false); return; }
          setBusy(false);
          setPhase('reveal');
        } else {
          const { error, needsConfirmation } = await U.signUp({
            email, password, handle: h, displayName: (name || U.nameFromHandle(h)).trim(),
          });
          if (error) { setErrorMsg(error.message || 'Could not create account.'); setBusy(false); return; }
          setBusy(false);
          if (needsConfirmation) {
            setErrorMsg('');
            setNoticeMsg('We sent a confirmation link to your email. Click it, then sign in to continue.');
            setAuthMode('signin');
            return;
          }
          setPhase('setup');
        }
      } catch (e) {
        setBusy(false);
        setErrorMsg('Something went wrong. Check your Supabase keys in config.js.');
      }
      return;
    }

    // DEMO auth (no backend configured)
    if (isReturning) {
      U.saveProfile({ handle: h, ...(name ? { displayName: name.trim() } : {}), isNew: false });
      setPhase('reveal');
    } else {
      U.saveProfile({ handle: h, displayName: (name || U.nameFromHandle(h)).trim(), isNew: true });
      setPhase('setup');
    }
  };

  const doOAuth = async (provider) => {
    setErrorMsg('');
    setNoticeMsg('');
    if (U.isConfigured()) {
      setBusy(true);
      const { error } = await U.signInWithProvider(provider);
      if (error) { setErrorMsg(error.message || 'OAuth failed.'); setBusy(false); }
      // On success the browser redirects to the provider; nothing more to do.
      return;
    }
    // Demo: pretend OAuth succeeded → go through setup.
    try { localStorage.setItem('launch.signedIn', '1'); } catch (e) {}
    U.saveProfile({ handle: provider + '.artist', displayName: U.nameFromHandle(provider + '.artist'), isNew: true });
    setPhase('setup');
  };

  const finishSetup = ({ genre, experience, goal, genres, goals }) => {
    U.saveProfile({ genre, experience, goal, genres, goals });
    setPhase('reveal');
  };

  if (phase === 'welcomeback') {
    return <WelcomeBackSplash theme={theme} handle={savedHandle} onContinue={onDone} />;
  }
  if (phase === 'splash') {
    return <SplashScreen theme={theme} onContinue={() => setPhase('welcome')} />;
  }
  if (phase === 'welcome') {
    return <WelcomeCarousel theme={theme}
      onContinue={() => { setAuthMode('signup'); setPhase('auth'); }}
      onSignIn={() => { setAuthMode('signin'); setPhase('auth'); }} />;
  }
  if (phase === 'auth') {
    return <AuthScreen theme={theme} mode={authMode}
      onContinue={(data) => finishAuth(data, authMode === 'signin')}
      onOAuth={doOAuth}
      busy={busy}
      errorMsg={errorMsg}
      noticeMsg={noticeMsg}
      onBack={() => setPhase('welcome')}
      onSwitchMode={() => { setErrorMsg(''); setNoticeMsg(''); setAuthMode(authMode === 'signup' ? 'signin' : 'signup'); }} />;
  }
  if (phase === 'setup') {
    return <SetupScreen theme={theme}
      onContinue={finishSetup}
      onBack={() => setPhase('auth')} />;
  }
  return <RevealScreen theme={theme} onEnter={onDone} />;
}

window.LAUNCH_SCREENS_7 = { OnboardingFlow, SplashScreen, WelcomeBackSplash, WelcomeCarousel, AuthScreen, SetupScreen, RevealScreen };
