'use client';

import { useEffect, useRef, useState } from 'react';
import { Provider } from 'react-redux';
import { PersistGate } from 'redux-persist/integration/react';
import { store, persistor } from '@/store/store';
import { setupNetworkDetection } from '@/store/middleware/offlineMiddleware';
import { CircularProgress, Box } from '@mui/material';

export function ReduxProvider({ children }: { children: React.ReactNode }) {
  const cleanupRef = useRef<(() => void) | null>(null);
  const [isClient, setIsClient] = useState(false);

  useEffect(() => {
    setIsClient(true);

    // Setup network detection
    cleanupRef.current = setupNetworkDetection(store.dispatch);

    // Cleanup on unmount
    return () => {
      if (cleanupRef.current) {
        cleanupRef.current();
      }
    };
  }, []);

  return (
    <Provider store={store}>
      <PersistGate
        loading={
          isClient ? (
            <Box
              sx={{
                display: 'flex',
                justifyContent: 'center',
                alignItems: 'center',
                minHeight: '100vh'
              }}
            >
              <CircularProgress />
            </Box>
          ) : null
        }
        persistor={persistor}
      >
        {children}
      </PersistGate>
    </Provider>
  );
}
