import { Component, type PropsWithChildren, type ReactNode } from 'react';

type ErrorBoundaryProps = PropsWithChildren<{
  fallback: ReactNode;
  onError?: (error: unknown) => void;
}>;

export default class ErrorBoundary extends Component<
  ErrorBoundaryProps,
  { hasError: boolean }
> {
  constructor(props: ErrorBoundaryProps) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError(error: unknown) {
    // Update state so the next render will show the fallback UI.
    return { hasError: true };
  }

  override render() {
    if (this.state.hasError) {
      // You can render any custom fallback UI
      return this.props.fallback;
    }

    return this.props.children;
  }
}
