/* ============================================================
   NeuroRoute — Login / Signup + Onboarding wizard (public)
   ============================================================ */
const {useState:useStateA, useEffect:useEffectA} = React;

function AuthStyles(){
  return <style>{`
.auth{display:grid;grid-template-columns:1.05fr 1fr;min-height:100vh;background:var(--bg-0)}
.auth-brand{position:relative;overflow:hidden;padding:56px;display:flex;flex-direction:column;justify-content:space-between;border-right:1px solid var(--line)}
.auth-brand .aurora-bg{opacity:.6}
.auth-pts{display:flex;flex-direction:column;gap:18px;position:relative;z-index:2;max-width:420px}
.auth-pt{display:flex;gap:14px;align-items:flex-start}
.auth-pt .m-ico{width:40px;height:40px;border-radius:11px;display:grid;place-items:center;flex:none}
.auth-form-wrap{display:flex;align-items:center;justify-content:center;padding:40px}
.auth-card{width:100%;max-width:380px}
.auth-divider{display:flex;align-items:center;gap:14px;color:var(--tx-3);font-size:12px;margin:20px 0}
.auth-divider::before,.auth-divider::after{content:"";height:1px;flex:1;background:var(--line)}
.auth-google{display:flex;align-items:center;justify-content:center;gap:10px;width:100%;background:#fff;color:#1a1a1a;
  border:none;border-radius:var(--r-md);padding:12px;font-weight:600;font-size:14.5px;font-family:var(--font-ui);transition:.15s}
.auth-google:hover{background:#f0f0f0}
.af-foot{text-align:center;font-size:13px;color:var(--tx-2);margin-top:20px}
.af-foot a{color:var(--blue);cursor:pointer;font-weight:600}

/* onboarding */
.ob{min-height:100vh;background:var(--bg-0);display:flex;flex-direction:column}
.ob-top{display:flex;align-items:center;justify-content:space-between;padding:20px 32px;border-bottom:1px solid var(--line)}
.ob-prog{height:4px;background:var(--bg-3)}
.ob-prog>span{display:block;height:100%;background:var(--grad-route);transition:width .5s cubic-bezier(.2,.9,.3,1)}
.ob-body{flex:1;display:flex;align-items:flex-start;justify-content:center;padding:56px 24px;position:relative;overflow:hidden}
.ob-inner{width:100%;max-width:560px;position:relative;z-index:2}
.ob-steps{display:flex;gap:8px;margin-bottom:28px}
.ob-dot{flex:1;height:4px;border-radius:99px;background:var(--bg-3)}
.ob-dot.done{background:var(--green)}.ob-dot.cur{background:var(--blue)}
.plan-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:12px;margin-top:8px}
.plan-opt{border:1.5px solid var(--line-2);border-radius:var(--r-lg);padding:18px;cursor:pointer;transition:.15s;background:var(--bg-2);position:relative}
.plan-opt:hover{border-color:var(--line-strong)}
.plan-opt.sel{border-color:var(--blue);box-shadow:0 0 0 3px rgba(59,130,246,.2)}
.plan-opt.hot{border-color:rgba(226,79,214,.4)}
.confetti{position:absolute;inset:0;pointer-events:none;z-index:5;overflow:hidden}
.confetti i{position:absolute;width:9px;height:14px;border-radius:2px;animation:cfall linear forwards}
@keyframes cfall{0%{transform:translateY(-20px) rotate(0);opacity:1}100%{transform:translateY(105vh) rotate(720deg);opacity:.9}}
@media(max-width:860px){.auth{grid-template-columns:1fr}.auth-brand{display:none}.plan-grid{grid-template-columns:1fr}}
`}</style>;
}

