import React from 'react';
import { createRoot } from 'react-dom/client';
import App from './App.tsx';
import './index.css';

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

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

  componentDidCatch(error: Error, info: React.ErrorInfo) {
    console.error('React crashed:', error, info);
  }

  render() {
    if (this.state.hasError) {
      return (
        <div style={{
          fontFamily: 'monospace',
          padding: '40px',
          background: '#0f172a',
          color: '#f87171',
          minHeight: '100vh',
          whiteSpace: 'pre-wrap',
          wordBreak: 'break-word'
        }}>
          <h1 style={{ color: '#fbbf24', fontSize: '24px', marginBottom: '16px' }}>
            ⚠️ Erreur JavaScript détectée
          </h1>
          <div style={{ color: '#94a3b8', marginBottom: '8px', fontSize: '14px' }}>
            Copiez ce message et partagez-le pour corriger le bug :
          </div>
          <div style={{
            background: '#1e293b',
            padding: '20px',
            borderRadius: '8px',
            border: '1px solid #ef4444',
            color: '#fca5a5',
            fontSize: '13px'
          }}>
            {this.state.error?.toString()}
            {'\n\n'}
            {this.state.error?.stack}
          </div>
        </div>
      );
    }
    return this.props.children;
  }
}

createRoot(document.getElementById('root')!).render(
  <ErrorBoundary>
    <App />
  </ErrorBoundary>,
);
