import { Component } from 'react';

export default class ViewportErrorBoundary extends Component {
  constructor(props) {
    super(props);
    this.state = { error: null, info: null };
  }

  static getDerivedStateFromError(error) {
    return { error };
  }

  componentDidCatch(error, info) {
    // eslint-disable-next-line no-console
    console.error('[ViewportErrorBoundary]', error, info);
    this.setState({ info });
  }

  handleReset = () => {
    this.setState({ error: null, info: null });
    if (this.props.onReset) this.props.onReset();
  };

  handleReload = () => {
    if (typeof window !== 'undefined') window.location.reload();
  };

  handleCompatibility = () => {
    this.setState({ error: null, info: null });
    if (this.props.onCompatibility) this.props.onCompatibility();
  };

  render() {
    const { error } = this.state;
    const { children, fallback } = this.props;

    if (!error) return children;

    if (fallback) return fallback(error, this.handleReset, this.handleReload, this.handleCompatibility);

    const msg = error?.message || String(error);
    const isWebGL = /WebGL|context|gl\.create|shader|gpu/i.test(msg);

    return (
      <div className="flex h-full w-full items-center justify-center bg-workshop p-6">
        <div className="panel max-w-lg p-6 text-slate-200">
          <div className="mb-3 flex items-center gap-2 text-amber-300">
            <svg viewBox="0 0 24 24" className="h-6 w-6" fill="none" stroke="currentColor" strokeWidth="2"><path d="M12 9v4M12 17h.01M10.3 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.7 3.86a2 2 0 0 0-3.4 0Z" strokeLinecap="round" strokeLinejoin="round"/></svg>
            <h2 className="text-lg font-semibold">3D viewport could not start</h2>
          </div>
          <p className="mb-3 text-sm text-slate-400">
            {isWebGL
              ? 'Your browser or device blocked WebGL initialisation. Try the controls below, or switch to a device with WebGL support.'
              : 'The 3D scene hit a runtime error. Your project data is safe — only the preview stopped rendering.'}
          </p>
          <div className="mb-4 max-h-40 overflow-auto rounded-xl border border-white/10 bg-black/30 p-3 font-mono text-xs text-rose-300">
            {msg}
          </div>
          <div className="flex flex-wrap gap-2">
            <button onClick={this.handleReset} className="btn-primary">Retry</button>
            <button onClick={this.handleReload} className="btn-secondary">Reset Viewport</button>
            <button onClick={this.handleCompatibility} className="btn-secondary">Switch to Compatibility Mode</button>
          </div>
          <p className="mt-3 text-xs text-slate-500">
            All workshop records — customers, limb profiles, prostheses, components and measurements — remain available in the non-3D pages.
          </p>
        </div>
      </div>
    );
  }
}