// src/providers/ModalProvider.tsx
import React, { useState, useMemo, useCallback } from 'react';
import { ModalContext, ModalContextType, ModalType } from '../contexts/ModalContext';

/**
 * The provider component that will wrap the application.
 * It holds the state for all modals and provides functions to control them.
 */
export const ModalProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const [modalState, setModalState] = useState<Record<ModalType, boolean>>({
    profile: false,
    voiceAssistant: false,
    whatsNew: false,
    correctionTool: false,
  });

  const openModal = useCallback((modal: ModalType) => setModalState(prev => ({ ...prev, [modal]: true })), []);
  const closeModal = useCallback((modal: ModalType) => setModalState(prev => ({ ...prev, [modal]: false })), []);
  const isModalOpen = useCallback((modal: ModalType) => modalState[modal], [modalState]);

  // useMemo ensures the context value object is stable across re-renders,
  // preventing unnecessary re-renders of consumer components.
  const value: ModalContextType = useMemo(() => ({ openModal, closeModal, isModalOpen }), [openModal, closeModal, isModalOpen]);

  return <ModalContext.Provider value={value}>{children}</ModalContext.Provider>;
};