import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import { RouterProvider } from 'react-router-dom';
import { toast } from 'sonner';

import { UserProvider } from '@/contexts/UserContext';
import { SocketProvider } from '@/socket';
import { env } from '@/lib/env';
import { router } from './routes';
import './index.css';

const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      throwOnError: true,
      staleTime: 1000 * 60,
      retry: 1,
    },
    mutations: {
      onError: (error) => {
        toast.error(error.message);
      },
    },
  },
});

const doc = document.getElementById('root');
if (!doc) {
  throw new Error('Root element not found');
}

createRoot(doc).render(
  <StrictMode>
    <QueryClientProvider client={queryClient}>
      <UserProvider>
        <SocketProvider imksUrl={env.IMKS_URL}>
          <RouterProvider router={router} />
        </SocketProvider>
      </UserProvider>
    </QueryClientProvider>
  </StrictMode>,
);
