import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import './index.css';

// Helper to log directly to the on-screen diagnostics panel if available
const log = (msg: string, color?: string) => {
  const time = new Date().toLocaleTimeString();
  console.log(`[main.tsx] ${msg}`);
  const globalLog = (window as any).logToScreen;
  if (globalLog) {
    globalLog(`[React Boot] ${msg}`, color);
  }
};

log('Module initialized. Document state: ' + document.readyState, '#fbbf24');

const rootElement = document.getElementById('root');

if (!rootElement) {
  log('🚨 CRITICAL ERROR: HTML element with id "root" not found in document!', '#ef4444');
  const errDiv = document.createElement('div');
  errDiv.style.cssText = 'color: red; padding: 20px; font-family: monospace; background: #fee2e2; border: 1px solid #f87171; margin: 20px; border-radius: 6px;';
  errDiv.innerHTML = '<h2>React Boot Failure</h2><p>Could not find the "#root" div element in the DOM.</p>';
  document.body.appendChild(errDiv);
} else {
  log('✓ Found #root element. Attempting to dynamically import App.tsx...', '#38bdf8');
  
  import('./App.tsx')
    .then((module) => {
      log('✓ App.tsx imported successfully.', '#34d399');
      const App = module.default;
      
      try {
        log('Initializing React root and rendering App...', '#818cf8');
        const root = createRoot(rootElement);
        root.render(
          <StrictMode>
            <App />
          </StrictMode>
        );
        log('✓ Render call completed successfully.', '#34d399');
      } catch (renderError: any) {
        const errMsg = renderError?.message || String(renderError);
        log(`🚨 Error during React rendering: ${errMsg}`, '#ef4444');
        if (renderError?.stack) {
          console.error(renderError);
          log(`Stack: ${renderError.stack.split('\n')[0]}`, '#f87171');
        }
      }
    })
    .catch((importError) => {
      const errMsg = importError?.message || String(importError);
      log(`🚨 CRITICAL ERROR: Failed to import App.tsx: ${errMsg}`, '#ef4444');
      console.error(importError);
      
      const errDiv = document.createElement('div');
      errDiv.style.cssText = 'color: #7f1d1d; padding: 20px; font-family: monospace; background: #fee2e2; border: 1px solid #f87171; margin: 20px; border-radius: 6px; line-height: 1.5;';
      errDiv.innerHTML = `
        <h2 style="margin-top: 0; color: #991b1b;">Failed to Load App Component</h2>
        <p>This is usually caused by a syntax error in a subcomponent or a missing import.</p>
        <pre style="background: #fca5a5; padding: 10px; border-radius: 4px; overflow-x: auto;">${errMsg}</pre>
      `;
      rootElement.appendChild(errDiv);
    });
}
