// Auth screen — login + register + Google sign-in. Approval gate on the backend.

function AuthScreen({ onSignIn }) {
  const [mode, setMode] = React.useState('login');
  const [email, setEmail] = React.useState('');
  const [username, setUsername] = React.useState('');
  const [password, setPassword] = React.useState('');
  const [name, setName] = React.useState('');
  const [loading, setLoading] = React.useState(false);
  const [error, setError] = React.useState(null);
  const [info, setInfo] = React.useState(null);
  const [googleClientId, setGoogleClientId] = React.useState('');

  // Probe whether Google sign-in is configured on this deployment.
  React.useEffect(() => {
    api.get('/api/auth/google/config')
      .then(c => setGoogleClientId(c.client_id || ''))
      .catch(() => {});
  }, []);

  // Initialize Google Identity Services once the client id arrives.
  React.useEffect(() => {
    if (!googleClientId) return;
    const onGoogleResponse = async (resp) => {
      setError(null); setInfo(null); setLoading(true);
      try {
        const r = await api.post('/api/auth/google', { credential: resp.credential });
        if (r.access_token) {
          api.setToken(r.access_token);
          const me = await api.get('/api/auth/me');
          onSignIn(me);
        } else if (r.status === 'pending') {
          setInfo(r.message || "Signed up with Google. Waiting for admin approval.");
          setMode('login');
        }
      } catch (e) {
        setError(e.detail || e.message || 'Google sign-in failed');
      }
      setLoading(false);
    };
    // Inject the GIS script once.
    if (!document.getElementById('gis-script')) {
      const s = document.createElement('script');
      s.id = 'gis-script';
      s.src = 'https://accounts.google.com/gsi/client';
      s.async = true; s.defer = true;
      s.onload = () => initGis(onGoogleResponse);
      document.head.appendChild(s);
    } else if (window.google?.accounts?.id) {
      initGis(onGoogleResponse);
    }
    function initGis(callback) {
      try {
        window.google.accounts.id.initialize({ client_id: googleClientId, callback });
        const el = document.getElementById('gsi-btn');
        if (el) window.google.accounts.id.renderButton(el, { theme: 'outline', size: 'large', width: 360, text: 'continue_with' });
      } catch (e) { /* render is best-effort */ }
    }
  }, [googleClientId]);

  const submit = async (e) => {
    e?.preventDefault();
    setLoading(true); setError(null); setInfo(null);
    try {
      if (mode === 'login') {
        const res = await api.post('/api/auth/login', { username: username || email, password });
        api.setToken(res.access_token);
        const user = await api.get('/api/auth/me');
        onSignIn(user);
      } else {
        const res = await api.post('/api/auth/register', {
          username,
          email,
          password,
          full_name: name || null,
        });
        api.setToken(res.access_token);
        const user = await api.get('/api/auth/me');
        onSignIn(user);
      }
    } catch (e) {
      setError(e.detail || e.message || 'Sign-in failed');
      setLoading(false);
      return;
    }
    setLoading(false);
  };

  return (
    <div className="auth-shell">
      <div className="auth-side">
        <div className="brand">
          <div className="brand-mark">A</div>
          <div>
            <div className="brand-name">Aeizch</div>
            <div className="brand-sub">Pooled trading · Closed user group</div>
          </div>
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 24, maxWidth: 460 }}>
          <div style={{ fontSize: 13, letterSpacing: '0.16em', textTransform: 'uppercase', opacity: 0.6, fontWeight: 600 }}>
            Members only · CUG
          </div>
          <h1 style={{ fontSize: 44, fontWeight: 700, letterSpacing: '-0.03em', lineHeight: 1.05, margin: 0 }}>
            One pool.<br/>Many bots.<br/><span style={{ color: 'var(--accent)' }}>Real-time NAV.</span>
          </h1>
          <p style={{ fontSize: 16, lineHeight: 1.5, opacity: 0.7, margin: 0 }}>
            Invest in algo-driven crypto strategies through a unit-priced fund.
            Buy units, sell units, watch the NAV move — we handle the keys.
          </p>
        </div>
        <div style={{ fontSize: 11, opacity: 0.4, fontWeight: 500 }}>
          v0.8 beta · Approval-gated signups
        </div>
        <Glyph />
      </div>
      <div className="auth-pane">
        <div className="auth-card">
          <div>
            <div className="crumb">{mode === 'login' ? 'Welcome back' : 'Create account'}</div>
            <h2 style={{ margin: '6px 0 0', fontSize: 28, fontWeight: 700, letterSpacing: '-0.02em' }}>
              {mode === 'login' ? 'Sign in to Aeizch' : 'Join the CUG'}
            </h2>
            <p className="muted" style={{ margin: '6px 0 0', fontSize: 14 }}>
              {mode === 'login'
                ? 'Use your username/email or sign in with Google.'
                : 'Sign up immediately and submit your KYC details for review.'}
            </p>
          </div>

          {googleClientId && (
            <>
              <div id="gsi-btn" style={{ display: 'flex', justifyContent: 'center' }}/>
              <div className="divider">or</div>
            </>
          )}

          <form onSubmit={submit} style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
            {mode === 'register' && (
              <>
                <div className="field">
                  <label className="field-label">Full name</label>
                  <input className="input" value={name} onChange={(e) => setName(e.target.value)} placeholder="Your name"/>
                </div>
                <div className="field">
                  <label className="field-label">Email</label>
                  <input className="input" type="email" value={email} onChange={(e) => setEmail(e.target.value)} required/>
                </div>
                <div className="field">
                  <label className="field-label">Username</label>
                  <input className="input" value={username} onChange={(e) => setUsername(e.target.value)} required/>
                </div>
              </>
            )}
            {mode === 'login' && (
              <div className="field">
                <label className="field-label">Username or email</label>
                <input className="input" value={username} onChange={(e) => setUsername(e.target.value)} required autoFocus/>
              </div>
            )}
            <div className="field">
              <label className="field-label">Password</label>
              <input className="input" type="password" value={password} onChange={(e) => setPassword(e.target.value)} required/>
            </div>
            {info && (
              <div style={{ fontSize: 13, color: 'var(--pos)', background: 'var(--pos-soft)', padding: 10, borderRadius: 8 }}>{info}</div>
            )}
            {error && (
              <div style={{ fontSize: 13, color: 'var(--neg)', background: 'var(--neg-soft)', padding: 10, borderRadius: 8 }}>{error}</div>
            )}
            <button className="btn primary lg block" type="submit" disabled={loading}>
              {loading ? 'Working…' : mode === 'login' ? 'Sign in' : 'Create account'}
            </button>
          </form>

          <div style={{ textAlign: 'center', fontSize: 13, color: 'var(--ink-3)' }}>
            {mode === 'login' ? "Don't have an account? " : 'Already have an account? '}
            <a href="#" onClick={(e) => { e.preventDefault(); setMode(mode === 'login' ? 'register' : 'login'); setError(null); setInfo(null); }}
              style={{ color: 'var(--ink)', fontWeight: 600, textDecoration: 'none' }}>
              {mode === 'login' ? 'Sign up' : 'Sign in'}
            </a>
          </div>

          <div style={{ marginTop: 8, padding: 12, borderRadius: 12, background: 'var(--bg-soft)', fontSize: 11.5, color: 'var(--ink-3)', lineHeight: 1.5 }}>
            <b style={{ color: 'var(--ink-2)' }}>KYC required.</b> After signing up, you will need to fill in the KYC details. An admin will review and approve your account before trading is enabled.
          </div>
        </div>
      </div>
    </div>
  );
}

function Glyph() {
  return (
    <svg style={{ position: 'absolute', right: -120, top: -80, width: 520, opacity: 0.07, pointerEvents: 'none' }}
         viewBox="0 0 400 400">
      <defs>
        <linearGradient id="ag" x1="0" y1="0" x2="1" y2="1">
          <stop offset="0%" stopColor="white"/>
          <stop offset="100%" stopColor="var(--accent)"/>
        </linearGradient>
      </defs>
      <circle cx="200" cy="200" r="180" stroke="url(#ag)" strokeWidth="40" fill="none"/>
      <circle cx="200" cy="200" r="120" stroke="white" strokeWidth="2" fill="none"/>
      <circle cx="200" cy="200" r="60" fill="white"/>
    </svg>
  );
}

window.AuthScreen = AuthScreen;
