import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import { QueryClientProvider } from '@tanstack/react-query'
import { RouterProvider } from 'react-router-dom'
import { Toaster } from 'sonner'
import { queryClient } from '@/lib/queryClient'
import { router } from '@/router'
import { ErrorBoundary } from '@/components/ErrorBoundary'
import { initSentry } from '@/lib/sentry'
import { initTheme } from '@/lib/theme'
import './index.css'

// Initialise telemetry before any other setup so React errors during
// initial render are captured. No-op when VITE_SENTRY_DSN is unset.
initSentry()
// Apply the persisted light/dark preference to <html> before first
// paint so there's no flash of the wrong theme.
initTheme()

createRoot(document.getElementById('root')!).render(
  <StrictMode>
    <ErrorBoundary>
      <QueryClientProvider client={queryClient}>
        <RouterProvider router={router} />
        {/* Toaster lives outside the router so toasts survive route changes. */}
        <Toaster
          theme="dark"
          richColors
          position="top-right"
          closeButton
          toastOptions={{
            // Match the panel + border tokens used elsewhere.
            style: {
              background: 'var(--color-panel)',
              border: '1px solid var(--color-border-dark)',
              color: 'var(--color-text-on-dark)',
            },
          }}
        />
      </QueryClientProvider>
    </ErrorBoundary>
  </StrictMode>,
)
