import React, { Component, ErrorInfo, ReactNode } from 'react';

/**
 * {{ModuleName}} 错误边界 — 捕获 {{moduleName}} 模块渲染异常并展示降级 UI。
 */
interface ErrorBoundaryProps {
  children: ReactNode;
  fallback?: ReactNode;
}

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

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

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

  componentDidCatch(error: Error, errorInfo: ErrorInfo): void {
    console.error('[{{ModuleName}}ErrorBoundary] 渲染异常:', error, errorInfo);
  }

  render(): ReactNode {
    if (this.state.hasError) {
      if (this.props.fallback) {
        return this.props.fallback;
      }
      return (
        <div className="{{moduleName}}-error-boundary" role="alert">
          <h2>{{ModuleName}} 模块渲染异常</h2>
          <p>{this.state.error?.message ?? '未知错误'}</p>
          <button onClick={() => this.setState({ hasError: false, error: null })}>
            重试
          </button>
        </div>
      );
    }
    return this.props.children;
  }
}

export default {{ModuleName}}ErrorBoundary;
