import React from 'react'

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

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

  componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
    console.error('Error caught by boundary:', error, errorInfo)
  }

  render() {
    if (this.state.hasError) {
      return (
        <div style={{ 
          padding: '20px', 
          backgroundColor: '#323232', 
          color: 'white', 
          minHeight: '100vh' 
        }}>
          <h1>🎵♟️ Musical Chess Arena</h1>
          <div style={{ 
            backgroundColor: '#ff4444', 
            padding: '20px', 
            borderRadius: '8px',
            marginTop: '20px'
          }}>
            <h2>Something went wrong!</h2>
            <p>Error: {this.state.error?.message}</p>
            <pre style={{ marginTop: '10px', fontSize: '12px' }}>
              {this.state.error?.stack}
            </pre>
            <button 
              onClick={() => window.location.reload()}
              style={{ 
                marginTop: '20px',
                padding: '10px 20px',
                backgroundColor: '#323232',
                color: 'white',
                border: '2px solid white',
                borderRadius: '4px',
                cursor: 'pointer'
              }}
            >
              Reload Page
            </button>
          </div>
        </div>
      )
    }

    return this.props.children
  }
}