// Auth screen — sign in / sign up with email or Google.

const AuthScreen = ({ inviteToken }) => {
  const { signInWithGoogle, signInWithEmail, signUpWithEmail } = useAuth();
  const [formMode, setFormMode] = React.useState(inviteToken ? 'signup' : 'signin');
  const [email, setEmail] = React.useState('');
  const [password, setPassword] = React.useState('');
  const [error, setError] = React.useState('');
  const [loading, setLoading] = React.useState(false);
  const [success, setSuccess] = React.useState('');

  const handleSubmit = async (e) => {
    e.preventDefault();
    setError('');
    setLoading(true);
    try {
      const { error } = formMode === 'signin'
        ? await signInWithEmail(email, password)
        : await signUpWithEmail(email, password);
      if (error) {
        setError(error.message);
      } else if (formMode === 'signup') {
        setSuccess('Check your email for a confirmation link, then come back and sign in.');
      }
    } finally {
      setLoading(false);
    }
  };

  const handleGoogle = async () => {
    setError('');
    const { error } = await signInWithGoogle();
    if (error) setError(error.message);
  };

  const switchMode = (m) => { setFormMode(m); setError(''); setSuccess(''); };

  return (
    <div style={{
      minHeight: '100vh',
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
      background: 'var(--surface)',
      padding: '24px 16px',
    }}>
      <div style={{
        width: '100%',
        maxWidth: 400,
        background: 'var(--card)',
        borderRadius: 20,
        padding: '36px 32px',
        boxShadow: 'var(--shadow-lg)',
        border: '1px solid var(--line)',
      }}>

        {/* Brand */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 28 }}>
          <div style={{
            width: 32, height: 32, borderRadius: 10,
            background: 'var(--ink)', position: 'relative', overflow: 'hidden',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}>
            <div style={{
              width: 14, height: 14, borderRadius: '50%',
              background: 'var(--mint)',
              animation: 'float 3s ease-in-out infinite',
            }} />
          </div>
          <div>
            <div style={{ fontSize: 15, fontWeight: 600, letterSpacing: '-0.01em', color: 'var(--ink)' }}>
              Budget Builder
            </div>
            <div style={{ fontSize: 10, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>
              Personal Finance
            </div>
          </div>
        </div>

        {inviteToken && (
          <div style={{ background:'#f0fdf4', border:'1px solid #86efac', borderRadius:10, padding:'12px 14px', fontSize:13, color:'#166534', marginBottom:20 }}>
            You've been invited to join a household — sign in or create an account to accept.
          </div>
        )}

        <h1 style={{ fontSize: 24, fontWeight: 500, letterSpacing: '-0.02em', margin: '0 0 6px', color: 'var(--ink)' }}>
          {formMode === 'signin' ? 'Welcome back' : 'Create account'}
        </h1>
        <p style={{ fontSize: 13.5, color: 'var(--ink-3)', margin: '0 0 24px' }}>
          {formMode === 'signin' ? 'Sign in to access your budget.' : 'Start tracking your finances today.'}
        </p>

        {/* Google button */}
        <button
          onClick={handleGoogle}
          style={{
            width: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center',
            gap: 10, padding: '11px 16px',
            border: '1.5px solid var(--line)', borderRadius: 10,
            background: 'var(--card)', cursor: 'pointer',
            fontSize: 14, fontWeight: 500, color: 'var(--ink)',
            transition: 'background 0.15s, border-color 0.15s',
            marginBottom: 20,
          }}
          onMouseOver={e => e.currentTarget.style.background = 'var(--surface-2)'}
          onMouseOut={e => e.currentTarget.style.background = 'var(--card)'}
        >
          <svg width="18" height="18" 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>
          Continue with Google
        </button>

        {/* Divider */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 20 }}>
          <div style={{ flex: 1, height: 1, background: 'var(--line)' }} />
          <span style={{ fontSize: 12, color: 'var(--ink-4)' }}>or</span>
          <div style={{ flex: 1, height: 1, background: 'var(--line)' }} />
        </div>

        {/* Success state */}
        {success ? (
          <div style={{
            background: '#f0fdf4', border: '1px solid #86efac',
            borderRadius: 10, padding: '14px 16px',
            fontSize: 13.5, color: '#166534', lineHeight: 1.5,
          }}>
            {success}
          </div>
        ) : (
          <form onSubmit={handleSubmit}>
            <div style={{ marginBottom: 12 }}>
              <label style={{ display: 'block', fontSize: 12, fontWeight: 500, color: 'var(--ink-2)', marginBottom: 5 }}>
                Email
              </label>
              <input
                type="email" value={email} onChange={e => setEmail(e.target.value)}
                required placeholder="you@example.com"
                style={{
                  width: '100%', padding: '10px 12px', borderRadius: 8,
                  border: '1.5px solid var(--line)', background: 'var(--surface)',
                  fontSize: 14, color: 'var(--ink)', outline: 'none',
                  boxSizing: 'border-box', transition: 'border-color 0.15s',
                }}
                onFocus={e => e.target.style.borderColor = 'var(--ink)'}
                onBlur={e => e.target.style.borderColor = 'var(--line)'}
              />
            </div>
            <div style={{ marginBottom: 20 }}>
              <label style={{ display: 'block', fontSize: 12, fontWeight: 500, color: 'var(--ink-2)', marginBottom: 5 }}>
                Password
              </label>
              <input
                type="password" value={password} onChange={e => setPassword(e.target.value)}
                required placeholder="••••••••" minLength={6}
                style={{
                  width: '100%', padding: '10px 12px', borderRadius: 8,
                  border: '1.5px solid var(--line)', background: 'var(--surface)',
                  fontSize: 14, color: 'var(--ink)', outline: 'none',
                  boxSizing: 'border-box', transition: 'border-color 0.15s',
                }}
                onFocus={e => e.target.style.borderColor = 'var(--ink)'}
                onBlur={e => e.target.style.borderColor = 'var(--line)'}
              />
            </div>

            {error && (
              <div style={{
                background: '#fff1f0', border: '1px solid #fca5a5',
                borderRadius: 8, padding: '10px 12px',
                fontSize: 13, color: '#b91c1c', marginBottom: 14,
              }}>
                {error}
              </div>
            )}

            <button
              type="submit" disabled={loading}
              style={{
                width: '100%', padding: '11px 16px',
                background: loading ? 'var(--ink-3)' : 'var(--ink)',
                color: 'white', border: 'none', borderRadius: 10,
                fontSize: 14, fontWeight: 500,
                cursor: loading ? 'not-allowed' : 'pointer',
                transition: 'background 0.15s',
              }}
            >
              {loading ? 'Please wait…' : formMode === 'signin' ? 'Sign in' : 'Create account'}
            </button>
          </form>
        )}

        {/* Toggle sign in / sign up */}
        <p style={{ textAlign: 'center', fontSize: 13, color: 'var(--ink-3)', marginTop: 20, marginBottom: 0 }}>
          {formMode === 'signin' ? "Don't have an account? " : 'Already have an account? '}
          <button
            onClick={() => switchMode(formMode === 'signin' ? 'signup' : 'signin')}
            style={{
              background: 'none', border: 'none', color: 'var(--ink)',
              fontWeight: 500, cursor: 'pointer', fontSize: 13, padding: 0,
            }}
          >
            {formMode === 'signin' ? 'Sign up' : 'Sign in'}
          </button>
        </p>
      </div>
    </div>
  );
};

Object.assign(window, { AuthScreen });
