// ErrorBoundary — capture les erreurs runtime React et affiche un fallback
// Vague 1 PR 1.1 — durcissement dashboard courtier

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

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

  componentDidCatch(error, info) {
    try {
      console.error('[ErrorBoundary]', error, info);
    } catch (_) {}
  }

  render() {
    if (this.state.hasError) {
      const lang = this.props.lang || 'fr';
      const FR = lang !== 'en';
      return (
        <div style={{
          padding: 24,
          margin: 16,
          background: '#fff5f5',
          border: '1px solid #fca5a5',
          borderRadius: 8,
          color: '#7f1d1d',
          fontFamily: 'system-ui, sans-serif',
        }}>
          <div style={{ fontWeight: 600, marginBottom: 8 }}>
            {FR ? 'Une erreur est survenue.' : 'An error occurred.'}
          </div>
          <div style={{ fontSize: 13, marginBottom: 12, opacity: 0.85 }}>
            {FR
              ? "Le composant n'a pas pu s'afficher. Veuillez recharger la page."
              : 'The component could not render. Please reload the page.'}
          </div>
          <button
            type="button"
            onClick={() => window.location.reload()}
            style={{
              background: '#dc2626',
              color: 'white',
              border: 0,
              borderRadius: 6,
              padding: '8px 14px',
              fontSize: 13,
              cursor: 'pointer',
            }}
          >
            {FR ? 'Recharger la page' : 'Reload page'}
          </button>
        </div>
      );
    }
    return this.props.children;
  }
}

window.ErrorBoundary = ErrorBoundary;
