const { useState: useStateLogin, useEffect: useEffectLogin } = React;

const GoogleGlyph = () => (
  <svg width="18" height="18" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
    <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.1c-.22-.66-.35-1.36-.35-2.1s.13-1.44.35-2.1V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.61z"/>
    <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>
);

const Login = ({ onSignedIn, lang }) => {
  const [submitting, setSubmitting] = useStateLogin(false);
  const [error, setError] = useStateLogin('');
  const [step, setStep] = useStateLogin('email');
  const [email, setEmail] = useStateLogin('');
  const [otp, setOtp] = useStateLogin('');
  const t = (k) => window.__t(k, lang);

  const handleGoogle = async () => {
    setError('');
    setSubmitting(true);
    try {
      await window.__api.signInWithGoogle();
    } catch (e) {
      console.error(e);
      setError(e.message || 'Sign in failed');
      setSubmitting(false);
    }
  };

  const handleSendOtp = async (e) => {
    e.preventDefault();
    setError('');
    if (!email) { setError('Please enter your email'); return; }
    setSubmitting(true);
    try {
      await window.__api.sendEmailOtp(email);
      setStep('otp');
    } catch (err) {
      console.error(err);
      setError(err.message || 'Failed to send code');
    } finally {
      setSubmitting(false);
    }
  };

  const handleVerifyOtp = async (e) => {
    e.preventDefault();
    setError('');
    if (!otp || otp.length < 6) { setError('Enter the 6-digit code'); return; }
    setSubmitting(true);
    try {
      await window.__api.verifyEmailOtp(email, otp);
    } catch (err) {
      console.error(err);
      setError(err.message || 'Invalid or expired code');
      setSubmitting(false);
    }
  };

  const resetEmail = () => { setStep('email'); setOtp(''); setError(''); };

  return (
    <div style={{
      minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center',
      background: 'var(--bg)', color: 'var(--fg)', padding: 40
    }}>
      <div style={{
        background: 'var(--bg-elev)', border: '1px solid var(--line)', borderRadius: 'var(--radius-lg)',
        padding: '48px 44px', width: '100%', maxWidth: 440, boxShadow: '0 8px 36px rgba(10,10,10,0.06)',
        textAlign: 'center'
      }}>
        <div style={{
          width: 56, height: 56, margin: '0 auto 24px',
          background: 'var(--fg)', color: 'var(--bg-elev)',
          borderRadius: 14, display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontFamily: 'var(--serif, var(--sans))', fontSize: 28, fontWeight: 600
        }}>{lang === 'ar' ? 'ف' : 'F'}</div>
        <div className="mono" style={{
          fontSize: 10, color: 'var(--fg-3)', textTransform: 'uppercase',
          letterSpacing: '0.16em', marginBottom: 8
        }}>{t('login.tag')}</div>
        <h1 style={{
          margin: '0 0 10px', fontSize: 26, fontWeight: 500,
          fontFamily: 'var(--serif, var(--sans))', letterSpacing: '-0.015em'
        }}>{t('login.title')}</h1>
        <p style={{ color: 'var(--fg-3)', fontSize: 14, margin: '0 0 32px', lineHeight: 1.6 }}>
          {t('login.body')}
        </p>

        <button
          onClick={handleGoogle}
          disabled={submitting}
          style={{
            width: '100%', padding: '12px 16px',
            background: 'var(--bg-elev)', color: 'var(--fg)',
            border: '1px solid var(--line-2)', borderRadius: 10,
            fontSize: 14, fontWeight: 500, cursor: submitting ? 'wait' : 'pointer',
            display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 12,
            transition: 'background 0.12s, border-color 0.12s'
          }}
          onMouseEnter={e => { if (!submitting) e.currentTarget.style.background = 'var(--bg-soft)'; }}
          onMouseLeave={e => { e.currentTarget.style.background = 'var(--bg-elev)'; }}
        >
          <GoogleGlyph />
          <span>{t('login.google')}</span>
        </button>

        <div style={{
          display: 'flex', alignItems: 'center', gap: 12,
          margin: '20px 0', color: 'var(--fg-4)', fontSize: 11,
          textTransform: 'uppercase', letterSpacing: '0.14em'
        }}>
          <div style={{ flex: 1, height: 1, background: 'var(--line)' }} />
          <span>or</span>
          <div style={{ flex: 1, height: 1, background: 'var(--line)' }} />
        </div>

        {step === 'email' ? (
          <form onSubmit={handleSendOtp}>
            <div style={{ textAlign: 'left', marginBottom: 14 }}>
              <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--fg)', marginBottom: 4 }}>
                Sign in with email
              </div>
              <div style={{ fontSize: 13, color: 'var(--fg-3)', lineHeight: 1.5 }}>
                Enter your email and we'll send you a 6-digit code to sign in.
              </div>
            </div>
            <input
              type="email"
              value={email}
              onChange={e => setEmail(e.target.value)}
              placeholder="you@example.com"
              autoComplete="email"
              required
              disabled={submitting}
              style={{
                width: '100%', padding: '12px 14px', boxSizing: 'border-box',
                background: 'var(--bg-elev)', color: 'var(--fg)',
                border: '1px solid var(--line-2)', borderRadius: 10,
                fontSize: 14, marginBottom: 10, outline: 'none'
              }}
            />
            <button
              type="submit"
              disabled={submitting}
              style={{
                width: '100%', padding: '12px 16px',
                background: 'var(--fg)', color: 'var(--bg-elev)',
                border: '1px solid var(--fg)', borderRadius: 10,
                fontSize: 14, fontWeight: 500,
                cursor: submitting ? 'wait' : 'pointer'
              }}
            >
              {submitting ? 'Sending code…' : 'Send code to email'}
            </button>
          </form>
        ) : (
          <form onSubmit={handleVerifyOtp}>
            <div style={{ textAlign: 'left', marginBottom: 14 }}>
              <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--fg)', marginBottom: 4 }}>
                Enter the 6-digit code
              </div>
              <div style={{ fontSize: 13, color: 'var(--fg-3)', lineHeight: 1.5 }}>
                We sent it to <strong style={{ color: 'var(--fg)' }}>{email}</strong>.
                {' '}
                <a href="#" onClick={(e) => { e.preventDefault(); resetEmail(); }} style={{ color: 'var(--fg)', textDecoration: 'underline' }}>
                  Use a different email
                </a>
              </div>
            </div>
            <input
              type="text"
              inputMode="numeric"
              pattern="[0-9]{6}"
              maxLength={6}
              value={otp}
              onChange={e => setOtp(e.target.value.replace(/\D/g, ''))}
              placeholder="123456"
              autoComplete="one-time-code"
              required
              disabled={submitting}
              autoFocus
              style={{
                width: '100%', padding: '12px 14px', boxSizing: 'border-box',
                background: 'var(--bg-elev)', color: 'var(--fg)',
                border: '1px solid var(--line-2)', borderRadius: 10,
                fontSize: 18, letterSpacing: '0.4em', textAlign: 'center',
                fontFamily: 'var(--mono, monospace)',
                marginBottom: 10, outline: 'none'
              }}
            />
            <button
              type="submit"
              disabled={submitting}
              style={{
                width: '100%', padding: '12px 16px',
                background: 'var(--fg)', color: 'var(--bg-elev)',
                border: '1px solid var(--fg)', borderRadius: 10,
                fontSize: 14, fontWeight: 500,
                cursor: submitting ? 'wait' : 'pointer'
              }}
            >
              {submitting ? 'Verifying…' : 'Verify and sign in'}
            </button>
          </form>
        )}

        {error && (
          <div style={{
            marginTop: 18, padding: '9px 12px', background: '#fee',
            color: 'var(--neg)', borderRadius: 8, fontSize: 13
          }}>{error}</div>
        )}
      </div>
    </div>
  );
};

window.Login = Login;
