import React from 'react';

/**
 * 专门处理 "Objects are not valid as a React child" 错误的边界组件
 * 特别针对 EllipsisMeasure 组件的问题
 */
class ReactChildErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { 
      hasError: false, 
      errorType: null,
      errorInfo: null 
    };
  }

  static getDerivedStateFromError(error) {
    // 检查是否是React子元素错误
    if (error.message && error.message.includes('Objects are not valid as a React child')) {
      return { 
        hasError: true, 
        errorType: 'REACT_CHILD_ERROR',
        originalError: error.message
      };
    }
    
    return { hasError: true, errorType: 'OTHER_ERROR' };
  }

  componentDidCatch(error, errorInfo) {
    console.group('🚨 React 错误边界捕获到错误');
    console.error('错误类型:', error.message);
    console.error('错误堆栈:', error.stack);
    console.error('组件堆栈:', errorInfo.componentStack);
    console.groupEnd();

    this.setState({
      errorInfo: errorInfo.componentStack
    });
  }

  render() {
    if (this.state.hasError) {
      // 如果有自定义的fallback组件
      if (this.props.fallback) {
        return this.props.fallback;
      }

      // 默认错误处理UI
      return (
        <div style={{
          padding: '20px',
          margin: '20px',
          border: '2px solid #ff6b6b',
          borderRadius: '8px',
          backgroundColor: '#fff5f5',
          color: '#c92a2a'
        }}>
          <h3>⚠️ 组件渲染错误</h3>
          <p>检测到React子元素错误，请检查数据格式。</p>
          <button 
            onClick={() => window.location.reload()}
            style={{
              padding: '8px 16px',
              background: '#ff6b6b',
              color: 'white',
              border: 'none',
              borderRadius: '4px',
              cursor: 'pointer'
            }}
          >
            刷新页面
          </button>
        </div>
      );
    }

    return this.props.children;
  }
}

/**
 * 包装器组件：自动检测并保护可能有问题的组件
 */
export const SafeWrapper = ({ children, fallback = null, debug = false }) => {
  return (
    <ReactChildErrorBoundary fallback={fallback} debug={debug}>
      {children}
    </ReactChildErrorBoundary>
  );
};

export default ReactChildErrorBoundary;