/* =====================================================================
   LoginScreen — Pantalla de login (correo+clave o Google Identity)
   Usa la misma tabla `users` del Panel de Control. Solo rol master.
   ===================================================================== */

function LoginScreen({ onLogin }) {
  const [email, setEmail]             = useState('');
  const [password, setPassword]       = useState('');
  const [err, setErr]                 = useState('');
  const [loading, setLoading]         = useState(false);
  const [googleReady, setGoogleReady] = useState(false);
  const googleBtnRef                  = useRef(null);

  // Inicializar Google Identity Services
  useEffect(() => {
    let attempts = 0;
    const initGoogle = () => {
      if (typeof google !== 'undefined' && google.accounts) {
        fetch('/api/config/google-client-id').then(r => r.json()).then(cfg => {
          if (!cfg.clientId) return;
          google.accounts.id.initialize({
            client_id: cfg.clientId,
            callback:  handleGoogleResponse,
          });
          if (googleBtnRef.current) {
            google.accounts.id.renderButton(googleBtnRef.current, {
              theme: 'outline', size: 'large', width: 288, text: 'signin_with',
              logo_alignment: 'center',
            });
          }
          setGoogleReady(true);
        });
      } else if (attempts < 20) {
        attempts++;
        setTimeout(initGoogle, 300);
      }
    };
    initGoogle();
  }, []);

  const handleGoogleResponse = async (response) => {
    setErr(''); setLoading(true);
    try {
      const r = await fetch('/api/auth/google-login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
        body: JSON.stringify({ credential: response.credential }),
      });
      const data = await r.json();
      if (!r.ok) throw new Error(data.error || 'Error con Google');
      onLogin(data.user);
    } catch (e) {
      setErr(e.message);
    } finally {
      setLoading(false);
    }
  };

  const submit = async (e) => {
    e.preventDefault();
    setErr(''); setLoading(true);
    try {
      const r = await fetch('/api/auth/login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
        body: JSON.stringify({ email, password }),
      });
      const data = await r.json();
      if (!r.ok) throw new Error(data.error || 'Error de autenticación');
      onLogin(data.user);
    } catch (e) {
      setErr(e.message);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="login-wrap">
      <form className="login-card" onSubmit={submit}>
        <img src={LOGO} alt="Veliantex" style={{ display:"block", height:40, margin:"0 auto 16px", borderRadius:4 }} />
        <h2>Cotizador Veliantex</h2>
        <p>Solo usuarios master — Ingresa con tu cuenta</p>
        {err && <div className="login-err" style={{ display:"block" }}>{err}</div>}
        <div ref={googleBtnRef} style={{ marginBottom: googleReady ? 16 : 0 }}></div>
        {googleReady && <div style={{ textAlign:"center", fontSize:11, color:"#9ca3af", margin:"-8px 0 12px" }}>o ingresa con correo y contraseña</div>}
        <label>Correo</label>
        <input type="email" value={email} onChange={e => setEmail(e.target.value)} required autoFocus />
        <label>Contraseña</label>
        <input type="password" value={password} onChange={e => setPassword(e.target.value)} required />
        <button type="submit" disabled={loading}>{loading ? 'Ingresando...' : 'Ingresar'}</button>
      </form>
    </div>
  );
}

// ── Exports a global scope (Babel standalone aisla cada <script>) ──
window.LoginScreen = LoginScreen;
