import type { ReactNode } from "react";
import { Navigate, useLocation } from "react-router-dom";
import { authStore } from "@/store/authStore";

interface PrivateRouteProps {
  children: ReactNode;
}

/** Guards authenticated routes; redirects unauthenticated users to /login. */
export function PrivateRoute({ children }: PrivateRouteProps) {
  const accessToken = authStore.useStore((s) => s.accessToken);
  const authReady = authStore.useStore((s) => s.authReady);
  const location = useLocation();

  if (!authReady) {
    return (
      <div className="flex min-h-screen items-center justify-center text-slate-500">
        …
      </div>
    );
  }

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

  return <>{children}</>;
}
