'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: false,
            refetchOnReconnect: true,
            retry: 1,
            staleTime: 10 * 60 * 1000, // 10 minutes
          },
          mutations: {
            retry: 0,
          },
        },
      })
  );

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