// ============ Auth screens ============

const AuthShell = ({ title, sub, children, footer }) => {
  const { t, lang, setLang } = useI18n();
  return (
    <div className="auth-wrap">
      <div className="auth-left">
        <div className="auth-brand">
          <div className="nav-logo-mark">E</div>
          <div style={{fontWeight:600,fontSize:15,letterSpacing:'-0.01em'}}>Edgebook</div>
        </div>
        <div style={{flex:1}}/>
        <div className="auth-quote">
          <div className="mono tiny muted" style={{letterSpacing:'0.08em',textTransform:'uppercase',marginBottom:12}}>{t('auth_tagline_label')}</div>
          <div style={{fontSize:26,fontWeight:600,lineHeight:1.25,letterSpacing:'-0.02em',textWrap:'pretty',maxWidth:440}}>
            {t('auth_tagline')}
          </div>
          <div className="muted" style={{marginTop:14,fontSize:13.5,maxWidth:420}}>{t('auth_tagline_sub')}</div>
        </div>
        <div className="auth-stats">
          <div><div className="mono" style={{fontSize:18,fontWeight:600}}>12,847</div><div className="tiny muted">{t('auth_traders')}</div></div>
          <div style={{width:1,background:'var(--border)'}}/>
          <div><div className="mono" style={{fontSize:18,fontWeight:600}}>3.2M</div><div className="tiny muted">{t('auth_trades_logged')}</div></div>
          <div style={{width:1,background:'var(--border)'}}/>
          <div><div className="mono" style={{fontSize:18,fontWeight:600}}>4.8★</div><div className="tiny muted">{t('auth_rating')}</div></div>
        </div>
      </div>
      <div className="auth-right">
        <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">
          <div style={{marginBottom:22}}>
            <div style={{fontSize:22,fontWeight:600,letterSpacing:'-0.015em',marginBottom:6}}>{title}</div>
            {sub && <div className="muted" style={{fontSize:13.5}}>{sub}</div>}
          </div>
          {children}
          {footer && <div className="auth-foot">{footer}</div>}
        </div>
      </div>
    </div>
  );
};

const Field = ({ label, children, hint, error }) => (
  <div style={{marginBottom:14}}>
    <label className="label">{label}</label>
    {children}
    {hint && !error && <div className="tiny muted" style={{marginTop:6}}>{hint}</div>}
    {error && <div className="tiny" style={{marginTop:6,color:'#ef4444'}}>{error}</div>}
  </div>
);

// ---- Login ----
const LoginPage = () => {
  const { t } = useI18n();
  const { signIn, setAuthRoute } = useAuth();
  const [email, setEmail] = useState('sam@edgebook.app');
  const [password, setPassword] = useState('');
  const [remember, setRemember] = useState(true);
  const [showPw, setShowPw] = useState(false);
  const [err, setErr] = useState('');

  const submit = (e) => {
    e.preventDefault();
    const r = signIn(email, password);
    if (r.error) setErr(t('err_invalid_credentials'));
  };

  return (
    <AuthShell
      title={t('login_title')}
      sub={t('login_sub')}
      footer={<>
        <span className="muted">{t('no_account')} </span>
        <a onClick={()=>setAuthRoute('signup')} className="auth-link">{t('sign_up')}</a>
      </>}
    >
      <button className="btn auth-sso" type="button">
        <svg width="15" height="15" viewBox="0 0 24 24"><path fill="#4285F4" d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"/><path fill="#34A853" d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"/><path fill="#FBBC05" d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z"/><path fill="#EA4335" d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z"/></svg>
        {t('continue_google')}
      </button>
      <div className="auth-or"><span>{t('or')}</span></div>
      <form onSubmit={submit}>
        <Field label={t('email')}>
          <input className="input" type="email" value={email} onChange={e=>{setEmail(e.target.value);setErr('')}} style={{width:'100%'}} autoComplete="email"/>
        </Field>
        <Field label={<div style={{display:'flex',justifyContent:'space-between'}}><span>{t('password')}</span><a onClick={()=>setAuthRoute('forgot')} className="auth-link tiny">{t('forgot_password')}</a></div>} error={err}>
          <div style={{position:'relative'}}>
            <input className="input" type={showPw?'text':'password'} value={password} onChange={e=>{setPassword(e.target.value);setErr('')}} style={{width:'100%',paddingRight:36}} autoComplete="current-password"/>
            <button type="button" onClick={()=>setShowPw(v=>!v)} className="pw-toggle"><Icon name={showPw?'eye-off':'eye'} size={14}/></button>
          </div>
        </Field>
        <label className="auth-check">
          <input type="checkbox" checked={remember} onChange={e=>setRemember(e.target.checked)}/>
          <span>{t('remember_me')}</span>
        </label>
        <button className="btn btn-primary" type="submit" style={{width:'100%',marginTop:18,height:38,justifyContent:'center'}}>{t('sign_in')}</button>
      </form>
    </AuthShell>
  );
};

