'use client';

import { useAuth } from '@/lib/auth';
import { usePathname, useRouter } from 'next/navigation';
import { useEffect, type ReactNode } from 'react';

export default function AuthGuard({ children }: { children: ReactNode }) {
  const { user, isLoading } = useAuth();
  const router = useRouter();
  const pathname = usePathname();

  const isLoginPage = pathname === '/login' || pathname === '/sugerencias';

  useEffect(() => {
    if (!isLoginPage && !isLoading && !user) router.replace('/login');
  }, [user, isLoading, router, isLoginPage]);

  if (isLoginPage) return <>{children}</>;
  if (isLoading) return <div className="flex h-screen items-center justify-center text-muted-foreground">Cargando...</div>;
  if (!user) return null;

  return <>{children}</>;
}
