import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App.jsx';
import { ThemeProvider } from './context/ThemeContext.jsx';
import './index.css';

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false, error: null };
  }

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

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

  render() {
    if (this.state.hasError) {
      return (
        <div style={{
          minHeight: '100vh',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          padding: '2rem',
          background: 'var(--bg-main)',
          color: 'var(--text-primary)',
          fontFamily: 'var(--font-sans)'
        }}>
          <div className="card-3d" style={{
            maxWidth: '480px',
            width: '100%',
            padding: '2.5rem 2rem',
            textAlign: 'center'
          }}>
            <span style={{
              fontSize: '0.7rem',
              fontWeight: 700,
              padding: '0.25rem 0.6rem',
              background: 'var(--status-error)',
              color: '#ffffff',
              textTransform: 'uppercase',
              letterSpacing: '0.1em',
              display: 'inline-block',
              marginBottom: '1.25rem',
              borderRadius: 'var(--radius-sharp)',
              fontFamily: 'var(--font-mono)'
            }}>
              SYSTEM EXCEPTION
            </span>
            <h2 className="font-serif" style={{ fontSize: '1.75rem', fontWeight: 500, marginBottom: '0.75rem' }}>
              Unexpected Error
            </h2>
            <p className="font-mono" style={{ color: 'var(--text-muted)', fontSize: '0.78rem', marginBottom: '1.75rem', lineHeight: 1.6 }}>
              {this.state.error?.toString() || 'An unexpected rendering error occurred.'}
            </p>
            <button
              onClick={() => window.location.reload()}
              className="btn-primary"
              style={{ margin: '0 auto' }}
            >
              <span>Reload Application</span>
            </button>
          </div>
        </div>
      );
    }

    return this.props.children || null;
  }
}

ReactDOM.createRoot(document.getElementById('root')).render(
  <React.StrictMode>
    <ThemeProvider>
      <ErrorBoundary>
        <App />
      </ErrorBoundary>
    </ThemeProvider>
  </React.StrictMode>,
);
