import { Buffer } from 'buffer';
if (typeof window !== 'undefined') {
  window.Buffer = Buffer;
  window.global = window;
}
import { StrictMode, Component, ErrorInfo, ReactNode } from 'react';
import { createRoot } from 'react-dom/client';
import App from './App.tsx';
import './index.css';

// Global error handlers for diagnostics
window.addEventListener('error', (event) => {
  console.error('[DIAGNOSTIC] Global error caught:', event.error || event.message);
});


class DiagnosticErrorBoundary extends Component<{children: ReactNode}, {hasError: boolean, error: Error | null, errorInfo: ErrorInfo | null}> {
  constructor(props: {children: ReactNode}) {
    super(props);
    (this as any).state = { hasError: false, error: null, errorInfo: null };
  }

  static getDerivedStateFromError(error: Error) {
    return { hasError: true, error, errorInfo: null };
  }

  componentDidCatch(error: Error, errorInfo: ErrorInfo) {
    console.error('[DIAGNOSTIC] React Error Boundary caught an error:');
    console.error(error);
    console.error(errorInfo.componentStack);
    (this as any).setState({ errorInfo });
  }

  render() {
    if ((this as any).state.hasError) {
      return (
        <div style={{ padding: '24px', backgroundColor: '#fef2f2', color: '#991b1b', fontFamily: 'monospace', minHeight: '100vh' }}>
          <h2 style={{ fontSize: '18px', fontWeight: 'bold', marginBottom: '16px' }}>Application failed to mount</h2>
          <div style={{ marginBottom: '16px', padding: '12px', backgroundColor: '#fee2e2', borderRadius: '4px' }}>
            <strong>Error:</strong> {(this as any).state.error?.toString()}
          </div>
          <p style={{ fontWeight: 'bold', marginBottom: '8px' }}>Component Stack:</p>
          <pre style={{ whiteSpace: 'pre-wrap', fontSize: '12px', backgroundColor: '#fff', padding: '12px', border: '1px solid #fca5a5', borderRadius: '4px', overflowX: 'auto' }}>
            {(this as any).state.errorInfo?.componentStack || (this as any).state.error?.stack}
          </pre>
        </div>
      );
    }
    return (this as any).props.children;
  }
}

console.log('[DIAGNOSTIC] Starting application initialization...');

try {
  const rootElement = document.getElementById('root');
  if (!rootElement) {
    throw new Error("Root element '#root' not found in DOM");
  }
  
  console.log('[DIAGNOSTIC] Root element found, creating React root...');
  const root = createRoot(rootElement);
  
  console.log('[DIAGNOSTIC] Rendering App component...');
  root.render(
    <StrictMode>
      <DiagnosticErrorBoundary>
        <App />
      </DiagnosticErrorBoundary>
    </StrictMode>
  );
  console.log('[DIAGNOSTIC] Initial render call completed.');
} catch (e) {
  console.error('[DIAGNOSTIC] Fatal error during initialization:', e);
}
