import { createRoot } from 'react-dom/client'
import App from './App.tsx'
import './index.css'

// Initialize analytics service early
import { analyticsService } from '@/lib/analytics'
import { configManager } from '@/lib/analytics/config'
// import { verifyAnalytics } from '@/lib/analytics/verify-analytics' // Remove this import

// Initialize analytics configuration
const initializeAnalytics = async () => {
  try {
    const config = await configManager.loadConfig()
    await analyticsService.initialize(config)
    
    if (config.environment === 'development') {
      console.log('Analytics service initialized in main.tsx with config:', config)
      // Run verification in development mode
      // setTimeout(() => {
      //   verifyAnalytics();
      // }, 3000);
    }
  } catch (error) {
    // Don't break app initialization if analytics fails
    if (process.env.NODE_ENV === 'development') {
      console.warn('Failed to initialize analytics in main.tsx:', error)
    }
  }
}

// Cleanup analytics on page unload
const handleBeforeUnload = () => {
  try {
    analyticsService.cleanup()
  } catch (error) {
    if (process.env.NODE_ENV === 'development') {
      console.warn('Error during analytics cleanup on page unload:', error)
    }
  }
}

// Add cleanup event listener
window.addEventListener('beforeunload', handleBeforeUnload)

// Initialize analytics before rendering the app
initializeAnalytics().then(() => {
  createRoot(document.getElementById("root")!).render(<App />)
})