/* useAuth hook + sign-in helpers.
   Waits for firebase-init.js (loaded as ES module) to populate window.fb,
   then subscribes to auth state changes. */
{
  const { useEffect, useState, useCallback } = React;

  function useAuth() {
    const [ready, setReady] = useState(() => !!window.fb);
    const [user, setUser] = useState(null);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);

    useEffect(() => {
      if (ready) return;
      function onReady() { setReady(true); }
      window.addEventListener("fb-ready", onReady);
      // Safety net: if fb arrived between render and effect.
      if (window.fb) setReady(true);
      return () => window.removeEventListener("fb-ready", onReady);
    }, [ready]);

    useEffect(() => {
      if (!ready) return;
      const fb = window.fb;
      const unsub = fb.onAuthStateChanged(fb.auth, (u) => {
        setUser(u ? {
          uid: u.uid,
          displayName: u.displayName || u.email || "anonymous",
          email: u.email || "",
          photoURL: u.photoURL || "",
        } : null);
        setLoading(false);
      });
      return () => unsub();
    }, [ready]);

    const signIn = useCallback(async () => {
      if (!window.fb) return;
      setError(null);
      try {
        const provider = new window.fb.GoogleAuthProvider();
        provider.setCustomParameters({ prompt: "select_account" });
        await window.fb.signInWithPopup(window.fb.auth, provider);
      } catch (e) {
        if (e.code === "auth/popup-closed-by-user" || e.code === "auth/cancelled-popup-request") return;
        setError(e.message || String(e));
      }
    }, []);

    const signOutFn = useCallback(async () => {
      if (!window.fb) return;
      try { await window.fb.signOut(window.fb.auth); } catch { /* noop */ }
    }, []);

    return { user, loading: loading || !ready, error, signIn, signOut: signOutFn };
  }

  window.useAuth = useAuth;
}
