import { Component, type ErrorInfo, type ReactNode } from 'react'

type AppErrorBoundaryProps = {
  children: ReactNode
}

type AppErrorBoundaryState = {
  error: Error | null
}

export class AppErrorBoundary extends Component<AppErrorBoundaryProps, AppErrorBoundaryState> {
  state: AppErrorBoundaryState = { error: null }

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

  componentDidCatch(error: Error, errorInfo: ErrorInfo) {
    console.error('React render error', error, errorInfo)
  }

  render() {
    if (this.state.error) {
      return (
        <div className="min-h-screen bg-background p-6 text-foreground">
          <div className="mx-auto max-w-3xl rounded-md border border-destructive/40 bg-destructive/10 p-4">
            <h1 className="text-lg font-semibold text-destructive">Frontend render failed</h1>
            <p className="mt-2 text-sm text-muted-foreground">
              {this.state.error.message || 'Unknown render error'}
            </p>
          </div>
        </div>
      )
    }

    return this.props.children
  }
}
