// app/components/auth/AuthWrapper.tsx
'use client';

import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';

interface AuthWrapperProps {
  children: React.ReactNode;
  redirectPath?: string;
}

export function AuthWrapper({ 
  children, 
  redirectPath = '/login' 
}: AuthWrapperProps) {
  const router = useRouter();
  const [isAuthenticated, setIsAuthenticated] = useState(false);

  useEffect(() => {
    const checkAuth = () => {
      const cookies = document.cookie.split('; ');
      const tokenCookie = cookies.find(row => row.startsWith('token='));
      const token = tokenCookie ? tokenCookie.split('=')[1] : null;
      
      if (!token) {
        router.push(redirectPath);
      } else {
        setIsAuthenticated(true);
      }
    };

    checkAuth();
  }, [router, redirectPath]);

  if (!isAuthenticated) {
    return (
      <div className="flex items-center justify-center min-h-screen bg-[#E0EBF6]">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500 mx-auto"></div>
          <p className="mt-4 text-gray-600">Loading...</p>
        </div>
      </div>
    );
  }

  return <>{children}</>;
}