// [REQ D1]  React Suspense i Error Boundaries – class component łapiący błędy runtime
// React error boundaries require a class component — getDerivedStateFromError
// and componentDidCatch have no hook equivalents.
import { Component } from 'react';
import styles from './ErrorBoundary.module.scss';
class ErrorBoundary extends Component {
  state = { hasError: false, error: null };

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

  componentDidCatch(error, info) {
    console.error('[ErrorBoundary]', error, info.componentStack);
  }

  handleReset = () => this.setState({ hasError: false, error: null });

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

    return (
      <div className={styles['error-boundary']} role="alert">
        <div className={styles['error-boundary__box']}>
          <h2 className={styles['error-boundary__title']}>Something went wrong</h2>
          <p className={styles['error-boundary__message']}>
            {this.state.error?.message || 'An unexpected error occurred in this section.'}
          </p>
          <button className={styles['error-boundary__btn']} onClick={this.handleReset}>
            Try again
          </button>
        </div>
      </div>
    );
  }
}

export default ErrorBoundary;
