import { createRoot } from "react-dom/client";
import App from "./App";
import "./index.css";

// Type declaration for global callback
declare global {
  interface Window {
    appLoaded?: () => void;
  }
}

console.log('🎬 main.tsx starting...');

// Force immediate execution - no waiting for DOM
document.addEventListener('DOMContentLoaded', function() {
  console.log('📄 DOM Content Loaded');
});

// Disable Service Worker for now - can cause caching issues
// if ('serviceWorker' in navigator) {
//   window.addEventListener('load', () => {
//     navigator.serviceWorker.register('/sw.js')
//       .then((registration) => {
//         console.log('SW registered: ', registration);
//       })
//       .catch((registrationError) => {
//         console.log('SW registration failed: ', registrationError);
//       });
//   });
// }

// Force immediate execution function
function initApp() {
  try {
    const rootElement = document.getElementById("root");
    console.log('🎯 Root element found:', rootElement);
    
    if (!rootElement) {
      throw new Error('Root element not found');
    }
    
    console.log('🚀 Creating React root...');
    const root = createRoot(rootElement);
    
    console.log('🎭 Rendering App component...');
    root.render(<App />);
    
    console.log('✅ React app mounted successfully');
    
    // Call global callback to clear timeout
    if (window.appLoaded) {
      window.appLoaded();
    }
    
    // Remove preloader once React app has mounted  
    setTimeout(() => {
      const preloader = document.getElementById('app-preloader');
      if (preloader) {
        preloader.style.opacity = '0';
        preloader.style.transition = 'opacity 0.5s ease-out';
        setTimeout(() => {
          preloader.remove();
          console.log('🎨 Preloader removed');
        }, 500);
      }
    }, 100);
  } catch (error) {
    console.error('❌ Failed to mount React app:', error);
    
    // Fallback error display
    const rootElement = document.getElementById("root");
    if (rootElement) {
      rootElement.innerHTML = `
        <div style="color: red; padding: 20px; font-family: Arial; text-align: center; background: #000; height: 100vh; display: flex; align-items: center; justify-content: center;">
          <div>
            <h1>Critical Error: React app failed to start</h1>
            <p>Error: ${error instanceof Error ? error.message : 'Unknown error'}</p>
            <p>Refreshing automatically in 3 seconds...</p>
          </div>
        </div>
      `;
      
      // Auto-refresh on error
      setTimeout(() => {
        location.reload();
      }, 3000);
    }
  }
}

// Try to initialize immediately
if (document.readyState === 'loading') {
  // DOM still loading
  document.addEventListener('DOMContentLoaded', initApp);
} else {
  // DOM already loaded
  initApp();
}
