import { Component, type ErrorInfo, type ReactNode } from "react";

interface SlideErrorBoundaryProps {
  fallback: ReactNode;
  children: ReactNode;
}

interface SlideErrorBoundaryState {
  hasError: boolean;
}

export class SlideErrorBoundary extends Component<
  SlideErrorBoundaryProps,
  SlideErrorBoundaryState
> {
  state: SlideErrorBoundaryState = {
    hasError: false
  };

  static getDerivedStateFromError(): SlideErrorBoundaryState {
    return {
      hasError: true
    };
  }

  componentDidCatch(error: Error, errorInfo: ErrorInfo) {
    console.error("Slide runtime crashed", error, errorInfo);
  }

  componentDidUpdate(prevProps: SlideErrorBoundaryProps) {
    if (prevProps.children !== this.props.children && this.state.hasError) {
      this.setState({ hasError: false });
    }
  }

  render() {
    if (this.state.hasError) {
      return this.props.fallback;
    }

    return this.props.children;
  }
}
