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

/**
 * Wraps <Canvas> from @react-three/fiber to catch WebGL context creation
 * failures (e.g. Chrome GPU sandbox) and show a graceful fallback instead
 * of crashing the entire React tree.
 */
export default class WebGLErrorBoundary extends Component<
  { children: ReactNode },
  { error: string | null }
> {
  constructor(props: { children: ReactNode }) {
    super(props)
    this.state = { error: null }
  }

  static getDerivedStateFromError(error: Error): { error: string } {
    return { error: error.message || 'WebGL context could not be created' }
  }

  componentDidCatch(error: Error, _info: ErrorInfo): void {
    console.warn('[WebGLErrorBoundary]', error.message)
  }

  render(): ReactNode {
    if (this.state.error) {
      return (
        <div className="absolute inset-0 flex flex-col items-center justify-center bg-gray-900 text-white gap-3 p-8 text-center">
          <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" className="text-yellow-400">
            <path d="m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3Z" />
            <path d="M12 9v4" /><path d="M12 17h.01" />
          </svg>
          <p className="text-lg font-medium">3D Viewer unavailable</p>
          <p className="text-sm text-gray-400 max-w-md">
            Your browser could not create a WebGL context. This may be caused by GPU sandbox restrictions or missing graphics drivers.
            Try a different browser or launch Chrome with <code className="bg-gray-800 px-1 rounded">--disable-gpu-sandbox</code>.
          </p>
        </div>
      )
    }
    return this.props.children
  }
}
