import React from 'react';
import { Alert } from 'antd';

interface ArtifactErrorBoundaryProps {
  children: React.ReactNode;
  /** 制品标题（用于错误提示文案） */
  title?: string;
}

interface ArtifactErrorBoundaryState {
  hasError: boolean;
}

/**
 * A2UI 制品（表单/审查卡/图表）渲染错误兜底：单个制品渲染失败只降级为
 * 错误占位卡片，不影响同气泡内其他消息与制品。
 */
export class ArtifactErrorBoundary extends React.Component<
  ArtifactErrorBoundaryProps,
  ArtifactErrorBoundaryState
> {
  state: ArtifactErrorBoundaryState = { hasError: false };

  static getDerivedStateFromError(): ArtifactErrorBoundaryState {
    return { hasError: true };
  }

  componentDidCatch(error: Error, info: React.ErrorInfo): void {
    console.error('[ArtifactErrorBoundary] 制品渲染异常:', error, info.componentStack);
  }

  render(): React.ReactNode {
    if (this.state.hasError) {
      return (
        <Alert
          type="warning"
          showIcon
          title={this.props.title ? `${this.props.title}渲染失败` : '此内容渲染失败'}
          description="请让 AI 重新生成，或刷新后重试。"
        />
      );
    }
    return this.props.children;
  }
}

export default ArtifactErrorBoundary;
