// Top-level error boundary. React eats thrown errors silently by default,
// which in an Electron app with no URL bar means "blank window, nothing
// to click" from the user's perspective. This component at least shows
// the error text + stack so we can copy-paste it into a bug report.

import React from 'react';

interface State {
  error: Error | null;
}

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

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

  componentDidCatch(error: Error, info: React.ErrorInfo): void {
    // Surface the exception in the devtools console too, for quick
    // copy-paste when the boundary is blocking the UI.
    console.error('[ErrorBoundary]', error, info);
  }

  render(): React.ReactNode {
    if (!this.state.error) return this.props.children;
    return (
      <div style={{
        padding: 24, height: '100%', overflow: 'auto',
        background: '#000', color: '#fff', fontFamily: 'monospace',
      }}>
        <h2 style={{ color: '#ff6b6b', marginTop: 0 }}>Something broke.</h2>
        <p style={{ color: '#fff' }}>{this.state.error.message}</p>
        <pre style={{
          color: '#8b8b8b', fontSize: 12, lineHeight: 1.4,
          whiteSpace: 'pre-wrap', wordBreak: 'break-word',
        }}>
          {this.state.error.stack}
        </pre>
        <button
          onClick={() => this.setState({ error: null })}
          style={{
            marginTop: 12, padding: '8px 14px', borderRadius: 999,
            border: '1px solid #1f1f1f', background: '#111',
            color: '#fff', cursor: 'pointer',
          }}
        >
          Retry
        </button>
      </div>
    );
  }
}
