import React from 'react';

interface ErrorBoundaryProps {
  children: React.ReactNode;
}

interface ErrorBoundaryState {
  error: Error | null;
}

export default class ErrorBoundary extends React.Component<ErrorBoundaryProps, ErrorBoundaryState> {
  constructor(props: ErrorBoundaryProps) {
    super(props);
    this.state = { error: null };
  }

  static getDerivedStateFromError(error: Error) {
    return { error };
  }

  componentDidCatch(error: Error, info: React.ErrorInfo) {
    console.error('ErrorBoundary caught:', error, info);
  }

  render() {
    if (this.state.error) {
      return (
        <div className="min-h-screen bg-surface-950 flex items-center justify-center p-8">
          <div className="max-w-lg text-center">
            <div className="text-red-400 text-2xl font-bold mb-3">Something went wrong</div>
            <div className="bg-surface-800 border border-surface-700 rounded-lg p-4 mb-4 text-left">
              <p className="text-red-300 text-sm font-mono break-all">{this.state.error.message}</p>
            </div>
            <button
              onClick={() => { this.setState({ error: null }); window.location.href = '/dashboard'; }}
              className="btn-primary"
            >
              Back to Dashboard
            </button>
          </div>
        </div>
      );
    }
    return this.props.children;
  }
}