'use client';

import { QueryClient, QueryClientProvider as TanstackQueryClientProvider } from '@tanstack/react-query';
import { ReactNode, useState } from 'react';

interface QueryClientProviderProps {
  children: ReactNode;
}

/**
 * Provides React Query client to the application
 * 
 * Must wrap any components that use React Query hooks (useQuery, useMutation, etc.)
 * Creates a new QueryClient instance per component tree to avoid state sharing
 */
export function QueryClientProvider({ children }: QueryClientProviderProps) {
  // Create a new QueryClient instance for each component tree
  // This prevents state sharing between different renders
  const [queryClient] = useState(
    () =>
      new QueryClient({
        defaultOptions: {
          queries: {
            // Disable automatic refetching in production for better performance
            refetchOnWindowFocus: process.env.NODE_ENV === 'development',
            refetchOnReconnect: true,
            retry: 1,
            staleTime: 5 * 60 * 1000, // 5 minutes
          },
          mutations: {
            retry: 0,
          },
        },
      })
  );

  return (
    <TanstackQueryClientProvider client={queryClient}>
      {children}
    </TanstackQueryClientProvider>
  );
}
