import {StrictMode, Component, ReactNode} from 'react';
import {createRoot} from 'react-dom/client';
import App from './App.tsx';
import './index.css';

console.log("Apros Tracker: main.tsx execution started");

class ErrorBoundary extends Component<{children: ReactNode}> {
  state = { hasError: false, error: null };
  static getDerivedStateFromError(error: any) { return { hasError: true, error }; }
  componentDidCatch(error: any, info: any) { 
    console.error("Global Error Caught:", error, info); 
  }
  render() {
    if (this.state.hasError) {
      return (
        <div className="p-10 text-red-500 font-mono bg-white min-h-screen">
          <h1 className="text-xl font-bold mb-4">Portal Initialization Failure</h1>
          <p className="mb-2">A critical error occurred while starting the application.</p>
          <pre className="bg-red-50 p-4 border border-red-100 overflow-auto max-w-full">
            {(this.state.error as any)?.message || String(this.state.error)}
          </pre>
          <button 
            onClick={() => window.location.reload()}
            className="mt-4 px-4 py-2 bg-red-600 text-white rounded"
          >
            Retry Connection
          </button>
        </div>
      );
    }
    return (this as any).props.children;
  }
}

const container = document.getElementById('root');
if (!container) {
  const msg = "Critical Error: #root element not found in DOM";
  console.error(msg);
  document.body.innerHTML = `<div style="color:red;padding:20px;">${msg}</div>`;
} else {
  try {
    const root = createRoot(container);
    root.render(
      <StrictMode>
        <ErrorBoundary>
          <App />
        </ErrorBoundary>
      </StrictMode>,
    );
    console.log("Apros Tracker: Root render called");
  } catch (error: any) {
    console.error("Apros Tracker: Failed to render root", error);
    container.innerHTML = `<div style="color:red;padding:20px;">Failed to render: ${error.message}</div>`;
  }
}
