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

class ErrorBoundary extends Component<{children: ReactNode}, {error: Error | null}> {
  state = { error: null as Error | null }

  static getDerivedStateFromError(error: Error) {
    return { error }
  }

  componentDidCatch(error: Error, info: ErrorInfo) {
    console.error('React crash:', error, info.componentStack)
  }

  render() {
    if (this.state.error) {
      return (
        <div style={{
          padding: '40px',
          background: '#1a0000',
          color: '#ff6666',
          fontFamily: 'monospace',
          fontSize: '14px',
          minHeight: '100vh',
          whiteSpace: 'pre-wrap',
        }}>
          <h2 style={{ color: '#ff4444', marginBottom: '20px' }}>React Error Caught</h2>
          <p><strong>Message:</strong> {this.state.error.message}</p>
          <p style={{ marginTop: '10px' }}><strong>Stack:</strong></p>
          <pre style={{ color: '#cc8888', fontSize: '12px' }}>{this.state.error.stack}</pre>
          <button
            onClick={() => this.setState({ error: null })}
            style={{
              marginTop: '20px',
              padding: '10px 20px',
              background: '#ff4444',
              color: '#fff',
              border: 'none',
              borderRadius: '6px',
              cursor: 'pointer',
            }}
          >
            Try Again
          </button>
        </div>
      )
    }
    return this.props.children
  }
}

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