'use client';

import { useEffect, useRef } from 'react';
import { useRouter } from 'next/navigation';
import { useSelector } from 'react-redux';
import { useLocale } from 'next-intl';
import { RootState } from '@/store/store';
import Loading from '@/components/loading';

interface ProtectedRouteProps {
  children: React.ReactNode;
}

export function ProtectedRoute({ children }: ProtectedRouteProps) {
  const router = useRouter();
  const locale = useLocale();
  const { isAuthenticated, user, accessToken, isInitialized } = useSelector((state: RootState) => state.auth as AuthState & { isInitialized?: boolean });

  useEffect(() => {
    // Wait until the auth app initialization sequence has finished
    if (!isInitialized) return;

    // Only redirect if effectively unauthenticated
    if (!isAuthenticated && !user && !accessToken) {
      router.replace(`/${locale}/login`);
    }
  }, [isInitialized, isAuthenticated, user, accessToken, router, locale]);

  // Show loading while initial auth state is being determined
  if (!isInitialized) {
    return <Loading fullScreen={true} variant="spinner" size="xl" />;
  }

  // If we have any sign of authentication (user data, token, or flag), render children
  if (isAuthenticated || user || accessToken) {
    return <>{children}</>;
  }

  // Fallback: don't render anything (redirect will happen from useEffect)
  return null;
}

