// ErrorBoundary Component
// Catches JavaScript errors anywhere in the child component tree and displays a fallback UI

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

    static getDerivedStateFromError(error) {
        // Update state so the next render shows the fallback UI
        return { hasError: true, error };
    }

    componentDidCatch(error, errorInfo) {
        // Log error details for debugging
        console.error('ErrorBoundary caught an error:', error, errorInfo);
        this.setState({ errorInfo });
        
        // Optional: Send to error reporting service
        if (this.props.onError) {
            this.props.onError(error, errorInfo);
        }
    }

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

    handleReload = () => {
        window.location.reload();
    };

    render() {
        if (this.state.hasError) {
            // Custom fallback UI if provided
            if (this.props.fallback) {
                return this.props.fallback;
            }

            const { error, errorInfo } = this.state;
            const isDev = window.location.hostname === 'localhost';

            return (
                <div className="min-h-screen flex items-center justify-center bg-slate-50 p-6">
                    <div className="max-w-lg w-full">
                        {/* Error Card */}
                        <div className="bg-white rounded-2xl shadow-xl border border-slate-200 overflow-hidden">
                            {/* Header */}
                            <div className="bg-gradient-to-r from-red-500 to-rose-500 px-6 py-8 text-center">
                                <div className="w-16 h-16 bg-white/20 rounded-full flex items-center justify-center mx-auto mb-4">
                                    <svg className="w-8 h-8 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
                                    </svg>
                                </div>
                                <h1 className="text-2xl font-bold text-white mb-2">
                                    Qualcosa è andato storto
                                </h1>
                                <p className="text-white/80 text-sm">
                                    Si è verificato un errore imprevisto nell'applicazione
                                </p>
                            </div>

                            {/* Content */}
                            <div className="p-6 space-y-4">
                                {/* Error message for developers */}
                                {isDev && error && (
                                    <div className="bg-slate-50 rounded-lg p-4 border border-slate-200">
                                        <p className="text-xs font-medium text-slate-500 uppercase tracking-wider mb-2">
                                            Dettagli errore (dev only)
                                        </p>
                                        <p className="text-sm font-mono text-red-600 break-all">
                                            {error.toString()}
                                        </p>
                                        {errorInfo?.componentStack && (
                                            <pre className="mt-3 text-xs font-mono text-slate-500 overflow-x-auto max-h-32 overflow-y-auto">
                                                {errorInfo.componentStack}
                                            </pre>
                                        )}
                                    </div>
                                )}

                                {/* Action buttons */}
                                <div className="flex flex-col sm:flex-row gap-3">
                                    <button
                                        onClick={this.handleRetry}
                                        className="flex-1 inline-flex items-center justify-center gap-2 px-4 py-3 bg-brand-500 text-white font-medium rounded-lg hover:bg-brand-600 transition-colors focus:outline-none focus:ring-2 focus:ring-brand-500 focus:ring-offset-2"
                                    >
                                        <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
                                        </svg>
                                        Riprova
                                    </button>
                                    <button
                                        onClick={this.handleReload}
                                        className="flex-1 inline-flex items-center justify-center gap-2 px-4 py-3 bg-white text-slate-700 font-medium rounded-lg border border-slate-300 hover:bg-slate-50 transition-colors focus:outline-none focus:ring-2 focus:ring-slate-400 focus:ring-offset-2"
                                    >
                                        <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
                                        </svg>
                                        Ricarica Pagina
                                    </button>
                                </div>

                                {/* Help text */}
                                <p className="text-center text-sm text-slate-500 pt-2">
                                    Se il problema persiste, contatta il supporto tecnico
                                </p>
                            </div>
                        </div>

                        {/* Footer hint */}
                        <p className="text-center text-xs text-slate-400 mt-4">
                            Premi <kbd className="px-1.5 py-0.5 bg-slate-200 rounded text-slate-600">F12</kbd> per aprire la console e vedere i dettagli dell'errore
                        </p>
                    </div>
                </div>
            );
        }

        return this.props.children;
    }
}

// Smaller inline error boundary for sections
class SectionErrorBoundary extends React.Component {
    constructor(props) {
        super(props);
        this.state = { hasError: false, error: null };
    }

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

    componentDidCatch(error, errorInfo) {
        console.error('SectionErrorBoundary caught an error:', error, errorInfo);
    }

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

    render() {
        if (this.state.hasError) {
            return (
                <div className="bg-red-50 border border-red-200 rounded-xl p-6 text-center">
                    <div className="w-10 h-10 bg-red-100 rounded-full flex items-center justify-center mx-auto mb-3">
                        <svg className="w-5 h-5 text-red-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
                        </svg>
                    </div>
                    <h3 className="font-medium text-red-800 mb-1">
                        {this.props.sectionName || 'Questa sezione'} non è disponibile
                    </h3>
                    <p className="text-sm text-red-600 mb-4">
                        Si è verificato un errore durante il caricamento
                    </p>
                    <button
                        onClick={this.handleRetry}
                        className="inline-flex items-center gap-2 px-4 py-2 bg-red-100 text-red-700 font-medium rounded-lg hover:bg-red-200 transition-colors text-sm"
                    >
                        <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
                        </svg>
                        Riprova
                    </button>
                </div>
            );
        }

        return this.props.children;
    }
}

window.ErrorBoundary = ErrorBoundary;
window.SectionErrorBoundary = SectionErrorBoundary;

