import React, { useState } from 'react';
import ReactDOM from 'react-dom/client';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { trpc, createTRPCClient } from './lib/trpc';
import { createMutationCache } from './lib/invalidation';
import { ThemeProvider } from './lib/theme';
import { TooltipProvider } from './components/ui/tooltip';
import App from './App';
import './index.css';

function Root() {
  const [queryClient] = useState(() => {
    // We need a reference to the QueryClient inside createMutationCache,
    // but it doesn't exist yet. Create a lazy holder.
    let qc: QueryClient;
    const mutationCache = createMutationCache(() => qc);
    qc = new QueryClient({
      mutationCache,
      defaultOptions: {
        queries: {
          refetchOnWindowFocus: false,
          retry: 1,
        },
      },
    });
    return qc;
  });
  const [trpcClient] = useState(createTRPCClient);

  return (
    <ThemeProvider>
      <TooltipProvider delayDuration={300}>
        <trpc.Provider client={trpcClient} queryClient={queryClient}>
          <QueryClientProvider client={queryClient}>
            <App />
          </QueryClientProvider>
        </trpc.Provider>
      </TooltipProvider>
    </ThemeProvider>
  );
}

ReactDOM.createRoot(document.getElementById('root')!).render(
  <React.StrictMode>
    <Root />
  </React.StrictMode>
);
