import { createRoot } from "react-dom/client";
import React, { Suspense, lazy } from "react";
import "./index.css";

// Lazy load App to ensure main.tsx can execute even if App has import errors
const App = lazy(() => import("./App"));

const LoadingScreen = () => (
  <div style={{
    height: '100vh',
    width: '100vw',
    backgroundColor: '#0a0a0a',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    color: 'white',
    fontSize: '24px',
    fontFamily: 'monospace',
    position: 'fixed',
    top: 0,
    left: 0,
    zIndex: 9999
  }}>
    <div className="animate-pulse">INITIALIZING AETHEX OS...</div>
  </div>
);

const renderApp = () => {
  console.log('[AeThexOS] Starting RenderApp...');

  const rootElement = document.getElementById("root");
  
  if (rootElement) {
    try {
      console.log('[AeThexOS] Creating Root...');
      const root = createRoot(rootElement);
      console.log('[AeThexOS] Rendering App...');
      root.render(
        <Suspense fallback={<LoadingScreen />}>
          <App />
        </Suspense>
      );
    } catch (e) {
      console.error('[AeThexOS] Critical render error:', e);
      // Force visible error
      document.body.innerHTML += '<div style="background:red;color:white;position:fixed;top:0;left:0;width:100%;z-index:9999">REACT CRASH: ' + String(e) + '</div>';
    }
  } else {
    console.error("Failed to find the root element");
    document.body.innerHTML = '<div style="background:red;color:white;">NO ROOT ELEMENT FOUND</div>';
  }
};

if (document.readyState === "loading") {
  document.addEventListener("DOMContentLoaded", renderApp);
} else {
  renderApp();
}
