// auth.jsx — 登录 / 注册，对接真实后端 API

const AuthScreen = ({ mode = 'signup' }) => {
  const { t } = useI18n();
  const { isMobile } = useBreakpoint();
  const [step, setStep]               = React.useState(1); // 1=form, 2=verify code, 3=forgot, 4=reset code, 5=new password
  const [email, setEmail]             = React.useState('');
  const [password, setPassword]       = React.useState('');
  const [newPassword, setNewPassword] = React.useState('');
  const [code, setCode]               = React.useState(['', '', '', '', '', '']);
  const [verifyToken, setVerifyToken] = React.useState('');
  const [loading, setLoading]         = React.useState(false);
  const [error, setError]             = React.useState('');

  // 已登录则直接跳 dashboard
  React.useEffect(() => {
    if (window.YiteAPI && window.YiteAPI.isLoggedIn()) {
      window.location.href = '/profile';
    }
  }, []);

  // Google One Tap for login/signup page
  React.useEffect(() => {
    if (window.initGoogleOneTap && !window.YiteAPI?.isLoggedIn?.()) {
      window.initGoogleOneTap();
    }
  }, []);

  /* ── 密码强度 ─────────────────────────────────────────── */
  const pwStrength = React.useMemo(() => {
    if (!password) return 0;
    let s = 0;
    if (password.length >= 6)  s++;
    if (password.length >= 10) s++;
    if (/[A-Z]/.test(password) || /[0-9]/.test(password)) s++;
    if (/[^A-Za-z0-9]/.test(password)) s++;
    return s;
  }, [password]);

  const pwStrengthColor = ['var(--line-2)', 'var(--danger)', 'var(--warn)', 'var(--accent)', '#4ade80'][pwStrength];

  /* ── 登录 ─────────────────────────────────────────────── */
  const handleLogin = async () => {
    if (!email || !password) { setError(t('auth.errEmailPassword')); return; }
    setLoading(true); setError('');
    try {
      const data = await window.YiteAPI.auth.login(email, password);
      window.YiteAPI.auth.saveAndRedirect(data, '/discover');
    } catch (e) {
      setError(e.message || t('auth.errLoginFailed'));
    } finally { setLoading(false); }
  };

  const handleSendCode = async () => {
    if (!email) { setError(t('auth.errEmail')); return; }
    if (!password || password.length < 6) { setError(t('auth.errPasswordLen')); return; }
    setLoading(true); setError('');
    try {
      const res = await fetch('/api/v1/auth/register', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email: email.trim(), password }),
      }).then(r => r.json());
      if (res.error) {
        setError(res.error === 'email already registered' ? t('auth.errEmailExists') : res.error);
        return;
      }
      if (res.token) {
        window.YiteAPI.setToken(res.token);
        if (res.user) window.YiteAPI.setUser(res.user);
        window.location.href = '/discover';
      }
    } catch (e) {
      setError(e.message || t('auth.errSendCode'));
    } finally { setLoading(false); }
  };

  const handleVerify = async () => {
    const codeStr = code.join('');
    if (codeStr.length < 6) { setError(t('auth.errCodeLength')); return; }
    setLoading(true); setError('');
    try {
      const data = await window.YiteAPI.auth.registerWithCode(email, verifyToken, codeStr, password);
      window.YiteAPI.auth.saveAndRedirect(data, '/discover');
    } catch (e) {
      if (e.status === 400) setError(t('auth.errInvalidCode'));
      else setError(e.message || t('auth.errVerifyFailed'));
    } finally { setLoading(false); }
  };

  /* ── 验证码输入框 ─────────────────────────────────────── */
  const codeRefs = Array.from({ length: 6 }, () => React.useRef(null));
  const handleCodeInput = (i, val) => {
    const v = val.replace(/\D/g, '').slice(-1);
    const next = [...code]; next[i] = v; setCode(next);
    if (v && i < 5) codeRefs[i + 1].current?.focus();
  };
  const handleCodeKey = (i, e) => {
    if (e.key === 'Backspace' && !code[i] && i > 0) codeRefs[i - 1].current?.focus();
  };

  /* ── 重发验证码 ───────────────────────────────────────── */
  const handleResend = async () => {
    setError('');
    try {
      const data = await window.YiteAPI.auth.sendRegisterCode(email);
      setVerifyToken(data.token);
      setCode(['', '', '', '', '', '']);
    } catch (e) { setError(e.message || 'Failed to resend.'); }
  };

  /* ── Forgot password ──────────────────────────────────── */
  const handleForgotSendCode = async () => {
    if (!email) { setError(t('auth.errEnterEmail')); return; }
    setLoading(true); setError('');
    try {
      const data = await window.YiteAPI.auth.sendResetCode(email);
      setVerifyToken(data.token);
      setCode(['', '', '', '', '', '']);
      setStep(4);
    } catch (e) { setError(e.message || t('auth.errSendCodeFailed')); }
    finally { setLoading(false); }
  };

  const handleResetPassword = async () => {
    const codeStr = code.join('');
    if (codeStr.length < 6) { setError(t('auth.errEnterCode')); return; }
    if (!newPassword || newPassword.length < 6) { setError(t('auth.errPasswordMin6')); return; }
    setLoading(true); setError('');
    try {
      await window.YiteAPI.auth.resetPassword(email, verifyToken, codeStr, newPassword);
      setStep(1);
      setError('');
      setPassword('');
      setNewPassword('');
      // Show success
      ytAlert(t('auth.resetSuccess'));
    } catch (e) { setError(e.message || t('auth.errResetFailed')); }
    finally { setLoading(false); }
  };

  /* ── Google OAuth ─────────────────────────────────────── */
  const handleGmail = () => {
    window.location.href = window.YiteAPI.auth.gmailLoginUrl();
  };

  /* ── 渲染 ─────────────────────────────────────────────── */
  return (
    <div className="yt yt-grid-bg" style={{ width: '100%', minHeight: '100vh', display: 'flex' }}>

      {/* LEFT: 视觉面板 — hidden on mobile */}
      {!isMobile && (
        <div className="yt-spot" style={{
          flex: '0 0 46%', position: 'relative', overflow: 'hidden',
          borderRight: '1px solid var(--line)', padding: '0 72px',
          display: 'flex', flexDirection: 'column', justifyContent: 'center',
        }}>
          <div style={{ marginBottom: 48 }}><Logo size={20} /></div>
          <div style={{ fontSize: 12, color: 'var(--accent)', textTransform: 'uppercase', letterSpacing: '0.12em', fontWeight: 600, marginBottom: 20 }}>{t('auth.whatsInside')}</div>
          <h2 style={{ fontSize: 38, fontWeight: 700, letterSpacing: '-0.03em', lineHeight: 1.2, margin: '0 0 36px', maxWidth: 440 }}>
            {t('auth.tagline1')}<br />{t('auth.tagline2')}<br /><span className="yt-grad-text">{t('auth.tagline3')}</span>
          </h2>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 18, maxWidth: 400 }}>
            {[
              ['image',  t('auth.pitch1')],
              ['layers', t('auth.pitch2')],
              ['lock',   t('auth.pitch3')],
            ].map(([ic, txt]) => (
              <div key={ic} style={{ display: 'flex', gap: 14, alignItems: 'center', fontSize: 15, color: 'var(--fg-1)', lineHeight: 1.6 }}>
                <div style={{ width: 36, height: 36, borderRadius: 10, background: 'rgba(34,211,238,0.08)', border: '1px solid rgba(34,211,238,0.15)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                  <Icon name={ic} size={16} color="var(--accent)" />
                </div>
                <span>{txt}</span>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* RIGHT: 表单 */}
      <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: isMobile ? '24px 20px' : '40px 60px' }}>
        <div style={{ width: '100%', maxWidth: 420 }}>

          {/* 错误提示 */}
          {error && (
            <div style={{
              marginBottom: 16, padding: '10px 14px', borderRadius: 8,
              background: 'rgba(248,113,113,0.1)', border: '1px solid rgba(248,113,113,0.3)',
              fontSize: 13, color: '#fca5a5', lineHeight: 1.4,
            }}>{error}</div>
          )}

          {step === 1 && (
            <>
              <h1 style={{ fontSize: isMobile ? 26 : 32, fontWeight: 700, letterSpacing: '-0.02em', margin: '0 0 8px' }}>
                {mode === 'signup' ? t('auth.createAccount') : t('auth.welcomeBack')}
              </h1>
              <p style={{ fontSize: isMobile ? 14 : 15, color: 'var(--fg-2)', margin: '0 0 36px' }}>
                {mode === 'signup' ? t('auth.startFree') : t('auth.signInDesc')}
              </p>

              <div style={{ display: 'flex', gap: 8, marginBottom: 20 }}>
                <button className="yt-btn yt-btn-ghost" style={{ flex: 1, height: 46 }} onClick={handleGmail}>
                  <Icon name="google" size={16} /> {t('auth.google')}
                </button>
              </div>

              <div style={{ display: 'flex', alignItems: 'center', gap: 14, margin: '8px 0 24px' }}>
                <div style={{ flex: 1, height: 1, background: 'var(--line)' }} />
                <span style={{ fontSize: 12, color: 'var(--fg-3)', textTransform: 'uppercase', letterSpacing: '0.08em' }}>{t('auth.orEmail')}</span>
                <div style={{ flex: 1, height: 1, background: 'var(--line)' }} />
              </div>

              <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
                <label>
                  <div style={{ fontSize: 13, color: 'var(--fg-2)', marginBottom: 8, fontWeight: 500 }}>{t('auth.email')}</div>
                  <div style={{ position: 'relative' }}>
                    <span style={{ position: 'absolute', left: 12, top: 12, color: 'var(--fg-3)' }}><Icon name="mail" size={16} /></span>
                    <input className="yt-input" type="email" value={email}
                      onChange={e => { setEmail(e.target.value); setError(''); }}
                      onKeyDown={e => e.key === 'Enter' && (mode === 'login' ? handleLogin() : handleSendCode())}
                      placeholder={t('auth.emailPlaceholder')} style={{ paddingLeft: 38 }} />
                  </div>
                </label>

                <label>
                  <div style={{ fontSize: 13, color: 'var(--fg-2)', marginBottom: 8, fontWeight: 500, display: 'flex', justifyContent: 'space-between' }}>
                    <span>{t('auth.password')}</span>
                    {mode === 'login' && <button onClick={() => { setStep(3); setError(''); }} style={{ background: 'none', border: 'none', color: 'var(--accent)', cursor: 'pointer', fontSize: 13, fontWeight: 400, padding: 0 }}>{t('auth.forgot')}</button>}
                  </div>
                  <div style={{ position: 'relative' }}>
                    <span style={{ position: 'absolute', left: 12, top: 12, color: 'var(--fg-3)' }}><Icon name="lock" size={16} /></span>
                    <input className="yt-input" type="password" value={password}
                      onChange={e => { setPassword(e.target.value); setError(''); }}
                      onKeyDown={e => e.key === 'Enter' && (mode === 'login' ? handleLogin() : handleSendCode())}
                      placeholder={t('auth.passwordPlaceholder')} style={{ paddingLeft: 38 }} />
                  </div>
                  {mode === 'signup' && password && (
                    <div style={{ display: 'flex', gap: 4, marginTop: 8 }}>
                      {[1,2,3,4].map(i => (
                        <div key={i} style={{ flex: 1, height: 3, borderRadius: 2, background: i <= pwStrength ? pwStrengthColor : 'var(--line)', transition: 'background .2s' }} />
                      ))}
                    </div>
                  )}
                </label>

                {mode === 'signup' && (
                  <label style={{ display: 'flex', gap: 10, alignItems: 'flex-start', fontSize: 13, color: 'var(--fg-2)', lineHeight: 1.5, marginTop: 4 }}>
                    <input type="checkbox" defaultChecked style={{ marginTop: 3, accentColor: 'var(--accent)' }} />
                    <span>{t('auth.agreeTerms')} <a href="/terms" target="_blank" style={{ color: 'var(--fg-1)' }}>{t('auth.terms')}</a> {t('auth.and')} <a href="/privacy" target="_blank" style={{ color: 'var(--fg-1)' }}>{t('auth.privacy')}</a></span>
                  </label>
                )}

                <button
                  className="yt-btn yt-btn-primary"
                  style={{ height: 48, marginTop: 8, fontSize: 15 }}
                  onClick={mode === 'login' ? handleLogin : handleSendCode}
                  disabled={loading}>
                  {loading ? <span className="yt-spinner" /> : mode === 'signup' ? t('auth.continue') : t('auth.signIn')}
                  {!loading && <Icon name="arrow" size={14} />}
                </button>
              </div>

              <div style={{ marginTop: 28, fontSize: 14, color: 'var(--fg-2)', textAlign: 'center' }}>
                {mode === 'signup'
                  ? <>{t('auth.haveAccount')} <a href="/login" style={{ color: 'var(--accent)', textDecoration: 'none', fontWeight: 500 }}>{t('auth.signInLink')}</a></>
                  : <>{t('auth.noAccount')} <a href="/signup" style={{ color: 'var(--accent)', textDecoration: 'none', fontWeight: 500 }}>{t('auth.createLink')}</a></>
                }
              </div>
            </>
          )}

          {step === 2 && (
            /* ── Step 2: 验证码 ── */
            <>
              <div style={{ width: 56, height: 56, borderRadius: 14, background: 'linear-gradient(135deg, rgba(34,211,238,0.2), rgba(167,139,250,0.15))', border: '1px solid rgba(34,211,238,0.3)', display: 'flex', alignItems: 'center', justifyContent: 'center', marginBottom: 20, color: 'var(--accent)' }}>
                <Icon name="mail" size={26} />
              </div>
              <h1 style={{ fontSize: 28, fontWeight: 600, letterSpacing: '-0.02em', margin: '0 0 6px' }}>{t('auth.checkEmail')}</h1>
              <p style={{ fontSize: 14, color: 'var(--fg-2)', margin: '0 0 24px', lineHeight: 1.5 }}>
                {t('auth.codeSent')} <span style={{ color: 'var(--fg-0)', fontWeight: 500 }}>{email}</span>. {t('auth.codeExpiry')}
              </p>

              {/* 6-digit input */}
              <div style={{ display: 'flex', gap: 8, marginBottom: 24 }}>
                {code.map((d, i) => (
                  <input key={i} ref={codeRefs[i]} maxLength={1} value={d}
                    onChange={e => handleCodeInput(i, e.target.value)}
                    onKeyDown={e => handleCodeKey(i, e)}
                    style={{
                      flex: 1, height: isMobile ? 48 : 56, textAlign: 'center', fontSize: isMobile ? 18 : 22, fontWeight: 600,
                      background: 'rgba(255,255,255,0.03)',
                      border: '1px solid ' + (d ? 'var(--accent)' : 'var(--line-2)'),
                      borderRadius: 10, color: 'var(--fg-0)', outline: 'none',
                      fontFamily: 'var(--font-mono)',
                      boxShadow: d ? '0 0 0 3px rgba(34,211,238,0.15)' : 'none',
                      transition: 'border-color .15s, box-shadow .15s',
                    }} />
                ))}
              </div>

              <button className="yt-btn yt-btn-primary" style={{ width: '100%', height: 44 }}
                onClick={handleVerify} disabled={loading}>
                {loading ? <span className="yt-spinner" /> : t('auth.verifyAndContinue')}
              </button>

              <div style={{ marginTop: 18, fontSize: 13, color: 'var(--fg-2)', textAlign: 'center' }}>
                {t('auth.didntGetIt')}{' '}
                <a style={{ color: 'var(--accent)', fontWeight: 500, cursor: 'pointer' }} onClick={handleResend}>{t('auth.resend')}</a>
                {' '}{t('auth.or')}{' '}
                <a style={{ color: 'var(--fg-1)', cursor: 'pointer' }} onClick={() => { setStep(1); setError(''); }}>{t('auth.changeEmail')}</a>
              </div>
            </>
          )}

          {/* ── Step 3: Forgot password — enter email ── */}
          {step === 3 && (
            <>
              <h1 style={{ fontSize: 28, fontWeight: 600, letterSpacing: '-0.02em', margin: '0 0 6px' }}>{t('auth.forgotTitle')}</h1>
              <p style={{ fontSize: 14, color: 'var(--fg-2)', margin: '0 0 24px' }}>{t('auth.forgotDesc')}</p>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
                <label>
                  <div style={{ fontSize: 12, color: 'var(--fg-2)', marginBottom: 6, fontWeight: 500 }}>{t('auth.emailLabel')}</div>
                  <div style={{ position: 'relative' }}>
                    <span style={{ position: 'absolute', left: 12, top: 12, color: 'var(--fg-3)' }}><Icon name="mail" size={16} /></span>
                    <input className="yt-input" type="email" value={email}
                      onChange={e => { setEmail(e.target.value); setError(''); }}
                      onKeyDown={e => e.key === 'Enter' && handleForgotSendCode()}
                      placeholder="you@example.com" style={{ paddingLeft: 38 }} />
                  </div>
                </label>
                <button className="yt-btn yt-btn-primary" style={{ height: 44, marginTop: 6 }} onClick={handleForgotSendCode} disabled={loading}>
                  {loading ? <span className="yt-spinner" /> : t('auth.sendCode')}
                </button>
              </div>
              <div style={{ marginTop: 18, fontSize: 13, color: 'var(--fg-2)', textAlign: 'center' }}>
                <button onClick={() => { setStep(1); setError(''); }} style={{ background: 'none', border: 'none', color: 'var(--accent)', cursor: 'pointer', fontSize: 13 }}>{t('auth.backToLogin')}</button>
              </div>
            </>
          )}

          {/* ── Step 4: Reset password — code + new password ── */}
          {step === 4 && (
            <>
              <div style={{ width: 56, height: 56, borderRadius: 14, background: 'linear-gradient(135deg, rgba(34,211,238,0.2), rgba(167,139,250,0.15))', border: '1px solid rgba(34,211,238,0.3)', display: 'flex', alignItems: 'center', justifyContent: 'center', marginBottom: 20, color: 'var(--accent)' }}>
                <Icon name="lock" size={26} />
              </div>
              <h1 style={{ fontSize: 28, fontWeight: 600, letterSpacing: '-0.02em', margin: '0 0 6px' }}>{t('auth.resetTitle')}</h1>
              <p style={{ fontSize: 14, color: 'var(--fg-2)', margin: '0 0 24px', lineHeight: 1.5 }}>
                {t('auth.codeSentTo')} <span style={{ color: 'var(--fg-0)', fontWeight: 500 }}>{email}</span>
              </p>
              <div style={{ display: 'flex', gap: 8, marginBottom: 16 }}>
                {code.map((d, i) => (
                  <input key={i} ref={codeRefs[i]} type="text" inputMode="numeric" maxLength={1}
                    value={d} onChange={e => handleCodeInput(i, e.target.value)} onKeyDown={e => handleCodeKey(i, e)}
                    style={{
                      flex: 1, height: isMobile ? 48 : 56, textAlign: 'center', fontSize: isMobile ? 18 : 22, fontWeight: 600,
                      fontFamily: 'var(--font-mono)', background: 'rgba(255,255,255,0.03)',
                      border: '1px solid ' + (d ? 'var(--accent)' : 'var(--line-2)'),
                      borderRadius: 10, color: 'var(--fg-0)', outline: 'none', caretColor: 'var(--accent)',
                      boxShadow: d ? '0 0 0 3px rgba(34,211,238,0.15)' : 'none',
                    }} />
                ))}
              </div>
              <label>
                <div style={{ fontSize: 12, color: 'var(--fg-2)', marginBottom: 6, fontWeight: 500 }}>{t('auth.newPasswordLabel')}</div>
                <div style={{ position: 'relative' }}>
                  <span style={{ position: 'absolute', left: 12, top: 12, color: 'var(--fg-3)' }}><Icon name="lock" size={16} /></span>
                  <input className="yt-input" type="password" value={newPassword}
                    onChange={e => { setNewPassword(e.target.value); setError(''); }}
                    onKeyDown={e => e.key === 'Enter' && handleResetPassword()}
                    placeholder={t('auth.newPasswordHint')} style={{ paddingLeft: 38, marginBottom: 12 }} />
                </div>
              </label>
              <button className="yt-btn yt-btn-primary" style={{ width: '100%', height: 44 }} onClick={handleResetPassword} disabled={loading}>
                {loading ? <span className="yt-spinner" /> : t('auth.resetPassword')}
              </button>
              <div style={{ marginTop: 18, fontSize: 13, color: 'var(--fg-2)', textAlign: 'center' }}>
                <button onClick={handleForgotSendCode} style={{ background: 'none', border: 'none', color: 'var(--accent)', cursor: 'pointer', fontSize: 13 }}>{t('auth.resendCode')}</button>
                {' · '}
                <button onClick={() => { setStep(1); setError(''); }} style={{ background: 'none', border: 'none', color: 'var(--fg-1)', cursor: 'pointer', fontSize: 13 }}>{t('auth.backToLogin')}</button>
              </div>
            </>
          )}
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { AuthScreen });
