// src/main.jsx - Simplified and Fixed

import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import './index.css';
import AppWithErrorBoundary from './components/AppWithErrorBoundary.jsx';
import BrowserWarning from './components/BrowserWarning.jsx';
import { initializeBrowserSupport, loadPolyfills } from './utils/browserCompatibility.js';

// Performance monitoring
if (typeof performance !== 'undefined' && performance.mark) {
  performance.mark('app-init-start');
}

// Main initialization function
async function initializeApp() {
  try {
    console.log('🚀 Starting application initialization...');

    // Check browser support first
    const { support, browserInfo } = initializeBrowserSupport();
    
    // Load polyfills for unsupported browsers
    if (!support.isSupported) {
      console.log('⚠️ Loading polyfills for browser compatibility...');
      try {
        await loadPolyfills();
      } catch (polyfillError) {
        console.warn('Failed to load some polyfills:', polyfillError);
      }
    }

    // Get root element
    const rootElement = document.getElementById('root');
    if (!rootElement) {
      throw new Error('Root element #root not found in DOM');
    }

    // Create React root
    const root = createRoot(rootElement);

    // Show browser warning if there are compatibility issues
    if (!support.isSupported && support.unsupportedFeatures.length > 0) {
      console.warn('🌐 Browser compatibility issues detected:', support.unsupportedFeatures);
      
      // Create warning overlay
      const warningDiv = document.createElement('div');
      warningDiv.id = 'browser-warning';
      warningDiv.className = 'browser-warning-overlay';
      document.body.appendChild(warningDiv);
      
      const warningRoot = createRoot(warningDiv);
      warningRoot.render(
        <StrictMode>
          <BrowserWarning 
            unsupportedFeatures={support.unsupportedFeatures}
            browserInfo={browserInfo}
            onContinue={() => {
              // Remove warning overlay
              const overlay = document.getElementById('browser-warning');
              if (overlay) {
                overlay.remove();
              }
              console.log('User chose to continue with unsupported browser');
            }}
          />
        </StrictMode>
      );
    }

    // Render main application
    root.render(
      <StrictMode>
        <AppWithErrorBoundary />
      </StrictMode>
    );

    console.log('✅ Application initialized successfully');

    // Performance measurement
    if (typeof performance !== 'undefined' && performance.mark && performance.measure) {
      performance.mark('app-init-end');
      performance.measure('app-init-duration', 'app-init-start', 'app-init-end');
      
      const measures = performance.getEntriesByType('measure');
      const initMeasure = measures.find(m => m.name === 'app-init-duration');
      
      if (initMeasure) {
        console.log(`⏱️ App initialization completed in ${Math.round(initMeasure.duration)}ms`);
      }
    }

  } catch (error) {
    console.error('❌ Critical error during application initialization:', error);
    
    // Show fallback error UI (this handles initialization errors, not React rendering errors)
    showFallbackErrorUI(error);
  }
}

// Fallback error UI for initialization failures (not React rendering errors)
function showFallbackErrorUI(error) {
  const errorHTML = `
    <div style="
      min-height: 100vh;
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 1rem;
      background: linear-gradient(135deg, #fef2f2 0%, #fee2e2 100%);
      font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
    ">
      <div style="
        background: white;
        border-radius: 12px;
        box-shadow: 0 20px 40px rgba(0,0,0,0.1);
        padding: 2rem;
        max-width: 500px;
        width: 100%;
        text-align: center;
        border: 1px solid #fecaca;
      ">
        <div style="
          width: 64px;
          height: 64px;
          margin: 0 auto 1.5rem;
          background: #fee2e2;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
        ">
          <svg width="32" height="32" fill="#dc2626" viewBox="0 0 24 24">
            <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"/>
          </svg>
        </div>
        
        <h1 style="
          color: #dc2626; 
          margin-bottom: 1rem; 
          font-size: 1.5rem;
          font-weight: 700;
        ">
          Application Failed to Load
        </h1>
        
        <p style="
          color: #374151; 
          margin-bottom: 1.5rem; 
          line-height: 1.6;
          font-size: 1rem;
        ">
          We're sorry, but Resume Tools encountered an error during startup. 
          This could be due to network issues, browser compatibility, or a temporary server problem.
        </p>
        
        <div style="
          margin-bottom: 2rem;
          padding: 1rem;
          background: #f9fafb;
          border-radius: 8px;
          border: 1px solid #e5e7eb;
        ">
          <p style="font-size: 0.875rem; color: #6b7280; font-weight: 600; margin-bottom: 0.5rem;">
            Technical Details:
          </p>
          <p style="font-size: 0.875rem; color: #374151; font-family: monospace;">
            ${error.message}
          </p>
        </div>
        
        <div style="
          display: flex; 
          gap: 0.75rem;
          flex-direction: column;
        ">
          <button 
            onclick="window.location.reload()" 
            style="
              background: #2563eb;
              color: white;
              border: none;
              padding: 0.75rem 1.5rem;
              border-radius: 8px;
              cursor: pointer;
              font-weight: 600;
              font-size: 1rem;
              transition: background 0.2s;
            "
            onmouseover="this.style.background='#1d4ed8'"
            onmouseout="this.style.background='#2563eb'"
          >
            🔄 Reload Application
          </button>
          
          <button 
            onclick="window.history.back()" 
            style="
              background: #6b7280;
              color: white;
              border: none;
              padding: 0.75rem 1.5rem;
              border-radius: 8px;
              cursor: pointer;
              font-weight: 600;
              font-size: 1rem;
              transition: background 0.2s;
            "
            onmouseover="this.style.background='#4b5563'"
            onmouseout="this.style.background='#6b7280'"
          >
            ← Go Back
          </button>
          
          <div style="margin-top: 1rem; padding-top: 1rem; border-top: 1px solid #e5e7eb;">
            <p style="font-size: 0.75rem; color: #6b7280;">
              If this problem persists, try clearing your browser cache or using a different browser.
            </p>
          </div>
        </div>
      </div>
    </div>
  `;

  // Replace entire body content with error UI
  document.body.innerHTML = errorHTML;
}

// Global error handlers for unhandled errors
window.addEventListener('error', (event) => {
  console.error('🚨 Global JavaScript Error:', {
    message: event.message || 'Unknown error',
    filename: event.filename || 'Unknown file',
    lineno: event.lineno || 0,
    colno: event.colno || 0,
    error: event.error ? {
      name: event.error.name,
      message: event.error.message,
      stack: event.error.stack?.substring(0, 500) // Limit stack trace length
    } : null,
    timestamp: new Date().toISOString(),
    userAgent: navigator.userAgent.substring(0, 100) // Limit user agent length
  });
});

window.addEventListener('unhandledrejection', (event) => {
  console.error('🚨 Unhandled Promise Rejection:', {
    reason: event.reason ? {
      name: event.reason.name || 'UnknownError',
      message: event.reason.message || event.reason.toString(),
      stack: event.reason.stack?.substring(0, 500) // Limit stack trace length
    } : String(event.reason),
    timestamp: new Date().toISOString()
  });
  
  // Prevent default browser behavior
  event.preventDefault();
});

// Initialize the application
initializeApp();