/* ---------- Login ---------- */
function LoginPage(){
  const [mode,setMode]=useStateA('signin');
  const t=useToast();
  const pts=[
    {ic:'route',c:'cyan',t:'Intelligent routing',d:'Every request goes to the optimal model automatically.'},
    {ic:'dollar',c:'green',t:'60–80% lower bills',d:'Keep quality, cut cost. See the proof per request.'},
    {ic:'shield',c:'amber',t:'Enterprise-grade security',d:'Encrypted keys, RBAC and full audit logging.'},
  ];
  return (
    <div className="auth">
      <AuthStyles/>
      <div className="auth-brand">
        <div className="aurora-bg"><span/><span/></div>
        <div className="row" style={{gap:11,position:'relative',zIndex:2,cursor:'pointer'}} onClick={()=>go('landing')}>
          <LogoMark size={56}/><div><div className="display" style={{fontSize:22}}>NeuroRoute</div><div className="faint mono" style={{fontSize:11}}>by SISL CloudWorx</div></div>
        </div>
        <div style={{position:'relative',zIndex:2}}>
          <h1 className="display" style={{fontSize:32,lineHeight:1.15,marginBottom:8}}>Route smarter.<br/><span className="route-text">Spend less.</span></h1>
          <p className="muted" style={{fontSize:15,maxWidth:380,marginBottom:36}}>The AI gateway that picks the right model for every request — and proves the savings.</p>
          <div className="auth-pts">
            {pts.map(p=>(
              <div key={p.t} className="auth-pt">
                <div className="m-ico" style={{background:`var(--${p.c}-t)`,color:`var(--${p.c})`}}><Icon name={p.ic} size={20}/></div>
                <div><div style={{fontWeight:700,fontSize:14.5}}>{p.t}</div><div className="faint" style={{fontSize:13}}>{p.d}</div></div>
              </div>
            ))}
          </div>
        </div>
        <div className="faint" style={{fontSize:12,position:'relative',zIndex:2}}>SOC 2 Type II · 99.9% uptime · Trusted by AI-native teams</div>
      </div>

      <div className="auth-form-wrap">
        <div className="auth-card">
          <h2 className="display" style={{fontSize:24,marginBottom:6}}>{mode==='signin'?'Welcome back':'Create your account'}</h2>
          <p className="faint" style={{fontSize:14,marginBottom:24}}>{mode==='signin'?'Sign in to your NeuroRoute dashboard.':'Start optimizing your AI costs in minutes.'}</p>
          <button className="auth-google" onClick={()=>{window.location.href='/v1/auth/login/google';}}>
            <Icon name="google" size={18}/>{mode==='signin'?'Sign in with Google':'Sign up with Google'}
          </button>
          <div className="auth-divider">or with email</div>
          <form className="grid" style={{gap:14}} onSubmit={e=>{e.preventDefault();t({title:mode==='signin'?'Signed in':'Account created'});setTimeout(()=>go(mode==='signin'?'dashboard':'onboarding'),500);}}>
            {mode==='signup'&&<Field label="Full name"><input className="input" placeholder="Raman Iyer" required/></Field>}
            <Field label="Work email"><input className="input" type="email" placeholder="you@company.com" required/></Field>
            <Field label="Password"><input className="input" type="password" placeholder="••••••••" required/></Field>
            {mode==='signin'&&<div style={{textAlign:'right',marginTop:-4}}><a className="hint" style={{color:'var(--blue)',cursor:'pointer'}}>Forgot password?</a></div>}
            <button className="btn btn-primary btn-block btn-lg" type="submit">{mode==='signin'?'Sign in':'Create account'}<Icon name="arrowright" size={16}/></button>
          </form>
          <div className="af-foot">
            {mode==='signin'? <>Don't have an account? <a onClick={()=>setMode('signup')}>Create account</a></>
              : <>Already have an account? <a onClick={()=>setMode('signin')}>Sign in</a></>}
          </div>
        </div>
      </div>
    </div>
  );
}

