'use client';

import { useEffect } from 'react';
import { useRouter, usePathname } from 'next/navigation';
import { useAuthStore } from '@/store/authStore';
import { Loader2 } from 'lucide-react';

interface ProtectedRouteProps {
  children: React.ReactNode;
}

/**
 * Client-side Protected Route Component
 *
 * This component provides an additional layer of protection on top of middleware.
 * It checks authentication status and redirects if not authenticated.
 */
export function ProtectedRoute({ children }: ProtectedRouteProps) {
  const router = useRouter();
  const pathname = usePathname();
  const { status, isLoading, hasHydrated } = useAuthStore();

  useEffect(() => {
    // Only redirect after hydration is complete
    if (hasHydrated && !isLoading && status === 'anonymous') {
      // Redirect to login with return URL
      const loginUrl = `/login?redirect=${encodeURIComponent(pathname)}`;
      router.push(loginUrl);
    }
  }, [status, isLoading, hasHydrated, router, pathname]);

  // Show loading state while hydrating or checking authentication
  if (!hasHydrated || isLoading || status === 'idle') {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <Loader2 className="h-8 w-8 animate-spin text-primary" />
      </div>
    );
  }

  // Only render children if authenticated
  if (status !== 'authenticated') {
    return null;
  }

  return <>{children}</>;
}

export default ProtectedRoute;
