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

/**
 * Route-level error boundary for /control. A render-time throw anywhere in the
 * cockpit subtree (a bad WS frame shape, a chart blowing up) degrades to a
 * message instead of unwinding to the root and blank-screening the whole app
 * (the failure class the project's CLAUDE.md repeatedly warns about).
 */
interface State {
  error: Error | null;
}

export class ControlErrorBoundary extends Component<{ children: ReactNode }, State> {
  state: State = { error: null };

  static getDerivedStateFromError(error: Error): State {
    return { error };
  }

  override render(): ReactNode {
    if (this.state.error) {
      return (
        <div className="flex-1 flex flex-col items-center justify-center gap-3 p-8 text-center">
          <p className="text-sm font-medium text-foreground">The control cockpit hit a render error.</p>
          <p className="text-xs text-muted-foreground max-w-md break-words">{this.state.error.message}</p>
          <button
            type="button"
            onClick={() => this.setState({ error: null })}
            className="px-3 py-1.5 text-xs rounded-md bg-primary text-primary-foreground hover:bg-primary/90"
          >
            Retry
          </button>
        </div>
      );
    }
    return this.props.children;
  }
}
