import { Navigate, Outlet, useLocation } from "react-router-dom";
import { Spinner } from "../components/ui/Spinner";
import { useAuth } from "./AuthContext";

/**
 * Gate for authenticated routes. While restoring a session from a stored token
 * we show a spinner (avoids a login-flash on reload). No user -> /login,
 * preserving the attempted location for post-login return.
 */
export function ProtectedRoute() {
  const { user, initializing } = useAuth();
  const location = useLocation();

  if (initializing) {
    return (
      <div className="auth-gate">
        <Spinner label="Restoring session" />
      </div>
    );
  }

  if (!user) {
    return <Navigate to="/login" replace state={{ from: location }} />;
  }

  return <Outlet />;
}
