import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import { GraphProvider } from './contexts/GraphContext'
import { UIStateProvider } from './contexts/UIStateContext'
import './index.css'
import App from './App.tsx'
import { isChunkLoadError, handleChunkLoadError } from './components/common/LazyLoadError'

/**
 * Global error handler for uncaught errors, especially chunk loading failures.
 * 
 * This catches errors that occur:
 * 1. During dynamic import before React mounts
 * 2. In async code outside of React's error boundary
 * 3. During router initialization
 * 
 * When a chunk load error is detected, we clear caches and reload.
 */
window.addEventListener('error', (event) => {
  if (event.error && isChunkLoadError(event.error)) {
    console.warn('[GlobalErrorHandler] Chunk load error detected, reloading...', event.error.message);
    event.preventDefault(); // Prevent the ugly default error UI
    handleChunkLoadError();
  }
});

/**
 * Handle unhandled promise rejections (e.g., failed dynamic imports)
 */
window.addEventListener('unhandledrejection', (event) => {
  if (event.reason && isChunkLoadError(event.reason)) {
    console.warn('[GlobalErrorHandler] Chunk load rejection detected, reloading...', event.reason.message);
    event.preventDefault();
    handleChunkLoadError();
  }
});

/**
 * Vite-specific: Handle module loading errors during HMR
 * This catches the "Failed to fetch dynamically imported module" errors
 */
if (import.meta.hot) {
  import.meta.hot.on('vite:error', (payload) => {
    if (payload.err?.message?.includes('dynamically imported module')) {
      console.warn('[HMR] Chunk error during HMR, triggering full reload');
      window.location.reload();
    }
  });
}

createRoot(document.getElementById('root')!).render(
  <StrictMode>
    <UIStateProvider>
      <GraphProvider>
        <App />
      </GraphProvider>
    </UIStateProvider>
  </StrictMode>,
)