// ---- Sign up ----
const SignupPage = () => {
  const { t } = useI18n();
  const { signUp, setAuthRoute } = useAuth();
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [accept, setAccept] = useState(false);
  const [showPw, setShowPw] = useState(false);
  const [err, setErr] = useState({});

  // Password strength
  const strength = (() => {
    let s = 0;
    if (password.length >= 8) s++;
    if (/[A-Z]/.test(password)) s++;
    if (/[0-9]/.test(password)) s++;
    if (/[^A-Za-z0-9]/.test(password)) s++;
    return s;
  })();
  const strengthLabel = ['', t('pw_weak'), t('pw_fair'), t('pw_good'), t('pw_strong')][strength];
  const strengthColor = ['#333','#ef4444','#f59e0b','#3b82f6','#10b981'][strength];

  const submit = (e) => {
    e.preventDefault();
    const er = {};
    if (!name.trim()) er.name = t('err_required');
    if (!email.trim() || !email.includes('@')) er.email = t('err_invalid_email');
    if (password.length < 8) er.password = t('err_pw_too_short');
    if (!accept) er.accept = t('err_accept_terms');
    setErr(er);
    if (Object.keys(er).length) return;
    signUp(name, email, password);
  };

  return (
    <AuthShell
      title={t('signup_title')}
      sub={t('signup_sub')}
      footer={<>
        <span className="muted">{t('have_account')} </span>
        <a onClick={()=>setAuthRoute('login')} className="auth-link">{t('sign_in')}</a>
      </>}
    >
      <button className="btn auth-sso" type="button">
        <svg width="15" height="15" viewBox="0 0 24 24"><path fill="#4285F4" d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"/><path fill="#34A853" d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"/><path fill="#FBBC05" d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z"/><path fill="#EA4335" d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z"/></svg>
        {t('signup_google')}
      </button>
      <div className="auth-or"><span>{t('or')}</span></div>
      <form onSubmit={submit}>
        <Field label={t('full_name')} error={err.name}>
          <input className="input" value={name} onChange={e=>setName(e.target.value)} placeholder={t('full_name_placeholder')} style={{width:'100%'}} autoComplete="name"/>
        </Field>
        <Field label={t('email')} error={err.email}>
          <input className="input" type="email" value={email} onChange={e=>setEmail(e.target.value)} placeholder="you@example.com" style={{width:'100%'}} autoComplete="email"/>
        </Field>
        <Field label={t('password')} error={err.password}>
          <div style={{position:'relative'}}>
            <input className="input" type={showPw?'text':'password'} value={password} onChange={e=>setPassword(e.target.value)} style={{width:'100%',paddingRight:36}} autoComplete="new-password"/>
            <button type="button" onClick={()=>setShowPw(v=>!v)} className="pw-toggle"><Icon name={showPw?'eye-off':'eye'} size={14}/></button>
          </div>
          {password && (
            <div style={{marginTop:8}}>
              <div style={{display:'flex',gap:3,marginBottom:6}}>
                {[1,2,3,4].map(i => (
                  <div key={i} style={{flex:1,height:3,borderRadius:999,background: i<=strength ? strengthColor : '#262626'}}/>
                ))}
              </div>
              <div className="tiny muted">{t('pw_strength')}: <span style={{color:strengthColor,fontWeight:500}}>{strengthLabel}</span> · {t('pw_hint')}</div>
            </div>
          )}
        </Field>
        <label className="auth-check" style={{alignItems:'flex-start',marginTop:6}}>
          <input type="checkbox" checked={accept} onChange={e=>setAccept(e.target.checked)} style={{marginTop:2}}/>
          <span className="tiny muted" style={{lineHeight:1.5}}>
            {t('accept_terms_prefix')} <a className="auth-link">{t('terms')}</a> {t('and')} <a className="auth-link">{t('privacy')}</a>.
          </span>
        </label>
        {err.accept && <div className="tiny" style={{color:'#ef4444',marginTop:4}}>{err.accept}</div>}
        <button className="btn btn-primary" type="submit" style={{width:'100%',marginTop:18,height:38,justifyContent:'center'}}>{t('create_account_btn')}</button>
      </form>
    </AuthShell>
  );
};

