// src/providers/MasterItemsProvider.tsx
import React, { ReactNode, useMemo, useEffect, useCallback } from 'react';
import { MasterItemsContext } from '../contexts/MasterItemsContext';
import type { MasterGroceryItem } from '../types';
import * as apiClient from '../services/apiClient';
import { useApiOnMount } from '../hooks/useApiOnMount';
import { logger } from '../services/logger.client';

export const MasterItemsProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
  // LOGGING: Check if the provider is unmounting/remounting repeatedly
  useEffect(() => {
    logger.debug('MasterItemsProvider: MOUNTED');
    return () => logger.debug('MasterItemsProvider: UNMOUNTED');
  }, []);

  // Memoize the fetch function to ensure stability for the useApiOnMount hook.
  const fetchFn = useCallback(() => apiClient.fetchMasterItems(), []);

  const { data, loading, error } = useApiOnMount<MasterGroceryItem[], []>(fetchFn);

  const value = useMemo(
    () => ({
      masterItems: data || [],
      isLoading: loading,
      error: error?.message || null,
    }),
    [data, loading, error],
  );

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