import 'core-js/stable';
import 'regenerator-runtime/runtime';
import { createRoot } from "react-dom/client";
import "./index.css";
import App from "./App";
import { ErrorBoundary } from "./components/ErrorBoundary";

// iOS Safari Compatibility Layer
// These modules are loaded dynamically AFTER React mounts to avoid breaking module resolution
// DO NOT import them at the top level - it breaks React in iOS Safari

// Enhanced error handling for iPhone Safari and all browsers
function showErrorMessage(error: Error) {
  console.error('❌ [React Mount Error]', error);
  const rootElement = document.getElementById("root");
  if (rootElement) {
    rootElement.innerHTML = `
      <div style="
        position: fixed;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        z-index: 9999;
        background: #fee;
        padding: 24px;
        border-radius: 12px;
        max-width: 90%;
        box-shadow: 0 4px 16px rgba(0,0,0,0.2);
        font-family: system-ui, -apple-system, sans-serif;
        color: #c00;
        text-align: center;
      ">
        <h2 style="margin: 0 0 12px 0; font-size: 20px;">App Loading Error</h2>
        <p style="margin: 0; font-size: 14px; color: #666;">
          Please try refreshing the page.
        </p>
        <button 
          onclick="window.location.reload()" 
          style="
            margin-top: 16px;
            padding: 12px 24px;
            background: #3b82f6;
            color: white;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-size: 16px;
          "
        >
          Refresh Page
        </button>
      </div>
    `;
  }
}

// Initialize the full application with error handling
try {
  console.log('🚀 [React] Starting app initialization...');
  
  const rootElement = document.getElementById("root");
  
  if (!rootElement) {
    throw new Error('Root element not found');
  }
  
  console.log('🎯 [React] Root element found, creating React root...');
  
  const root = createRoot(rootElement);
  
  console.log('✅ [React] React root created, rendering App component...');
  
  // Mark root element so timeout script knows React initialized
  rootElement.setAttribute('data-react-root', 'true');
  
  // Add timeout to detect stuck rendering on iOS
  const renderTimeout = setTimeout(() => {
    if (!(window as any).__appFullyRendered) {
      console.error('⏱️ [React] Render timeout - App component stuck');
      if ((window as any).__updateLoadingScreen) {
        (window as any).__updateLoadingScreen(
          '⏱️ Rendering Timeout',
          'App is taking too long to render. Possible infinite loop or blocking operation.',
          true
        );
      }
    }
  }, 5000);
  
  root.render(
    <ErrorBoundary>
      <App />
    </ErrorBoundary>
  );
  
  console.log('🎉 [React] App component rendered successfully!');
  
  // Signal that React has successfully initialized
  (window as any).__reactInitialized = true;
  (window as any).__appFullyRendered = true;
  
  // Clear the render timeout since React mounted successfully
  clearTimeout(renderTimeout);
  
  
  // NOW it's safe to initialize iOS compatibility features
  // Load iOS modules dynamically AFTER React has successfully mounted
  if (typeof window !== 'undefined') {
    // Use requestIdleCallback or setTimeout to defer initialization
    const initializeIOSFeatures = () => {
      console.log('📱 [iOS Init] Starting iOS compatibility initialization...');
      
      // Check if we're on iOS
      const isIOS = typeof navigator !== 'undefined' && /iPad|iPhone|iPod/.test(navigator.userAgent);
      
      if (isIOS) {
        console.log('📱 [iOS Init] iOS device detected');
      } else {
        console.log('📱 [iOS Init] Not an iOS device');
      }
    };
    
    // Use requestIdleCallback if available, otherwise setTimeout
    if ('requestIdleCallback' in window) {
      (window as any).requestIdleCallback(initializeIOSFeatures, { timeout: 1000 });
    } else {
      setTimeout(initializeIOSFeatures, 100);
    }
  }
  
} catch (error) {
  console.error('💥 [React] Fatal error during initialization:', error);
  
  // Update loading screen with error
  if ((window as any).__updateLoadingScreen) {
    (window as any).__updateLoadingScreen(
      '❌ React Failed',
      'Error: ' + (error as Error).message,
      true
    );
  }
  
  showErrorMessage(error as Error);
}

// Global error handler for unhandled errors
window.addEventListener('error', (event) => {
  console.error('🌐 [Global Error]', event.error || event.message);
});

// Global handler for unhandled promise rejections
window.addEventListener('unhandledrejection', (event) => {
  console.error('🔴 [Unhandled Promise Rejection]', event.reason);
});

// iOS Safari page cache handling (bfcache) (lines 195-205 commented out by Replit Support)
// Safari on iOS caches pages aggressively and may show stale content when using back/forward
// window.addEventListener('pageshow', (event) => {
//   if (event.persisted) {
//     console.log('📱 [iOS Cache] Page restored from bfcache, reloading to ensure fresh state');
//     window.location.reload();
//   }
// });

// iOS Safari page cache handling (bfcache) (added by Replit SUpport on Nov 12, and since removed to try to solve IOS rendering issues). Decided to comment out both the suggested fix and original code to check if this was causing the infinite white screen on IOS browsers
// Only reload ONCE to prevent infinite loops
// window.addEventListener('pageshow', (event) => {
//   if (event.persisted) {
//     console.log('📱 [iOS Cache] Page restored from bfcache');

//     // Check if we've already reloaded to prevent infinite loop
//     const hasReloaded = sessionStorage.getItem('bfcache-reloaded');

//     if (!hasReloaded) {
//       console.log('📱 [iOS Cache] Reloading once to ensure fresh state');
//       sessionStorage.setItem('bfcache-reloaded', 'true');
//       window.location.reload();
//     } else {
//       console.log('📱 [iOS Cache] Already reloaded once, skipping to prevent loop');
//       // Clear the flag after a short delay so future navigations work
//       setTimeout(() => {
//         sessionStorage.removeItem('bfcache-reloaded');
//       }, 1000);
//     }
//   }
// });