/* ---------- Onboarding wizard ---------- */
function Confetti(){
  const cols=['#3b82f6','#22d3ee','#e24fd6','#f59e0b','#10b981','#8b5cf6'];
  const bits=Array.from({length:60},(_,i)=>({l:Math.random()*100,d:1.5+Math.random()*2,delay:Math.random()*0.6,c:cols[i%cols.length]}));
  return <div className="confetti">{bits.map((b,i)=><i key={i} style={{left:b.l+'%',background:b.c,animationDuration:b.d+'s',animationDelay:b.delay+'s'}}/>)}</div>;
}

function OnboardingPage(){
  const [step,setStep]=useStateA(1);
  const [plan,setPlan]=useStateA('Free');
  const [provider,setProvider]=useStateA('openai');
  const [key,setKey]=useStateA('');
  const [validated,setValidated]=useStateA(false);
  const [validating,setValidating]=useStateA(false);
  const [sent,setSent]=useStateA(false);
  const t=useToast();
  const plans=[{id:'Free',price:'$0',d:'1K req/mo'},{id:'Pro',price:'$49',d:'50K req/mo',hot:true},{id:'Enterprise',price:'Custom',d:'Unlimited'}];

  return (
    <div className="ob">
      <AuthStyles/>
      <div className="ob-top">
        <div className="row" style={{gap:12,cursor:'pointer'}} onClick={()=>go('landing')}><LogoMark size={44}/><span className="display" style={{fontSize:19}}>NeuroRoute</span></div>
        <a className="hint" style={{cursor:'pointer'}} onClick={()=>go('dashboard')}>Skip setup →</a>
      </div>
      <div className="ob-prog"><span style={{width:(step/3*100)+'%'}}/></div>
      <div className="ob-body">
        {step===4 && <Confetti/>}
        <div className="ob-inner">
          <div className="ob-steps">{[1,2,3].map(n=><div key={n} className={'ob-dot'+(n<step?' done':n===step?' cur':'')}/>)}</div>

          {step===1 && <div>
            <div className="eyebrow" style={{marginBottom:8}}>STEP 1 OF 3</div>
            <h2 className="display" style={{fontSize:28,marginBottom:6}}>Welcome to NeuroRoute 👋</h2>
            <p className="faint" style={{marginBottom:24}}>Choose a plan to get started. You can change this anytime.</p>
            <div className="plan-grid">
              {plans.map(p=>(
                <div key={p.id} className={'plan-opt'+(plan===p.id?' sel':'')+(p.hot?' hot':'')} onClick={()=>setPlan(p.id)}>
                  {p.hot&&<span className="badge b-magenta" style={{position:'absolute',top:12,right:12,fontSize:9.5,padding:'1px 7px'}}>POPULAR</span>}
                  <div className="display" style={{fontSize:16}}>{p.id}</div>
                  <div className="display tnum" style={{fontSize:26,margin:'8px 0 2px'}}>{p.price}</div>
                  <div className="faint" style={{fontSize:12.5}}>{p.d}</div>
                </div>
              ))}
            </div>
            <button className="btn btn-grad btn-block btn-lg" style={{marginTop:24}} onClick={()=>setStep(2)}>Continue<Icon name="arrowright" size={16}/></button>
          </div>}

          {step===2 && <div>
            <div className="eyebrow" style={{marginBottom:8}}>STEP 2 OF 3</div>
            <h2 className="display" style={{fontSize:28,marginBottom:6}}>Add your first provider key</h2>
            <p className="faint" style={{marginBottom:24}}>Bring your own key — it's encrypted with AES-256-GCM and never leaves our vault in plaintext.</p>
            <div className="grid" style={{gap:16}}>
              <Field label="Provider"><select className="select" value={provider} onChange={e=>{setProvider(e.target.value);setValidated(false);}}>
                {DATA.PROVIDERS.map(p=><option key={p.id} value={p.id}>{p.name}</option>)}</select></Field>
              <Field label="API key" hint="We validate the key with a $0.00 test call before saving.">
                <input className="input input-mono" placeholder="sk-..." value={key} onChange={e=>{setKey(e.target.value);setValidated(false);}}/>
              </Field>
              <div className="row" style={{gap:10}}>
                <button className="btn btn-soft" disabled={!key||validating} onClick={()=>{setValidating(true);setTimeout(()=>{setValidating(false);setValidated(true);t({title:'Key validated',msg:DATA.providerById(provider).name+' key is active.'});},1100);}}>
                  {validating?<><span className="skel" style={{width:14,height:14,borderRadius:99}}/>Validating…</>:validated?<><Icon name="checkcircle" size={15} style={{color:'var(--green)'}}/>Validated</>:<><Icon name="check" size={15}/>Validate key</>}
                </button>
                {validated&&<Badge color="green" dot>Active</Badge>}
              </div>
            </div>
            <div className="row" style={{marginTop:28,gap:10}}>
              <button className="btn btn-ghost" onClick={()=>setStep(1)}>Back</button>
              <button className="btn btn-grad" style={{flex:1}} onClick={()=>setStep(3)}>Continue<Icon name="arrowright" size={16}/></button>
            </div>
          </div>}

          {step===3 && <div>
            <div className="eyebrow" style={{marginBottom:8}}>STEP 3 OF 3</div>
            <h2 className="display" style={{fontSize:28,marginBottom:6}}>Make your first request</h2>
            <p className="faint" style={{marginBottom:20}}>Point your client at NeuroRoute. Same OpenAI SDK — just a new base URL.</p>
            <div className="codeblock" style={{fontSize:12.5}}>
              <div><span className="tok-key">curl</span> https://api.neuroroute.ai/v1/chat/completions \</div>
              <div>  -H <span className="tok-str">"Authorization: Bearer nr_live_••••4f8a"</span> \</div>
              <div>  -d <span className="tok-str">{'\'{"model":"auto","messages":[...]}\''}</span></div>
            </div>
            <button className="btn btn-soft btn-block" style={{marginTop:14}} disabled={sent} onClick={()=>{setSent(true);t({title:'Request routed!',msg:'Routed to Gemini 2.5 Flash · saved 71%.'});}}>
              {sent?<><Icon name="checkcircle" size={16} style={{color:'var(--green)'}}/>Routed successfully</>:<><Icon name="zap" size={16}/>Try it now</>}
            </button>
            {sent&&<div className="card card-pad" style={{marginTop:14,display:'grid',gridTemplateColumns:'repeat(3,1fr)',gap:12,textAlign:'center'}}>
              <div><div className="faint" style={{fontSize:11.5}}>Routed to</div><div style={{fontWeight:700,marginTop:3}}>Gemini 2.5 Flash</div></div>
              <div><div className="faint" style={{fontSize:11.5}}>Cost</div><div className="mono" style={{marginTop:3}}>$0.0008</div></div>
              <div><div className="faint" style={{fontSize:11.5}}>Saved</div><div className="route-text" style={{fontWeight:700,marginTop:3}}>71%</div></div>
            </div>}
            <div className="row" style={{marginTop:28,gap:10}}>
              <button className="btn btn-ghost" onClick={()=>setStep(2)}>Back</button>
              <button className="btn btn-grad" style={{flex:1}} onClick={()=>{setStep(4);setTimeout(()=>go('dashboard'),2600);}}>Finish setup<Icon name="check" size={16}/></button>
            </div>
          </div>}

          {step===4 && <div style={{textAlign:'center',paddingTop:30}}>
            <div className="m-ico" style={{background:'var(--green-t)',color:'var(--green)',width:72,height:72,borderRadius:20,margin:'0 auto 20px'}}><Icon name="checkcircle" size={36}/></div>
            <h2 className="display" style={{fontSize:30,marginBottom:8}}>You're all set!</h2>
            <p className="muted">Taking you to your dashboard…</p>
          </div>}
        </div>
      </div>
    </div>
  );
}

window.PAGES = Object.assign(window.PAGES||{}, {login:LoginPage, onboarding:OnboardingPage});
