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

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

export default class ErrorBoundary extends Component<Props, State> {
  state: State = { hasError: false, error: null };

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

  componentDidCatch(error: Error, info: React.ErrorInfo) {
    // 生产环境错误日志记录入口
    // TODO: 集成遥测服务后将错误上报
    console.error('QRGen ErrorBoundary 捕获错误:', error.message, info.componentStack);
  }

  render() {
    if (this.state.hasError) {
      return (
        <div className="h-screen flex flex-col items-center justify-center gap-3 bg-gray-50 dark:bg-gray-950 text-gray-600 dark:text-gray-400">
          <span className="text-4xl">⚠</span>
          <h2 className="text-lg font-semibold">应用发生错误</h2>
          <p className="text-sm max-w-md text-center">{this.state.error?.message}</p>
          <button
            onClick={() => window.location.reload()}
            className="px-4 py-2 rounded-lg bg-blue-500 text-white text-sm hover:bg-blue-600 transition-all"
          >
            重新加载
          </button>
        </div>
      );
    }
    return this.props.children;
  }
}
