import { Navigate, Outlet, useLocation } from "react-router-dom";
import { useClientSession } from "../hooks/useClientSession";

export function ClientAuthGate() {
  const location = useLocation();
  const { data: client, isLoading } = useClientSession();

  if (client) {
    return <Outlet />;
  }

  if (isLoading) {
    return (
      <div className="flex min-h-screen items-center justify-center bg-background">
        <div className="h-8 w-8 animate-spin rounded-full border-b-2 border-primary" />
      </div>
    );
  }

  const redirectUrl = `${location.pathname}${location.search}${location.hash}`;
  localStorage.setItem("clients.redirectUrl", redirectUrl);

  return <Navigate to="/login" replace />;
}