// ---- Forgot password ----
const ForgotPage = () => {
  const { t } = useI18n();
  const { requestReset, setAuthRoute } = useAuth();
  const [email, setEmail] = useState('');
  const [err, setErr] = useState('');

  const submit = (e) => {
    e.preventDefault();
    if (!email.trim() || !email.includes('@')) { setErr(t('err_invalid_email')); return; }
    requestReset(email);
  };

  return (
    <AuthShell
      title={t('forgot_title')}
      sub={t('forgot_sub')}
      footer={<>
        <a onClick={()=>setAuthRoute('login')} className="auth-link">← {t('back_to_login')}</a>
      </>}
    >
      <form onSubmit={submit}>
        <Field label={t('email')} error={err} hint={t('forgot_hint')}>
          <input className="input" type="email" value={email} onChange={e=>{setEmail(e.target.value);setErr('')}} placeholder="you@example.com" style={{width:'100%'}} autoFocus/>
        </Field>
        <button className="btn btn-primary" type="submit" style={{width:'100%',marginTop:8,height:38,justifyContent:'center'}}>{t('send_reset_link')}</button>
      </form>
    </AuthShell>
  );
};

// ---- Reset password (code + new pw) ----
const ResetPage = () => {
  const { t } = useI18n();
  const { pendingEmail, resetPassword, setAuthRoute } = useAuth();
  const [code, setCode] = useState('');
  const [pw, setPw] = useState('');
  const [pw2, setPw2] = useState('');
  const [err, setErr] = useState({});

  const submit = (e) => {
    e.preventDefault();
    const er = {};
    if (code.length < 6) er.code = t('err_code');
    if (pw.length < 8) er.pw = t('err_pw_too_short');
    if (pw !== pw2) er.pw2 = t('err_pw_mismatch');
    setErr(er);
    if (Object.keys(er).length) return;
    resetPassword(code, pw);
  };

  return (
    <AuthShell
      title={t('reset_title')}
      sub={pendingEmail ? t('reset_sub_with_email').replace('{email}', pendingEmail) : t('reset_sub')}
      footer={<>
        <a onClick={()=>setAuthRoute('forgot')} className="auth-link">← {t('different_email')}</a>
      </>}
    >
      <form onSubmit={submit}>
        <Field label={t('verification_code')} error={err.code} hint={t('code_hint')}>
          <input className="input mono" value={code} onChange={e=>{setCode(e.target.value.replace(/\D/g,'').slice(0,6));setErr(p=>({...p,code:undefined}))}} placeholder="000000" style={{width:'100%',letterSpacing:'0.4em',textAlign:'center',fontSize:18,height:44}}/>
        </Field>
        <Field label={t('new_password')} error={err.pw}>
          <input className="input" type="password" value={pw} onChange={e=>setPw(e.target.value)} style={{width:'100%'}} autoComplete="new-password"/>
        </Field>
        <Field label={t('confirm_password')} error={err.pw2}>
          <input className="input" type="password" value={pw2} onChange={e=>setPw2(e.target.value)} style={{width:'100%'}} autoComplete="new-password"/>
        </Field>
        <button className="btn btn-primary" type="submit" style={{width:'100%',marginTop:8,height:38,justifyContent:'center'}}>{t('reset_password_btn')}</button>
      </form>
    </AuthShell>
  );
};

