import React from 'react';

interface ErrorBoundaryState {
  hasError: boolean;
  error?: Error;
}

class ErrorBoundary extends React.Component<React.PropsWithChildren, ErrorBoundaryState> {
  constructor(props: React.PropsWithChildren) {
    super(props);
    this.state = { hasError: false };
  }

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

  componentDidCatch(error: Error, info: React.ErrorInfo) {
    // Log detailed error to console so we can see stack instead of generic "Script error"
    console.error('App crashed with error:', error, info);
  }

  render() {
    if (this.state.hasError) {
      return (
        <div className="flex items-center justify-center min-h-screen">
          <div className="max-w-md text-center">
            <h1 className="text-2xl font-semibold mb-2">Algo salió mal</h1>
            <p className="text-sm text-gray-500 mb-4">Se produjo un error inesperado. Intenta recargar la página.</p>
            {this.state.error && (
              <pre className="text-left text-xs bg-gray-100 p-3 rounded overflow-auto" style={{maxHeight: 200}}>
                {this.state.error.message}\n{this.state.error.stack}
              </pre>
            )}
            <button onClick={() => window.location.reload()} className="mt-4 px-4 py-2 rounded bg-orange-500 text-white">Recargar</button>
          </div>
        </div>
      );
    }

    return this.props.children;
  }
}

export default ErrorBoundary;
