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

interface Props {
  children: ReactNode;
  name: string;
}

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

/**
 * Lightweight error boundary for individual dashboard components.
 * Renders an inline fallback instead of crashing the entire page.
 */
export class ComponentErrorBoundary 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: ErrorInfo) {
    if (import.meta.env.DEV) {
      // eslint-disable-next-line no-console
      console.error(`[${this.props.name}] crashed:`, error, info.componentStack);
    }
  }

  render() {
    if (this.state.hasError) {
      return (
        <div className="flex flex-col items-center justify-center h-full p-4 text-center">
          <span className="text-sm text-[var(--color-red)] mb-1">
            {this.props.name} failed to render
          </span>
          <span className="text-xs text-[var(--color-text-secondary)] mb-2">
            {this.state.error?.message}
          </span>
          <button
            onClick={() => this.setState({ hasError: false, error: null })}
            className="text-xs underline text-[var(--color-accent)]"
          >
            Retry
          </button>
        </div>
      );
    }

    return this.props.children;
  }
}
