import { useEffect, useRef, useState } from 'react';

const GIS_SRC = 'https://accounts.google.com/gsi/client';
const CLIENT_ID = import.meta.env.VITE_GOOGLE_CLIENT_ID;

// Load the Google Identity Services script once and share the promise.
let gisPromise;
function loadGis() {
  if (window.google?.accounts?.id) return Promise.resolve();
  if (!gisPromise) {
    gisPromise = new Promise((resolve, reject) => {
      const s = document.createElement('script');
      s.src = GIS_SRC;
      s.async = true;
      s.defer = true;
      s.onload = resolve;
      s.onerror = () => {
        gisPromise = undefined; // allow a retry on next mount
        reject(new Error('Failed to load Google sign-in'));
      };
      document.head.appendChild(s);
    });
  }
  return gisPromise;
}

/**
 * Renders Google's official "Sign in with Google" button.
 * Calls `onCredential(idToken)` with the Google ID token when the user signs in.
 * Renders nothing if VITE_GOOGLE_CLIENT_ID is not configured or the script fails.
 *
 * NOTE: `onCredential` should be memoized (useCallback) by the parent so the
 * button isn't torn down and re-rendered on every keystroke.
 */
export default function GoogleSignInButton({ onCredential, text = 'continue_with' }) {
  const ref = useRef(null);
  const [failed, setFailed] = useState(false);

  useEffect(() => {
    if (!CLIENT_ID) return undefined;
    let cancelled = false;

    loadGis()
      .then(() => {
        if (cancelled || !ref.current) return;
        window.google.accounts.id.initialize({
          client_id: CLIENT_ID,
          callback: (resp) => resp?.credential && onCredential(resp.credential),
        });
        ref.current.innerHTML = '';
        window.google.accounts.id.renderButton(ref.current, {
          type: 'standard',
          theme: 'outline',
          size: 'large',
          text, // 'continue_with' | 'signin_with' | 'signup_with'
          shape: 'rectangular',
          logo_alignment: 'center',
          width: 320,
        });
      })
      .catch(() => !cancelled && setFailed(true));

    return () => {
      cancelled = true;
    };
  }, [onCredential, text]);

  if (!CLIENT_ID || failed) return null;
  return <div className="google-btn-wrap" ref={ref} />;
}
