import { Component, type ReactNode } from 'react'

interface Props {
  children: ReactNode
}

interface State {
  hasError: boolean
  error?: Error
}

export class ErrorBoundary extends Component<Props, State> {
  constructor(props: Props) {
    super(props)
    this.state = { hasError: false }
  }

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

  render() {
    if (this.state.hasError) {
      return (
        <div className="min-h-screen flex items-center justify-center p-4 bg-cream">
          <div className="text-center space-y-4">
            <span className="text-5xl">😵</span>
            <h1 className="font-display text-xl text-espresso">Etwas ist schiefgelaufen</h1>
            <p className="text-warm-grey text-sm">{this.state.error?.message}</p>
            <button
              onClick={() => {
                this.setState({ hasError: false })
                window.location.href = '/'
              }}
              className="bg-primary text-white px-6 py-3 rounded-xl text-sm font-medium min-h-[44px]"
            >
              Zurück zur Startseite
            </button>
          </div>
        </div>
      )
    }
    return this.props.children
  }
}
