import { Navigate, useLocation } from "react-router-dom";

import { useAuth } from "../state/auth";

export const ProtectedRoute = ({ children }: { children: React.ReactNode }) => {
  const { state } = useAuth();
  const location = useLocation();

  if (state === "loading") {
    return <div className="center-screen">Checking session...</div>;
  }

  if (state === "unauthenticated") {
    const nextPath = encodeURIComponent(location.pathname);
    return <Navigate to={`/login?next=${nextPath}`} replace />;
  }

  return <>{children}</>;
};
