import "./instrument"; // Sentry must init before any other imports

import posthog from 'posthog-js'
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import { reactErrorHandler } from '@sentry/react'
import { HelmetProvider } from 'react-helmet-async'
import { PostHogProvider } from '@posthog/react'
import { Toaster } from 'sonner'
import './index.css'
import App from './App'

// Initialize PostHog client before rendering
const posthogKey = import.meta.env.VITE_PUBLIC_POSTHOG_KEY as string | undefined
if (posthogKey) {
  posthog.init(posthogKey, {
    api_host: (import.meta.env.VITE_PUBLIC_POSTHOG_HOST as string) || 'https://us.i.posthog.com',
    autocapture: true,
    capture_pageview: true,
    capture_pageleave: 'if_capture_pageview',
    persistence: 'localStorage+cookie',
  })
}

createRoot(document.getElementById('root')!, {
  onUncaughtError: reactErrorHandler(),
  onCaughtError: reactErrorHandler(),
  onRecoverableError: reactErrorHandler(),
}).render(
  <StrictMode>
    <PostHogProvider client={posthog}>
      <HelmetProvider>
        {/* Toast notification system - theme syncs automatically via CSS custom properties */}
        <Toaster
          position="top-right"
          expand={false}
          closeButton
          visibleToasts={3}
          gap={8}
          theme="dark"
          toastOptions={{
            className: 'sonner-toast-custom',
          }}
        />
        <App />
      </HelmetProvider>
    </PostHogProvider>
  </StrictMode>,
)
