'use client';

import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { useState, ReactNode, useEffect } from 'react';
import { Toaster } from 'sonner';
import { ThemeProvider } from './ThemeProvider';
import { ErrorBoundary } from './ErrorBoundary';
import { clientLogger } from '@/lib/utils/client-logger';
import { initGlobalErrorHandlers } from '@/lib/utils/global-error-handler';

export function Providers({ children }: { children: ReactNode }) {
  const [queryClient] = useState(
    () =>
      new QueryClient({
        defaultOptions: {
          queries: {
            staleTime: 3 * 1000, // 3 seconds for real-time feel
            refetchOnWindowFocus: false,
            retry: 2,
          },
          mutations: {
            retry: 1,
          },
        },
        logger: {
          log: (message) => clientLogger.debug(message),
          warn: (message) => clientLogger.warn(message),
          error: (error) => clientLogger.error('React Query error', error),
        },
      })
  );

  // Initialize global error handlers once
  useEffect(() => {
    initGlobalErrorHandlers();
  }, []);

  return (
    <ErrorBoundary>
      <ThemeProvider>
        <QueryClientProvider client={queryClient}>
          {children}
          <Toaster position="top-right" richColors closeButton />
        </QueryClientProvider>
      </ThemeProvider>
    </ErrorBoundary>
  );
}
