import { Component, type ReactNode } from 'react'
import { Handle, type HandleProps } from '@xyflow/react'

/**
 * Error boundary that silently catches React Flow context errors.
 * When rendered outside a ReactFlowProvider (e.g. in unit tests),
 * Handle throws — this boundary swallows the error and renders nothing.
 */
class HandleBoundary extends Component<{ children: ReactNode }, { hasError: boolean }> {
  constructor(props: { children: ReactNode }) {
    super(props)
    this.state = { hasError: false }
  }

  static getDerivedStateFromError(): { hasError: boolean } {
    return { hasError: true }
  }

  render(): ReactNode {
    if (this.state.hasError) return null
    return this.props.children
  }
}

/**
 * A Handle wrapper that gracefully degrades when rendered outside
 * a React Flow context (e.g. in isolated unit tests).
 */
export function SafeHandle(props: HandleProps) {
  return (
    <HandleBoundary>
      <Handle {...props} />
    </HandleBoundary>
  )
}
