import { Component } from 'react';

/**
 * Catches unhandled render errors inside child components and shows
 * a friendly fallback instead of crashing the entire page.
 *
 * Usage:
 *   <ErrorBoundary label="slide card">
 *     <SlideCard ... />
 *   </ErrorBoundary>
 */
export default class ErrorBoundary extends Component {
  constructor(props) {
    super(props);
    this.state = { error: null };
  }

  static getDerivedStateFromError(error) {
    return { error };
  }

  componentDidCatch(error, info) {
    console.error('[ErrorBoundary]', this.props.label ?? '', error, info);
  }

  reset() {
    this.setState({ error: null });
  }

  render() {
    if (this.state.error) {
      return (
        <div className="error-boundary">
          <span className="error-boundary__msg">
            {this.props.label ? `Error in ${this.props.label}` : 'Something went wrong'}
          </span>
          <button className="error-boundary__retry" onClick={() => this.reset()}>
            RETRY
          </button>
        </div>
      );
    }

    return this.props.children;
  }
}
