// Onboarding / sign-in screen — real auth
function Onboarding({ onAuth, onGuest }) {
  const S = window.SOL;
  const API = 'https://api.solunce.com';
  const [mode, setMode]   = React.useState('signin'); // 'signin' | 'register' | 'verify'
  const [email, setEmail] = React.useState('');
  const [pass, setPass]   = React.useState('');
  const [loading, setLoading] = React.useState(false);
  const [error, setError]     = React.useState('');

  const SolunceLogo = ({ size = 26 }) => (
    <svg width={size} height={size} viewBox="0 0 32 32" style={{ display:'block', flexShrink:0 }}>
      <circle cx="16" cy="16" r="14" fill={S.ink}/>
      <circle cx="16" cy="16" r="12" fill="none" stroke={S.cream} strokeOpacity="0.95" strokeWidth="0.6"/>
      {[0,1,2,3].map(i => {
        const a=(i/4)*Math.PI;
        return <line key={i} x1={16+Math.cos(a)*11.6} y1={16+Math.sin(a)*11.6} x2={16-Math.cos(a)*11.6} y2={16-Math.sin(a)*11.6} stroke={S.cream} strokeOpacity="0.95" strokeWidth="0.6" strokeLinecap="round"/>;
      })}
    </svg>
  );

  const submit = async (e) => {
    e.preventDefault();
    if (!email.trim() || !pass.trim()) { setError('Please enter your email and password.'); return; }
    setLoading(true); setError('');
    try {
      const r = await fetch(`${API}${mode === 'signin' ? '/api/auth/login' : '/api/auth/register'}`, {
        method:'POST', headers:{'Content-Type':'application/json'},
        body: JSON.stringify({ email: email.trim().toLowerCase(), password: pass }),
      });
      const data = await r.json();
      if (!r.ok) {
        setError(data.code === 'email_not_verified'
          ? 'Verify your email first — check your inbox.'
          : (data.error || 'Something went wrong.'));
        setLoading(false); return;
      }
      if (mode === 'register') { setMode('verify'); setLoading(false); return; }
      onAuth(data.token, data.user);
    } catch { setError('Connection failed. Check your internet.'); setLoading(false); }
  };

  if (mode === 'verify') {
    return (
      <div style={{ height:'100%', background:S.cream, display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center', padding:'40px 32px', textAlign:'center', position:'relative', zIndex:2 }}>
        <div style={{ width:56, height:56, borderRadius:'50%', background:`radial-gradient(circle at 35% 35%, ${S.sun}, ${S.amber})`, marginBottom:24 }}/>
        <div style={{ fontFamily:S.serif, fontSize:32, letterSpacing:-0.8, color:S.ink, marginBottom:12 }}>Check your inbox</div>
        <div style={{ fontFamily:S.sans, fontSize:14, color:S.ink2, lineHeight:1.55, maxWidth:280 }}>
          We sent a link to <strong>{email}</strong>. Click it then come back and sign in.
        </div>
        <button onClick={() => setMode('signin')} style={{ marginTop:32, height:50, borderRadius:14, border:'none', background:S.ink, color:S.cream, fontFamily:S.sans, fontSize:15, fontWeight:500, padding:'0 28px', cursor:'pointer' }}>
          Back to sign in
        </button>
      </div>
    );
  }

  const inp = { width:'100%', height:52, borderRadius:14, border:`1.5px solid ${S.line2}`, background:S.paper, fontFamily:S.sans, fontSize:16, color:S.ink, padding:'0 16px', outline:'none', letterSpacing:-0.1, WebkitAppearance:'none' };

  return (
    <div style={{ height:'100%', background:S.cream, display:'flex', flexDirection:'column', position:'relative', overflow:'hidden' }}>
      <div style={{ position:'absolute', top:-120, right:-120, width:360, height:360, borderRadius:'50%', background:'radial-gradient(circle, rgba(244,199,123,0.5) 0%, rgba(244,199,123,0) 70%)', pointerEvents:'none' }}/>
      <div style={{ position:'absolute', bottom:-140, left:-100, width:320, height:320, borderRadius:'50%', background:'radial-gradient(circle, rgba(232,155,60,0.2) 0%, rgba(232,155,60,0) 70%)', pointerEvents:'none' }}/>

      <div style={{ height:'env(safe-area-inset-top, 44px)', minHeight:44 }}/>

      <div style={{ flex:1, padding:'32px 28px 20px', display:'flex', flexDirection:'column', justifyContent:'space-between', position:'relative', zIndex:2, overflowY:'auto' }}>
        <div>
          <div style={{ display:'flex', alignItems:'center', gap:10, marginBottom:44 }}>
            <SolunceLogo size={26}/>
            <span style={{ fontFamily:S.sans, fontSize:14, fontWeight:500, letterSpacing:0.6, textTransform:'uppercase', color:S.ink }}>Solunce</span>
          </div>
          <div style={{ fontFamily:S.serif, fontSize:46, lineHeight:0.98, letterSpacing:-1.5, color:S.ink, marginBottom:14 }}>
            A calmer way<br/><span style={{ fontStyle:'italic', color:S.amberDeep }}>to think</span> with AI.
          </div>
          <div style={{ fontFamily:S.sans, fontSize:14.5, lineHeight:1.5, color:S.ink2, maxWidth:290 }}>
            Two models. Solus for everyday. Apollo — intelligence, unbounded.
          </div>
        </div>

        <div style={{ display:'flex', gap:10, margin:'24px 0' }}>
          {[{v:'solus',n:'Solus X5',t:'Free'},{v:'apollo',n:'Apollo 1',t:'Plus'}].map(({v,n,t}) => {
            const ap=v==='apollo';
            return (
              <div key={v} style={{ flex:1, background:ap?S.ink:S.paper, border:ap?'none':`1px solid ${S.line2}`, borderRadius:18, padding:'14px 14px 16px', position:'relative', overflow:'hidden' }}>
                {ap&&<div style={{ position:'absolute', top:-40, right:-40, width:120, height:120, borderRadius:'50%', background:'radial-gradient(circle, rgba(232,155,60,0.35) 0%, rgba(232,155,60,0) 70%)' }}/>}
                <div style={{ display:'flex', alignItems:'center', gap:8, position:'relative' }}>
                  <SunMark size={22} variant={v}/>
                  <div style={{ fontFamily:S.sans, fontSize:13, fontWeight:500, color:ap?S.cream:S.ink }}>{n}</div>
                </div>
                <div style={{ marginTop:20, fontFamily:S.mono, fontSize:10, letterSpacing:0.8, textTransform:'uppercase', opacity:0.5, color:ap?S.cream:S.ink }}>{t}</div>
              </div>
            );
          })}
        </div>

        <form onSubmit={submit} style={{ display:'flex', flexDirection:'column', gap:10 }}>
          <div style={{ display:'flex', borderRadius:14, border:`1.5px solid ${S.line2}`, background:S.paper, overflow:'hidden' }}>
            {['signin','register'].map(m => (
              <button key={m} type="button" onClick={() => { setMode(m); setError(''); }} style={{
                flex:1, height:44, border:'none', borderRight:m==='signin'?`1px solid ${S.line2}`:'none',
                background:mode===m?S.ink:'transparent', color:mode===m?S.cream:S.ink2,
                fontFamily:S.sans, fontSize:14, fontWeight:500, cursor:'pointer',
              }}>{m==='signin'?'Sign in':'Create account'}</button>
            ))}
          </div>

          <input type="email" placeholder="Email" value={email} onChange={e=>setEmail(e.target.value)} autoComplete="email" style={inp}/>
          <input type="password" placeholder="Password" value={pass} onChange={e=>setPass(e.target.value)} autoComplete={mode==='signin'?'current-password':'new-password'} style={inp}/>

          {error && <div style={{ fontFamily:S.sans, fontSize:13, color:S.ember, padding:'8px 12px', background:'rgba(184,74,31,0.08)', borderRadius:10 }}>{error}</div>}

          <button type="submit" disabled={loading} style={{
            height:54, border:'none', borderRadius:16, background:loading?S.ink2:S.ink,
            color:S.cream, fontFamily:S.sans, fontSize:16, fontWeight:500,
            cursor:loading?'default':'pointer', letterSpacing:-0.2,
            display:'flex', alignItems:'center', justifyContent:'center', gap:10,
          }}>
            {loading
              ? <div style={{ width:20, height:20, borderRadius:'50%', border:`2px solid rgba(245,239,228,.3)`, borderTopColor:S.cream, animation:'sol-spin 0.7s linear infinite' }}/>
              : (mode==='signin'?'Sign in':'Create account')}
          </button>

          <button type="button" onClick={onGuest} style={{
            height:46, border:`1px solid ${S.line2}`, borderRadius:14, background:'transparent',
            color:S.ink2, fontFamily:S.sans, fontSize:14, cursor:'pointer',
          }}>Continue as guest</button>

          <div style={{ textAlign:'center', fontFamily:S.sans, fontSize:11.5, color:S.ink3, lineHeight:1.5 }}>
            By continuing you agree to our{' '}
            <a href="/tos" style={{ color:S.amberDeep, textDecoration:'none' }}>Terms</a> &amp; <a href="/privacy" style={{ color:S.amberDeep, textDecoration:'none' }}>Privacy</a>.
          </div>
        </form>
      </div>

      <div style={{ height:'env(safe-area-inset-bottom, 20px)', minHeight:20 }}/>
    </div>
  );
}

window.Onboarding = Onboarding;
