"use client"; import { useEffect } from "react"; import { useRouter } from "next/navigation"; import { useAuth } from "@/hooks/useAuth"; import { currentPage } from "@/lib/signIn"; /** * Use inside any client component that requires authentication. * Returns `ready: true` only once auth has resolved and the user is confirmed. * While loading or unauthenticated, `ready` is false — render null to prevent flash. * * @example * const { ready, user, token } = useRequireAuth(); * if (!ready) return null; */ export function useRequireAuth(redirectTo = "/login") { const { user, token, loading } = useAuth(); const router = useRouter(); useEffect(() => { if (loading) return; // Back to this exact page after signing in (3.0.0: through the church's Accounts, which // `/login` forwards to). if (!user) router.replace(redirectTo === "/login" ? `/login?redirect=${encodeURIComponent(currentPage())}` : redirectTo); }, [user, loading, router, redirectTo]); const ready = !loading && !!user; return { ready, user, token, loading }; }