// frontend/main.jsx
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App.jsx';

// Cache management and error handling for dynamic imports
const setupErrorHandling = () => {
  // Detect when chunks fail to load and reload
  window.addEventListener('error', (event) => {
    const { message, filename, source } = event;
    
    // Check if it's a chunk loading error
    if (
      message?.includes('Loading chunk') ||
      message?.includes('Loading CSS chunk') ||
      message?.includes('Failed to fetch dynamically imported module') ||
      filename?.includes('/assets/') ||
      source?.includes('/assets/')
    ) {
      console.warn('Chunk loading failed, attempting reload:', {
        message,
        filename,
        source
      });
      
      // Show user-friendly message
      const existingMessage = document.getElementById('chunk-error-message');
      if (!existingMessage) {
        const errorDiv = document.createElement('div');
        errorDiv.id = 'chunk-error-message';
        errorDiv.style.cssText = `
          position: fixed;
          top: 20px;
          right: 20px;
          background: #ff6b6b;
          color: white;
          padding: 15px;
          border-radius: 5px;
          z-index: 10000;
          max-width: 300px;
          box-shadow: 0 4px 6px rgba(0,0,0,0.1);
        `;
        errorDiv.innerHTML = `
          <strong>Loading Error</strong><br>
          Refreshing page in 3 seconds...<br>
          <button onclick="window.location.reload()" style="
            background: white;
            color: #ff6b6b;
            border: none;
            padding: 5px 10px;
            border-radius: 3px;
            margin-top: 5px;
            cursor: pointer;
          ">Refresh Now</button>
        `;
        document.body.appendChild(errorDiv);
      }
      
      // Clear any cached versions
      if ('caches' in window) {
        caches.keys().then(cacheNames => {
          cacheNames.forEach(cacheName => {
            caches.delete(cacheName);
          });
        });
      }
      
      // Clear localStorage that might contain stale module info
      try {
        const keysToRemove = [];
        for (let i = 0; i < localStorage.length; i++) {
          const key = localStorage.key(i);
          if (key && (key.includes('vite') || key.includes('chunk'))) {
            keysToRemove.push(key);
          }
        }
        keysToRemove.forEach(key => localStorage.removeItem(key));
      } catch (e) {
        console.warn('Could not clear localStorage:', e);
      }
      
      // Reload the page after a short delay
      setTimeout(() => {
        window.location.reload();
      }, 3000);
      
      // Prevent the error from propagating further
      event.preventDefault();
      return false;
    }
  });

  // Handle unhandled promise rejections (often from dynamic imports)
  window.addEventListener('unhandledrejection', (event) => {
    if (
      event.reason?.message?.includes('Failed to fetch dynamically imported module') ||
      event.reason?.message?.includes('Loading chunk')
    ) {
      console.warn('Unhandled chunk loading rejection:', event.reason);
      event.preventDefault(); // Prevent console error
      
      // Trigger the same recovery as above
      setTimeout(() => {
        window.location.reload();
      }, 2000);
    }
  });

  // Enhanced fetch wrapper for better error handling
  const originalFetch = window.fetch;
  window.fetch = function(...args) {
    return originalFetch.apply(this, args).catch(error => {
      // Log fetch failures for assets
      if (args[0] && typeof args[0] === 'string' && args[0].includes('/assets/')) {
        console.error('Asset fetch failed:', args[0], error);
      }
      throw error;
    });
  };
};

// Preload critical chunks when the app starts
const preloadCriticalChunks = async () => {
  try {
    // Try to get the manifest file
    const response = await fetch('/.vite/manifest.json'); // was /manifest.json
    if (response.ok) {
      const manifest = await response.json();
      
      // Critical components that should be preloaded
      const criticalComponents = [
        'Home',
        'Login', 
        'FreeRegistration',
        'Campsite',
        'Booking'
      ];
      
      // Preload chunks that are likely to be needed
      Object.entries(manifest).forEach(([key, value]) => {
        if (criticalComponents.some(comp => key.includes(comp))) {
          const link = document.createElement('link');
          link.rel = 'modulepreload';
          link.href = value.file || value;
          link.onload = () => console.log('Preloaded:', key);
          link.onerror = () => console.warn('Failed to preload:', key);
          document.head.appendChild(link);
        }
      });
    }
  } catch (error) {
    console.warn('Could not preload critical chunks:', error);
  }
};

// Initialize everything
const initializeApp = () => {
  setupErrorHandling();
  preloadCriticalChunks();
  
  // Render the app
  const root = ReactDOM.createRoot(document.getElementById("app"));
  root.render(
    <React.StrictMode>
      <App />
    </React.StrictMode>
  );
};

// Start the app when DOM is ready
if (document.readyState === 'loading') {
  document.addEventListener('DOMContentLoaded', initializeApp);
} else {
  initializeApp();
}