import React, { useEffect } from 'react';
import { useAuthModal } from '../contexts/AuthModalContext';
import LoginModal from './LoginModal';
import RegisterModal from './RegisterModal';
import ForgotPasswordModal from './ForgotPasswordModal';
import ResetPasswordModal from './ResetPasswordModal';
import useAuthStore from '../../../store/useAuthStore';

const AuthModalManager: React.FC = () => {
  const { isOpen, modalType, resetPasswordParams, openModal } = useAuthModal();
  const { isAuthenticated } = useAuthStore();

  // Listen for auth:logout event from apiClient
  useEffect(() => {
    const handleAuthLogout = () => {
      if (!isAuthenticated) {
        openModal('login');
      }
    };

    window.addEventListener('auth:logout', handleAuthLogout as EventListener);
    return () => {
      window.removeEventListener('auth:logout', handleAuthLogout as EventListener);
    };
  }, [openModal, isAuthenticated]);

  if (!isOpen) {
    return null;
  }

  switch (modalType) {
    case 'login':
      return <LoginModal />;
    case 'register':
      return <RegisterModal />;
    case 'forgot-password':
      return <ForgotPasswordModal />;
    case 'reset-password':
      return resetPasswordParams?.token ? <ResetPasswordModal token={resetPasswordParams.token} /> : null;
    default:
      return null;
  }
};

export default AuthModalManager;