// ---- Verify email ----
const VerifyPage = () => {
  const { t } = useI18n();
  const { pendingEmail, verifyEmail, setAuthRoute } = useAuth();
  const [code, setCode] = useState(['','','','','','']);
  const [err, setErr] = useState('');
  const [resent, setResent] = useState(false);
  const refs = React.useRef([]);

  const setDigit = (i, v) => {
    const d = v.replace(/\D/g,'').slice(0,1);
    const next = [...code];
    next[i] = d;
    setCode(next);
    setErr('');
    if (d && i < 5) refs.current[i+1]?.focus();
    if (next.every(x=>x) && next.join('').length === 6) {
      // auto-submit
      setTimeout(()=>{
        const r = verifyEmail(next.join(''));
        if (r.error) setErr(t('err_code'));
      }, 100);
    }
  };

  const handleKey = (i, e) => {
    if (e.key === 'Backspace' && !code[i] && i > 0) refs.current[i-1]?.focus();
    if (e.key === 'ArrowLeft' && i > 0) refs.current[i-1]?.focus();
    if (e.key === 'ArrowRight' && i < 5) refs.current[i+1]?.focus();
  };

  const handlePaste = (e) => {
    const pasted = e.clipboardData.getData('text').replace(/\D/g,'').slice(0,6);
    if (pasted.length === 6) {
      e.preventDefault();
      setCode(pasted.split(''));
      setTimeout(()=>{
        const r = verifyEmail(pasted);
        if (r.error) setErr(t('err_code'));
      }, 100);
    }
  };

  const submit = (e) => {
    e.preventDefault();
    const c = code.join('');
    if (c.length < 6) { setErr(t('err_code')); return; }
    const r = verifyEmail(c);
    if (r.error) setErr(t('err_code'));
  };

  return (
    <AuthShell
      title={t('verify_title')}
      sub={pendingEmail ? t('verify_sub_with_email').replace('{email}', pendingEmail) : t('verify_sub')}
      footer={<>
        <a onClick={()=>setAuthRoute('signup')} className="auth-link">← {t('use_different_email')}</a>
      </>}
    >
      <form onSubmit={submit}>
        <label className="label">{t('verification_code')}</label>
        <div className="otp-row" onPaste={handlePaste}>
          {code.map((d, i) => (
            <input
              key={i}
              ref={el=>refs.current[i]=el}
              className="otp-input mono"
              value={d}
              onChange={e=>setDigit(i, e.target.value)}
              onKeyDown={e=>handleKey(i,e)}
              inputMode="numeric"
              maxLength={1}
              autoFocus={i===0}
            />
          ))}
        </div>
        {err && <div className="tiny" style={{color:'#ef4444',marginTop:8}}>{err}</div>}
        <div className="tiny muted" style={{marginTop:12}}>
          {t('didnt_receive')}{' '}
          {resent
            ? <span style={{color:'#10b981'}}>✓ {t('code_resent')}</span>
            : <a className="auth-link" onClick={()=>setResent(true)}>{t('resend_code')}</a>}
        </div>
        <button className="btn btn-primary" type="submit" style={{width:'100%',marginTop:20,height:38,justifyContent:'center'}}>{t('verify_email_btn')}</button>
      </form>
    </AuthShell>
  );
};

const AuthRouter = () => {
  const { authRoute } = useAuth();
  switch (authRoute) {
    case 'signup': return <SignupPage />;
    case 'forgot': return <ForgotPage />;
    case 'reset':  return <ResetPage />;
    case 'verify': return <VerifyPage />;
    case 'login':
    default:       return <LoginPage />;
  }
};

window.AuthRouter = AuthRouter;
