import type { ReactNode } from "react";
import { Navigate } from "react-router-dom";
import { useAuth } from "./AuthContext";

/**
 * Route guard for pages that require an authenticated session (e.g. the
 * home page). Renders nothing while the initial session check is pending,
 * to avoid a flash-then-redirect; once resolved, either renders `children`
 * or redirects to `/login`.
 */
export function RequireAuth({ children }: { children: ReactNode }) {
  const { user, isLoading } = useAuth();

  if (isLoading) {
    // Initial GET /auth/me still in flight — don't redirect yet, we don't
    // know the auth state.
    return null;
  }
  if (!user) {
    return <Navigate to="/login" replace />;
  }
  return <>{children}</>;
}
