import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';

class ErrorBoundary extends React.Component<{children: React.ReactNode}, {hasError: boolean, error: any}> {
  constructor(props: any) {
    super(props);
    this.state = { hasError: false, error: null };
  }

  static getDerivedStateFromError(error: any) {
    return { hasError: true, error };
  }

  componentDidCatch(error: any, errorInfo: any) {
    console.error("Uncaught error:", error, errorInfo);
  }

  render() {
    if (this.state.hasError) {
      return (
        <div style={{padding: '40px', fontFamily: 'sans-serif'}}>
          <h1 style={{color: '#e11d48', fontSize: '24px', marginBottom: '16px'}}>Something went wrong</h1>
          <div style={{backgroundColor: '#f1f5f9', padding: '20px', borderRadius: '8px', overflow: 'auto'}}>
            <p style={{fontWeight: 'bold', color: '#334155'}}>{this.state.error?.toString()}</p>
            <pre style={{fontSize: '12px', color: '#64748b', marginTop: '10px'}}>{this.state.error?.stack}</pre>
          </div>
          <button 
            onClick={() => window.location.reload()} 
            style={{marginTop: '20px', padding: '10px 20px', backgroundColor: '#0f172a', color: 'white', border: 'none', borderRadius: '6px', cursor: 'pointer'}}
          >
            Reload Page
          </button>
        </div>
      );
    }

    return this.props.children;
  }
}

const rootElement = document.getElementById('root');
if (!rootElement) {
  throw new Error("Could not find root element to mount to");
}

const root = ReactDOM.createRoot(rootElement);
root.render(
  <React.StrictMode>
    <ErrorBoundary>
      <App />
    </ErrorBoundary>
  </React.StrictMode>
);