/* Reusable error boundary — wraps unstable components so one crash doesn't kill the page.
   Pairs with the global #__crash overlay in index.html for runtime/Babel errors.
*/

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { err: null };
  }
  static getDerivedStateFromError(err) { return { err }; }
  componentDidCatch(err, info) {
    console.error('[ErrorBoundary]', this.props.name || '?', err, info);
  }
  reset() { this.setState({ err: null }); }
  render() {
    if (this.state.err) {
      const { name = '구성요소', fallback } = this.props;
      if (fallback) return fallback;
      return (
        <div className="eb-card">
          <div className="eb-icon">⚠</div>
          <div className="eb-body">
            <strong>{name}에서 오류가 발생했어요</strong>
            <div className="eb-msg">{String(this.state.err.message || this.state.err)}</div>
            <button className="eb-retry" onClick={() => this.reset()}>다시 시도</button>
          </div>
          <style>{`
            .eb-card {
              display: flex; gap: 12px;
              padding: 14px 16px;
              background: oklch(0.20 0.04 22 / 0.50);
              border: 1px solid oklch(0.68 0.21 22 / 0.40);
              border-left: 3px solid var(--alert);
              border-radius: 0;
            }
            .eb-icon {
              font-size: 22px; color: var(--alert);
              flex: 0 0 auto;
            }
            .eb-body { flex: 1; min-width: 0; }
            .eb-body strong { display: block; font-size: 13px; color: var(--text); }
            .eb-msg {
              margin-top: 4px; font-size: 11px; color: var(--text-dim);
              font-family: var(--font-mono);
              word-break: break-all;
            }
            .eb-retry {
              margin-top: 8px;
              padding: 4px 10px;
              background: var(--alert);
              color: var(--ink-000);
              border: none; font-size: 11px; cursor: pointer;
              font-weight: 600;
            }
          `}</style>
        </div>
      );
    }
    return this.props.children;
  }
}

Object.assign(window, { ErrorBoundary });
