class ErrorBoundary extends React.Component {
    constructor(props) {
        super(props);
        this.state = { hasError: false, error: null, errorInfo: null };
    }

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

    componentDidCatch(error, errorInfo) {
        console.error('🔴 REACT ERROR BOUNDARY CAUGHT:', error);
        console.error('🔴 ERROR INFO:', errorInfo);
        console.error('🔴 COMPONENT STACK:', errorInfo.componentStack);
        this.setState({ error, errorInfo });
    }

    render() {
        if (this.state.hasError) {
            return (
                <div style={{ padding: '20px', fontFamily: 'monospace' }}>
                    <h1 style={{ color: 'red' }}>⚠️ React Component Error</h1>
                    <details style={{ whiteSpace: 'pre-wrap', background: '#f5f5f5', padding: '10px', marginTop: '10px' }}>
                        <summary style={{ cursor: 'pointer', fontWeight: 'bold' }}>Error Details (click to expand)</summary>
                        <div style={{ marginTop: '10px' }}>
                            <strong>Error:</strong>
                            <pre>{this.state.error && this.state.error.toString()}</pre>
                            <strong>Stack:</strong>
                            <pre>{this.state.error && this.state.error.stack}</pre>
                            <strong>Component Stack:</strong>
                            <pre>{this.state.errorInfo && this.state.errorInfo.componentStack}</pre>
                        </div>
                    </details>
                    <button 
                        onClick={() => window.location.reload()} 
                        style={{ marginTop: '20px', padding: '10px 20px', cursor: 'pointer' }}
                    >
                        Reload Page
                    </button>
                </div>
            );
        }

        return this.props.children;
    }
}

if (typeof window !== 'undefined') window.ErrorBoundary = ErrorBoundary;