"use client";

import React, { useEffect } from "react";
import { useRouter, usePathname } from "next/navigation";
import { useAuth } from "@/hooks/useAuth";

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

  useEffect(() => {
    if (!loading) {
      // If user is not authenticated and not on a public page, redirect to login
      if (!user && !pathname.startsWith("/login") && !pathname.startsWith("/register")) {
        router.push("/login");
      }
    }
  }, [user, loading, router, pathname]);

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-screen bg-background">
        <div className="text-primary font-display text-2xl animate-pulse">A carregar...</div>
      </div>
    );
  }

  // If not authenticated and not on a public page, don't render children
  // (the useEffect will redirect)
  if (!user && !pathname.startsWith("/login") && !pathname.startsWith("/register")) {
    return null;
  }

  return <>{children}</>;
}
