// ============ Onboarding wizard (post-signup) ============
const OnboardingWizard = ({ setRoute }) => {
  const { t, lang, setLang } = useI18n();
  const { user } = useAuth();
  const { addAccount, setActive } = useAccounts();

  const firstName = (user?.name || '').split(/\s+/)[0] || 'trader';

  const [step, setStep] = useState(1);
  const [name, setName] = useState('');
  const [broker, setBroker] = useState('IBKR');
  const [type, setType] = useState('personal');
  const [startingCapital, setStartingCapital] = useState(25000);
  const [color, setColor] = useState('#10b981');
  const [maxDailyLoss, setMaxDailyLoss] = useState(5);
  const [maxTotalLoss, setMaxTotalLoss] = useState(10);
  const [profitTarget, setProfitTarget] = useState(10);
  const [deadline, setDeadline] = useState('2026-06-15');
  const [toast, setToast] = useState(false);

  const colors = ['#10b981','#3b82f6','#f59e0b','#ef4444','#8b5cf6','#ec4899','#06b6d4','#6b6b6b'];
  const isProp = type === 'prop_challenge' || type === 'prop_funded';
  const totalSteps = isProp ? 3 : 2;
  const lastStep = isProp ? 3 : 2;

  const canContinueStep2 = name.trim().length > 0 && Number(startingCapital) > 0;

  const finish = () => {
    const acct = {
      name: name.trim(),
      broker,
      type,
      currency: 'USD',
      assetClass: 'Equities',
      startingCapital: Number(startingCapital),
      color,
      notes: '',
      rules: isProp ? {
        maxDailyLoss: Number(maxDailyLoss),
        maxTotalLoss: Number(maxTotalLoss),
        profitTarget: type==='prop_funded' ? 0 : Number(profitTarget),
        deadline: type==='prop_funded' ? null : deadline,
      } : null,
    };
    addAccount(acct);
    setActive('all');
    try { localStorage.setItem('edgebook:onboarded', 'true'); } catch {}
    setToast(true);
    setTimeout(() => { setRoute('dashboard'); }, 900);
  };

  const skip = () => {
    try { localStorage.setItem('edgebook:onboarded', 'true'); } catch {}
    setRoute('dashboard');
  };

  const next = () => {
    if (step === 1) setStep(2);
    else if (step === 2) { if (isProp) setStep(3); else finish(); }
    else finish();
  };

  const dots = [];
  for (let i=1; i<=totalSteps; i++){
    dots.push(<span key={i} className={'ob-dot ' + (i===step?'active':i<step?'done':'')}/>);
  }

  return (
    <div className="auth-wrap" style={{gridTemplateColumns:'1fr'}}>
      <div className="auth-right" style={{minHeight:'100vh'}}>
        <div className="auth-topbar">
          <div className="lang-pill">
            <button className={lang==='en'?'on':''} onClick={()=>setLang('en')}>EN</button>
            <button className={lang==='mn'?'on':''} onClick={()=>setLang('mn')}>MN</button>
          </div>
        </div>
        <div className="auth-card" style={{maxWidth:540}}>
          <div style={{display:'flex',alignItems:'center',gap:10,marginBottom:8}}>
            {dots}
          </div>
          <div className="muted tiny" style={{marginBottom:22,fontFamily:'JetBrains Mono',letterSpacing:'0.04em'}}>
            {t('ob_step_n_of_m', { n: step, m: totalSteps })}
          </div>

          {step === 1 && (
            <div>
              <h1 style={{fontSize:26,fontWeight:600,letterSpacing:'-0.02em',marginBottom:8}}>
                {t('ob_welcome_title', { name: firstName })}
              </h1>
              <div className="muted" style={{fontSize:14,marginBottom:26,textWrap:'pretty'}}>{t('ob_welcome_sub')}</div>
              <div style={{display:'flex',flexDirection:'column',gap:14,marginBottom:28}}>
                {[t('ob_f1'), t('ob_f2'), t('ob_f3')].map((f,i)=>(
                  <div key={i} style={{display:'flex',alignItems:'flex-start',gap:12}}>
                    <div style={{width:22,height:22,borderRadius:'50%',background:'rgba(16,185,129,.15)',color:'#10b981',display:'grid',placeItems:'center',flexShrink:0,marginTop:1}}>
                      <Icon name="check" size={13}/>
                    </div>
                    <div style={{fontSize:14}}>{f}</div>
                  </div>
                ))}
              </div>
            </div>
          )}

          {step === 2 && (
            <div>
              <h1 style={{fontSize:24,fontWeight:600,letterSpacing:'-0.02em',marginBottom:8}}>{t('ob_basics_title')}</h1>
              <div className="muted" style={{fontSize:13.5,marginBottom:22}}>{t('ob_basics_sub')}</div>

              <div style={{display:'flex',flexDirection:'column',gap:14,marginBottom:22}}>
                <div>
                  <label className="label">{t('new_account')} {t('th_name')}</label>
                  <input className="input" value={name} onChange={e=>setName(e.target.value)} placeholder="My IBKR" style={{width:'100%'}} autoFocus/>
                </div>
                <div className="g-2">
                  <div>
                    <label className="label">{t('th_broker')}</label>
                    <select className="select" value={broker} onChange={e=>setBroker(e.target.value)} style={{width:'100%'}}>
                      {['IBKR','Schwab','Tradovate','MT4','MT5','Binance','Coinbase','TradingView'].map(b=><option key={b}>{b}</option>)}
                    </select>
                  </div>
                  <div>
                    <label className="label">{t('th_type')}</label>
                    <select className="select" value={type} onChange={e=>setType(e.target.value)} style={{width:'100%'}}>
                      <option value="personal">{accountTypeLabel('personal')}</option>
                      <option value="prop_challenge">{accountTypeLabel('prop_challenge')}</option>
                      <option value="prop_funded">{accountTypeLabel('prop_funded')}</option>
                      <option value="demo">{accountTypeLabel('demo')}</option>
                      <option value="paper">{accountTypeLabel('paper')}</option>
                    </select>
                  </div>
                </div>
                <div>
                  <label className="label">{t('th_starting')} (USD)</label>
                  <input className="input mono" type="number" value={startingCapital} onChange={e=>setStartingCapital(e.target.value)} style={{width:'100%'}}/>
                </div>
                <div>
                  <label className="label">{t('ob_color')}</label>
                  <div style={{display:'flex',gap:10}}>
                    {colors.map(c => (
                      <div key={c} onClick={()=>setColor(c)} style={{
                        width:28,height:28,borderRadius:'50%',background:c,cursor:'pointer',
                        border: color===c ? '2px solid #fff' : '2px solid transparent',
                        boxShadow: color===c ? '0 0 0 2px '+c : 'none',
                      }}/>
                    ))}
                  </div>
                </div>
              </div>
            </div>
          )}

          {step === 3 && (
            <div>
              <h1 style={{fontSize:24,fontWeight:600,letterSpacing:'-0.02em',marginBottom:8}}>{t('ob_rules_title')}</h1>
              <div className="muted" style={{fontSize:13.5,marginBottom:22,textWrap:'pretty'}}>{t('ob_rules_sub')}</div>

              <div className="g-2" style={{marginBottom:14}}>
                <div><label className="label">{t('max_daily_loss')} (%)</label><input className="input mono" type="number" value={maxDailyLoss} onChange={e=>setMaxDailyLoss(e.target.value)} style={{width:'100%'}}/></div>
                <div><label className="label">{t('total_loss_used')} (%)</label><input className="input mono" type="number" value={maxTotalLoss} onChange={e=>setMaxTotalLoss(e.target.value)} style={{width:'100%'}}/></div>
                {type==='prop_challenge' && <div><label className="label">{t('profit_target_progress')} (%)</label><input className="input mono" type="number" value={profitTarget} onChange={e=>setProfitTarget(e.target.value)} style={{width:'100%'}}/></div>}
                {type==='prop_challenge' && <div><label className="label">{t('ob_deadline')}</label><input className="input mono" type="date" value={deadline} onChange={e=>setDeadline(e.target.value)} style={{width:'100%'}}/></div>}
              </div>
            </div>
          )}

          <div style={{display:'flex',gap:8,marginTop:8}}>
            {step > 1 && <button className="btn" onClick={()=>setStep(step-1)} style={{height:38}}>{t('ob_back')}</button>}
            <button
              className="btn btn-primary"
              style={{flex:1,height:38,justifyContent:'center'}}
              disabled={step===2 && !canContinueStep2}
              onClick={next}
            >
              {step === lastStep ? t('ob_finish') : t('ob_continue')}
            </button>
          </div>

          <div style={{textAlign:'center',marginTop:18}}>
            <span className="muted tiny" onClick={skip} style={{cursor:'pointer'}}>{t('ob_skip')}</span>
          </div>
        </div>
      </div>

      {toast && (
        <div style={{
          position:'fixed',bottom:24,left:'50%',transform:'translateX(-50%)',
          background:'#10b981',color:'#042f1c',padding:'10px 18px',borderRadius:8,
          fontSize:13,fontWeight:500,boxShadow:'0 10px 40px rgba(0,0,0,.5)',zIndex:1000,
          display:'flex',alignItems:'center',gap:8,
        }}>
          <Icon name="check" size={14}/> {t('ob_toast')}
        </div>
      )}
    </div>
  );
};

window.OnboardingWizard = OnboardingWizard;
