/**
 * ErrorBoundary Component
 *
 * @package Advanced_Customer_Account
 */

import { Component } from '@wordpress/element';
import { __ } from '@wordpress/i18n';

/**
 * Error boundary component to catch JavaScript errors.
 */
class ErrorBoundary extends Component {
    constructor( props ) {
        super( props );
        this.state = { hasError: false, error: null };
    }

    static getDerivedStateFromError( error ) {
        return { hasError: true, error };
    }

    componentDidCatch( error, errorInfo ) {
        // Log error to console in development
        console.error( 'ErrorBoundary caught an error:', error, errorInfo );
    }

    render() {
        if ( this.state.hasError ) {
            return (
                <div className="aca-error-boundary">
                    <div className="aca-error-boundary__content">
                        <span className="dashicons dashicons-warning" aria-hidden="true" />
                        <h2 className="aca-error-boundary__title">
                            { __( 'Something went wrong', 'advanced-customer-account' ) }
                        </h2>
                        <p className="aca-error-boundary__message">
                            { __( 'An error occurred while loading this page. Please try refreshing.', 'advanced-customer-account' ) }
                        </p>
                        <button
                            type="button"
                            className="aca-btn aca-btn--primary"
                            onClick={ () => window.location.reload() }
                        >
                            { __( 'Refresh Page', 'advanced-customer-account' ) }
                        </button>
                    </div>
                </div>
            );
        }

        return this.props.children;
    }
}

export default ErrorBoundary;
