/* global React */
const { useState } = React;

function AuthGate({ onAuth }) {
  const [mode, setMode]         = useState('login'); // 'login' | 'signup'
  const [email, setEmail]       = useState('');
  const [password, setPassword] = useState('');
  const [loading, setLoading]   = useState(false);
  const [error, setError]       = useState('');
  const [message, setMessage]   = useState('');

  async function handleSubmit(e) {
    e.preventDefault();
    setError('');
    setMessage('');
    setLoading(true);
    try {
      let result;
      if (mode === 'login') {
        result = await window._sb.auth.signInWithPassword({ email, password });
      } else {
        result = await window._sb.auth.signUp({ email, password });
        if (!result.error && result.data.user && !result.data.session) {
          setMessage('Check your email for a confirmation link.');
          setLoading(false);
          return;
        }
      }
      if (result.error) {
        setError(result.error.message);
      } else if (result.data.session) {
        onAuth(result.data.session);
      }
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  }

  const inputStyle = {
    width: '100%', padding: '10px 12px',
    border: '1px solid rgba(120,160,255,0.2)', borderRadius: 8,
    background: 'rgba(255,255,255,0.04)', color: '#f0f4ff',
    fontSize: 14, fontFamily: 'inherit', outline: 'none',
    transition: 'border-color 0.15s', boxSizing: 'border-box',
  };

  return (
    <div style={{
      minHeight: '100vh', display: 'flex', alignItems: 'center',
      justifyContent: 'center', background: '#0a0e1a',
      fontFamily: '-apple-system, BlinkMacSystemFont, "Inter", sans-serif',
    }}>
      <div style={{
        width: 360, padding: '36px 32px',
        background: '#11172a', border: '1px solid rgba(120,160,255,0.15)',
        borderRadius: 16, boxShadow: '0 30px 80px -20px rgba(0,0,0,0.6)',
      }}>

        {/* Branding */}
        <div style={{ textAlign: 'center', marginBottom: 28 }}>
          <div style={{
            display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
            width: 48, height: 48, borderRadius: 12, marginBottom: 14,
            background: 'linear-gradient(135deg, oklch(0.55 0.20 240), oklch(0.46 0.24 250))',
            boxShadow: '0 8px 24px oklch(0.55 0.20 240 / 0.35)',
          }}>
            <span style={{ color: '#fff', fontWeight: 800, fontSize: 13, letterSpacing: '-0.5px' }}>AIP</span>
          </div>
          <div style={{ fontSize: 20, fontWeight: 700, color: '#f0f4ff', letterSpacing: '-0.3px' }}>
            AIP Analyzer
          </div>
          <div style={{ fontSize: 13, color: '#8590ad', marginTop: 4 }}>
            {mode === 'login' ? 'Sign in to your account' : 'Create an account'}
          </div>
        </div>

        {/* Mode toggle */}
        <div style={{
          display: 'flex', border: '1px solid rgba(120,160,255,0.15)',
          borderRadius: 8, overflow: 'hidden', marginBottom: 24,
        }}>
          {[['login', 'Sign In'], ['signup', 'Sign Up']].map(([m, label]) => (
            <button key={m} onClick={() => { setMode(m); setError(''); setMessage(''); }}
              style={{
                flex: 1, padding: '8px 0', border: 'none', cursor: 'pointer',
                fontFamily: 'inherit', fontSize: 13, fontWeight: 500,
                background: mode === m ? 'oklch(0.55 0.20 240)' : 'transparent',
                color: mode === m ? '#fff' : '#8590ad',
                transition: 'all 0.12s',
              }}>
              {label}
            </button>
          ))}
        </div>

        {/* Form */}
        <form onSubmit={handleSubmit} style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          <div>
            <label style={{ fontSize: 12, fontWeight: 500, color: '#c4cee0', display: 'block', marginBottom: 6 }}>
              Email
            </label>
            <input type="email" value={email} onChange={e => setEmail(e.target.value)}
              required placeholder="you@example.com" style={inputStyle}
              onFocus={e => { e.target.style.borderColor = 'oklch(0.55 0.20 240)'; }}
              onBlur={e  => { e.target.style.borderColor = 'rgba(120,160,255,0.2)'; }}
            />
          </div>
          <div>
            <label style={{ fontSize: 12, fontWeight: 500, color: '#c4cee0', display: 'block', marginBottom: 6 }}>
              Password
            </label>
            <input type="password" value={password} onChange={e => setPassword(e.target.value)}
              required placeholder="••••••••" minLength={6} style={inputStyle}
              onFocus={e => { e.target.style.borderColor = 'oklch(0.55 0.20 240)'; }}
              onBlur={e  => { e.target.style.borderColor = 'rgba(120,160,255,0.2)'; }}
            />
          </div>

          {error && (
            <div style={{
              padding: '9px 12px', borderRadius: 7, fontSize: 13,
              background: 'rgba(239,68,68,0.12)', border: '1px solid rgba(239,68,68,0.25)',
              color: '#f87171',
            }}>
              {error}
            </div>
          )}
          {message && (
            <div style={{
              padding: '9px 12px', borderRadius: 7, fontSize: 13,
              background: 'rgba(34,197,94,0.12)', border: '1px solid rgba(34,197,94,0.25)',
              color: '#4ade80',
            }}>
              {message}
            </div>
          )}

          <button type="submit" disabled={loading} style={{
            width: '100%', padding: '10px', borderRadius: 8, border: 'none',
            background: 'oklch(0.55 0.20 240)', color: '#fff',
            fontSize: 14, fontWeight: 600, cursor: loading ? 'default' : 'pointer',
            fontFamily: 'inherit', opacity: loading ? 0.7 : 1,
            transition: 'opacity 0.15s', marginTop: 4,
          }}>
            {loading ? 'Please wait…' : mode === 'login' ? 'Sign In' : 'Create Account'}
          </button>
        </form>
      </div>
    </div>
  );
}
