function AuthScreen() {
  const T = window.T;
  const [email, setEmail] = React.useState('');
  const [code, setCode] = React.useState('');
  const [phase, setPhase] = React.useState('input'); 
  // input | sending | code | verifying | error
  const [errorMsg, setErrorMsg] = React.useState('');

  const isValidEmail = (value) => {
    const trimmed = value.trim();
    return trimmed && trimmed.includes('@');
  };

  const sendCode = async (e) => {
    e?.preventDefault();

    const trimmed = email.trim().toLowerCase();
    if (!isValidEmail(trimmed)) {
      setErrorMsg('Please enter a valid email address');
      setPhase('error');
      return;
    }

    setPhase('sending');
    setErrorMsg('');

    try {
      await window.signInWithEmail(trimmed);
      setEmail(trimmed);
      setCode('');
      setPhase('code');
    } catch (err) {
      setErrorMsg(err?.message || 'Something went wrong. Try again.');
      setPhase('error');
    }
  };

  const verifyCode = async (e) => {
    e?.preventDefault();

    const trimmedEmail = email.trim().toLowerCase();
    const trimmedCode = code.trim();

    if (!trimmedCode) {
      setErrorMsg('Please enter the code from your email');
      setPhase('error');
      return;
    }

    setPhase('verifying');
    setErrorMsg('');

    try {
      await window.verifyEmailCode(trimmedEmail, trimmedCode);
      window.location.href = '/';
    } catch (err) {
      setErrorMsg(err?.message || 'Invalid or expired code. Try again.');
      setPhase('code');
    }
  };

  const reset = () => {
    setPhase('input');
    setEmail('');
    setCode('');
    setErrorMsg('');
  };

  const resendCode = async () => {
    const trimmed = email.trim().toLowerCase();
    if (!isValidEmail(trimmed)) {
      setErrorMsg('Please enter a valid email address');
      setPhase('error');
      return;
    }

    setPhase('sending');
    setErrorMsg('');

    try {
      await window.signInWithEmail(trimmed);
      setPhase('code');
    } catch (err) {
      setErrorMsg(err?.message || 'Could not resend code. Try again.');
      setPhase('code');
    }
  };

  return (
    <div style={{
      flex: 1,
      display:'flex',
      flexDirection:'column',
      padding:'60px 24px 40px',
      background: T.navy950,
    }}>
      <div style={{textAlign:'center', marginTop: 40}}>
        <Wordmark size={44}/>
        <div style={{
          fontSize: 13,
          color: T.textSec,
          marginTop: 10,
          letterSpacing:'0.08em',
          fontFamily:'DM Sans',
          textTransform:'uppercase'
        }}>
          Beta
        </div>
      </div>

      <div style={{flex: 1, display:'flex', flexDirection:'column', justifyContent:'center'}}>
        {(phase === 'input' || phase === 'sending' || phase === 'error') && (
          <form onSubmit={sendCode}>
            <div style={{marginBottom: 24}}>
              <div style={{
                fontFamily:'Bakbak One, sans-serif',
                fontSize: 26,
                color: T.text,
                letterSpacing:'0.03em',
                marginBottom: 8,
                textAlign:'center',
              }}>
                SIGN IN TO PLAY
              </div>
              <div style={{
                fontSize: 13,
                color: T.textSec,
                textAlign:'center',
                lineHeight: 1.5
              }}>
                Enter your email and we&apos;ll send you<br/>a login code — no password needed
              </div>
            </div>

            <div style={{marginBottom: 14}}>
              <input
                type="email"
                value={email}
                onChange={e => setEmail(e.target.value)}
                placeholder="you@email.com"
                autoCapitalize="off"
                autoCorrect="off"
                autoComplete="email"
                disabled={phase === 'sending'}
                style={{
                  width:'100%',
                  padding:'14px 16px',
                  background: T.card,
                  border:`1px solid ${phase === 'error' ? T.red : T.border}`,
                  borderRadius: 12,
                  color: T.text,
                  fontFamily:'DM Sans',
                  fontSize: 14,
                  outline:'none',
                  boxSizing:'border-box',
                }}
              />
              {phase === 'error' && errorMsg && (
                <div style={{color: T.red, fontSize: 12, marginTop: 8, paddingLeft: 4}}>
                  {errorMsg}
                </div>
              )}
            </div>

            <button
              type="submit"
              disabled={phase === 'sending' || !email.trim()}
              style={{
                width:'100%',
                padding:'14px',
                borderRadius: 12,
                background: phase === 'sending' || !email.trim()
                  ? T.card
                  : 'linear-gradient(180deg, #F5C842, #C99A10)',
                color: phase === 'sending' || !email.trim() ? T.textMute : '#1A1200',
                border: phase === 'sending' || !email.trim() ? `1px solid ${T.border}` : 'none',
                cursor: phase === 'sending' || !email.trim() ? 'default' : 'pointer',
                fontFamily:'Bakbak One, sans-serif',
                fontSize: 15,
                letterSpacing:'0.06em',
              }}
            >
              {phase === 'sending' ? 'SENDING…' : 'SEND LOGIN CODE'}
            </button>
          </form>
        )}

        {(phase === 'code' || phase === 'verifying') && (
          <div style={{padding:'0 4px'}}>
            <div style={{textAlign:'center', padding:'0 10px', marginBottom: 24}}>
              <div style={{
                width: 72,
                height: 72,
                borderRadius:'50%',
                background:'rgba(55,168,95,0.15)',
                border:'1px solid rgba(55,168,95,0.4)',
                margin:'0 auto 22px',
                display:'flex',
                alignItems:'center',
                justifyContent:'center',
              }}>
                <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="#37A85F" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                  <path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"/>
                  <path d="M22 6l-10 7L2 6"/>
                </svg>
              </div>

              <div style={{
                fontFamily:'Bakbak One, sans-serif',
                fontSize: 24,
                color: T.text,
                letterSpacing:'0.03em',
                marginBottom: 10
              }}>
                ENTER YOUR CODE
              </div>

              <div style={{
                fontSize: 14,
                color: T.textSec,
                lineHeight: 1.5,
                marginBottom: 24
              }}>
                We sent a login code to<br/>
                <span style={{color: T.text, fontWeight: 600}}>{email}</span>
              </div>
            </div>

            <form onSubmit={verifyCode}>
              <div style={{marginBottom: 14}}>
                <input
                  type="text"
                  value={code}
                  onChange={e => setCode(e.target.value.replace(/\s/g, ''))}
                  placeholder="Enter code"
                  inputMode="numeric"
                  autoComplete="one-time-code"
                  disabled={phase === 'verifying'}
                  style={{
                    width:'100%',
                    padding:'14px 16px',
                    background: T.card,
                    border:`1px solid ${errorMsg ? T.red : T.border}`,
                    borderRadius: 12,
                    color: T.text,
                    fontFamily:'DM Sans',
                    fontSize: 16,
                    outline:'none',
                    boxSizing:'border-box',
                    textAlign:'center',
                    letterSpacing:'0.18em',
                  }}
                />
                {errorMsg && (
                  <div style={{color: T.red, fontSize: 12, marginTop: 8, paddingLeft: 4, textAlign:'center'}}>
                    {errorMsg}
                  </div>
                )}
              </div>

              <button
                type="submit"
                disabled={phase === 'verifying' || !code.trim()}
                style={{
                  width:'100%',
                  padding:'14px',
                  borderRadius: 12,
                  background: phase === 'verifying' || !code.trim()
                    ? T.card
                    : 'linear-gradient(180deg, #F5C842, #C99A10)',
                  color: phase === 'verifying' || !code.trim() ? T.textMute : '#1A1200',
                  border: phase === 'verifying' || !code.trim() ? `1px solid ${T.border}` : 'none',
                  cursor: phase === 'verifying' || !code.trim() ? 'default' : 'pointer',
                  fontFamily:'Bakbak One, sans-serif',
                  fontSize: 15,
                  letterSpacing:'0.06em',
                  marginBottom: 14,
                }}
              >
                {phase === 'verifying' ? 'VERIFYING…' : 'VERIFY CODE'}
              </button>
            </form>

            <div style={{textAlign:'center', display:'flex', flexDirection:'column', gap: 10}}>
              <button
                type="button"
                onClick={resendCode}
                disabled={phase === 'verifying'}
                style={{
                  background:'transparent',
                  border:'none',
                  color: T.gold400,
                  fontSize: 12,
                  fontWeight: 600,
                  cursor:'pointer',
                  fontFamily:'DM Sans',
                }}
              >
                Resend code
              </button>

              <button
                type="button"
                onClick={reset}
                disabled={phase === 'verifying'}
                style={{
                  background:'transparent',
                  border:'none',
                  color: T.textSec,
                  fontSize: 12,
                  fontWeight: 600,
                  cursor:'pointer',
                  fontFamily:'DM Sans',
                }}
              >
                Use a different email
              </button>
            </div>
          </div>
        )}
      </div>

      <div style={{
        textAlign:'center',
        fontSize: 10.5,
        color: T.textMute,
        fontFamily:'DM Sans',
        letterSpacing:'0.1em'
      }}>
        BY SIGNING IN YOU AGREE TO OUR BETA TERMS
      </div>
    </div>
  );
}

window.AuthScreen = AuthScreen;
