import { Component, type ReactNode } from 'react';

interface Props {
  children: ReactNode;
  fallback?: ReactNode;
}

interface State {
  hasError: boolean;
  error: Error | null;
}

export class ErrorBoundary extends Component<Props, State> {
  constructor(props: Props) {
    super(props);
    this.state = { hasError: false, error: null };
  }

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

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

  render() {
    if (this.state.hasError) {
      if (this.props.fallback) return this.props.fallback;

      return (
        <div
          style={{
            display: 'grid',
            placeItems: 'center',
            minHeight: '100dvh',
            padding: '2rem',
            color: '#efe2ce',
            background: '#070604',
            fontFamily: "'Chakra Petch', sans-serif",
          }}
        >
          <div
            style={{
              maxWidth: 480,
              textAlign: 'center',
              padding: '2rem',
              borderRadius: 20,
              border: '1px solid rgba(225, 109, 76, 0.3)',
              background: 'rgba(16, 13, 10, 0.94)',
            }}
          >
            <h2 style={{ margin: '0 0 0.75rem', fontSize: '1.3rem', letterSpacing: '0.08em' }}>
              界面发生异常
            </h2>
            <p style={{ margin: '0 0 1.25rem', color: '#a38f73', lineHeight: 1.5 }}>
              {this.state.error?.message ?? '渲染过程中出现未知错误，请尝试刷新页面。'}
            </p>
            <button
              onClick={() => window.location.reload()}
              style={{
                minHeight: 48,
                padding: '0 2rem',
                borderRadius: 14,
                border: '1px solid rgba(228, 158, 75, 0.42)',
                background: 'linear-gradient(135deg, #eeab52, #c86d22)',
                color: '#160f08',
                fontWeight: 700,
                cursor: 'pointer',
                fontSize: '0.9rem',
              }}
            >
              刷新页面
            </button>
          </div>
        </div>
      );
    }

    return this.props.children;
  }
}
