"use client";

import { useEffect } from "react";
import { onAuthStateChanged } from "firebase/auth";
import { auth } from "@/lib/firebase";
import { useAppDispatch } from "@/store/hooks";
import { validateAuth } from "@/store/slices/authSlice";

/**
 * Listens for Firebase Auth session loss (token expired, signed out externally)
 * and syncs Redux auth state accordingly.
 * Firebase manages its own session restoration on page reload — no manual re-sign-in needed.
 */
export function FirebaseAuthSync() {
  const dispatch = useAppDispatch();

  useEffect(() => {
    const unsub = onAuthStateChanged(auth, (firebaseUser) => {
      if (!firebaseUser) {
        // Firebase session gone — validate Redux state to clear stale auth
        dispatch(validateAuth());
      }
    });
    return () => unsub();
  }, [dispatch]);

  return null;
}
