'use client';

import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { ReactQueryDevtools } from '@tanstack/react-query-devtools';
import { broadcastQueryClient } from '@tanstack/query-broadcast-client-experimental';
import { useEffect, useState, type ReactNode } from 'react';

export function QueryProvider({ children }: { children: ReactNode }) {
  const [queryClient] = useState(
    () =>
      new QueryClient({
        defaultOptions: {
          queries: {
            staleTime: 30 * 1000,
            retry: 1,
            refetchOnWindowFocus: false,
          },
          mutations: {
            onError: (error) => {
              console.error('Mutation error:', error);
            },
          },
        },
      }),
  );

  // Sync cache across tabs via BroadcastChannel. When a rep updates a
  // client in tab A, tab B's cached query invalidates instantly without
  // a server roundtrip. Runs in browser only.
  useEffect(() => {
    if (typeof window === 'undefined') return;
    broadcastQueryClient({ queryClient, broadcastChannel: 'pn-crm' });
  }, [queryClient]);

  return (
    <QueryClientProvider client={queryClient}>
      {children}
      {process.env.NODE_ENV === 'development' && <ReactQueryDevtools initialIsOpen={false} />}
    </QueryClientProvider>
  );
}
