"use client";

import { useSession, signOut } from "next-auth/react";
import { usePathname, useRouter } from "next/navigation";
import { useEffect } from "react";

export function AuthCheck({ children }: { children: React.ReactNode }) {
  const { data: session, status } = useSession();
  const pathname = usePathname();
  const router = useRouter();

  useEffect(() => {
    // Handle authentication status changes
    if (status === "unauthenticated" && !pathname.includes("/signin")) {
      console.log("User is not authenticated, redirecting to signin page");
      router.push("/signin");
    }
    
    // Handle session errors (like refresh token failures)
    if (session?.error) {
      console.log(`Session error detected: ${session.error}, signing out`);
      // Force a clean sign out
      signOut({ 
        callbackUrl: `/signin?error=${encodeURIComponent(session.error)}`,
        redirect: true
      });
    }
  }, [status, session, router, pathname]);

  // Show loading state
  if (status === "loading") {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-blue-500 mx-auto"></div>
          <p className="mt-4 text-gray-600">Chargement...</p>
        </div>
      </div>
    );
  }

  // If not authenticated and not on signin page, don't render children
  if (status === "unauthenticated" && !pathname.includes("/signin")) {
    return null;
  }

  // Session has error, don't render children
  if (session?.error) {
    return null;
  }

  // Authentication is valid, render children
  return <>{children}</>;
} 