import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import ErrorBoundary from './components/ErrorBoundary';
import { ErrorNotificationProvider } from './components/ErrorNotificationProvider';
import './i18n';
import './index.css';
import './api/axiosConfig'; // Setup axios interceptors

// Global error handlers (CWE-391 protection)
// Handle unhandled promise rejections
window.addEventListener('unhandledrejection', (event) => {
  event.preventDefault(); // Prevent default browser console error
  
  if (process.env.NODE_ENV !== 'production') {
    console.error('Unhandled promise rejection:', event.reason);
  }
  
  // Log to error tracking service in production
  // trackError(event.reason);
});

// Handle global errors
window.addEventListener('error', (event) => {
  event.preventDefault(); // Prevent default browser console error
  
  if (process.env.NODE_ENV !== 'production') {
    console.error('Global error:', event.error || event.message);
  }
  
  // Log to error tracking service in production
  // trackError(event.error || event.message);
});

// Register Service Worker for PWA
if ('serviceWorker' in navigator) {
  window.addEventListener('load', () => {
    navigator.serviceWorker
      .register('/service-worker.js')
      .then((registration) => {
        // Service worker registered successfully
        if (process.env.NODE_ENV !== 'production') {
          console.log('SW registered:', registration);
        }
      })
      .catch((error) => {
        // Service worker registration failed - log only in development
        if (process.env.NODE_ENV !== 'production') {
          console.log('SW registration failed:', error);
        }
      });
  });
}

ReactDOM.createRoot(document.getElementById('root')).render(
  <React.StrictMode>
    <ErrorBoundary>
      <ErrorNotificationProvider>
        <App />
      </ErrorNotificationProvider>
    </ErrorBoundary>
  </React.StrictMode>
);
