"use client";

import { useEffect, ReactNode } from "react";
import { useRouter } from "next/navigation";
import { useAuth } from "@/components/auth/auth-provider";

function FullScreenLoader() {
  return (
    <div className="flex min-h-screen items-center justify-center bg-ink">
      <div className="h-10 w-10 animate-spin rounded-full border-4 border-white/20 border-t-brand-400" />
    </div>
  );
}

export function RouteGuard({ children }: { children: ReactNode }) {
  const { isAuthenticated, isLoading } = useAuth();
  const router = useRouter();

  useEffect(() => {
    if (!isLoading && !isAuthenticated) {
      const next = encodeURIComponent(window.location.pathname);
      router.replace(`/login?next=${next}`);
    }
  }, [isLoading, isAuthenticated, router]);

  if (isLoading) return <FullScreenLoader />;
  if (!isAuthenticated) return <FullScreenLoader />;

  return <>{children}</>;
}
