// RiverSafe — Error Boundary
// Catches render errors so one bad component degrades a section, not the whole app.

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false, copied: false };
    this.handleCopy = this.handleCopy.bind(this);
  }

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

  componentDidCatch(error, info) {
    console.error('[RiverSafe] Render error:', error, info && info.componentStack);
    try {
      sessionStorage.setItem('rs_last_error', JSON.stringify({
        error: error.toString(),
        componentStack: info && info.componentStack || ''
      }));
    } catch (e) {}
  }

  handleCopy() {
    let details = '';
    try { details = sessionStorage.getItem('rs_last_error') || ''; } catch (e) {}
    const done = () => {
      this.setState({ copied: true });
      setTimeout(() => this.setState({ copied: false }), 2500);
    };
    if (navigator.clipboard && navigator.clipboard.writeText) {
      navigator.clipboard.writeText(details).then(done).catch(() => {
        this.fallbackCopy(details); done();
      });
    } else {
      this.fallbackCopy(details); done();
    }
  }

  fallbackCopy(text) {
    const ta = document.createElement('textarea');
    ta.value = text;
    ta.style.position = 'fixed';
    ta.style.opacity = '0';
    document.body.appendChild(ta);
    ta.focus();
    ta.select();
    try { document.execCommand('copy'); } catch (e) {}
    document.body.removeChild(ta);
  }

  render() {
    if (!this.state.hasError) return this.props.children;
    return (
      <div className="usa-card" role="alert" style={{ margin: 'var(--sp-3)' }}>
        <div className="usa-card__body" style={{ textAlign: 'center', padding: 'var(--sp-4)' }}>
          <h2 style={{ fontFamily: 'var(--font-sans)', fontSize: 'var(--fs-6)', color: 'var(--fg1)', margin: '0 0 var(--sp-1)' }}>
            Something went wrong.
          </h2>
          <p style={{ fontSize: 'var(--fs-4)', color: 'var(--fg2)', margin: '0 0 var(--sp-3)' }}>
            Reload to start over.
          </p>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--sp-105)', alignItems: 'center' }}>
            <button className="usa-button usa-button--primary" onClick={() => window.location.reload()}>
              Reload
            </button>
            <button className="usa-button usa-button--outline" onClick={this.handleCopy}>
              {this.state.copied ? 'Copied!' : 'Copy error details for support'}
            </button>
          </div>
        </div>
      </div>);

  }
}

Object.assign(window, { ErrorBoundary });
