import React from 'react';
import { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { checkAuthStatus } from './authSlice';
import type { RootState, AppDispatch } from '../../store/store';

interface AuthInitializerProps {
  children: React.ReactNode;
}

/**
 * AuthInitializer Component
 * Initializes authentication state from Firebase persistence on app load
 * Shows a loading screen until the initial auth check is complete
 * This prevents premature redirect to login before the persisted session is restored
 */
const AuthInitializer: React.FC<AuthInitializerProps> = ({ children }) => {
  const dispatch = useDispatch<AppDispatch>();
  const { isInitialized } = useSelector((state: RootState) => state.auth);

  useEffect(() => {
    // Perform initial auth check when component mounts
    // This restores the persisted session from Firebase
    dispatch(checkAuthStatus());
  }, [dispatch]);

  // Show loading state while initializing auth
  if (!isInitialized) {
    return (
      <div className="flex items-center justify-center h-screen bg-slate-50">
        <div className="text-center">
          <div className="inline-block">
            <div className="w-8 h-8 border-4 border-slate-200 border-t-primary rounded-full animate-spin"></div>
          </div>
          <p className="mt-4 text-slate-600">Loading application...</p>
        </div>
      </div>
    );
  }

  return <>{children}</>;
};

export default AuthInitializer;
