// components/error-boundary.jsx
// #323(4) — Catch render errors in a page subtree so one component throwing can't
// blank the whole SPA (this was the amplifier behind the #291/#317 white-screens).
// The router wraps each route render in <ErrorBoundary key={route}> so the boundary
// resets on navigation (a broken page never traps the user).
class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { error: null };
  }
  static getDerivedStateFromError(error) {
    return { error };
  }
  componentDidCatch(error, info) {
    try { console.error('[ErrorBoundary] caught render error:', error, info && info.componentStack); } catch (_) {}
  }
  render() {
    if (!this.state.error) return this.props.children;
    return (
      <div className="pb-scroll" style={{ background: 'var(--pb-bg)' }}>
        {typeof PBNav !== 'undefined' ? <PBNav /> : null}
        <section style={{ minHeight: '52vh', display: 'grid', placeItems: 'center', padding: 48, textAlign: 'center' }} data-testid="error-boundary">
          <div style={{ maxWidth: 440 }}>
            <div style={{ fontSize: 40, marginBottom: 12 }}>⚠️</div>
            <div style={{ fontFamily: 'var(--pb-serif)', fontSize: 22, fontWeight: 600, marginBottom: 10 }}>
              页面出错了 · Something went wrong
            </div>
            <p style={{ color: 'var(--pb-fg-muted)', fontSize: 14, lineHeight: 1.6, marginBottom: 22 }}>
              该页面遇到一个错误，但网站其它功能仍可正常使用。<br />This page hit an error; the rest of the site still works.
            </p>
            <div style={{ display: 'flex', gap: 10, justifyContent: 'center', flexWrap: 'wrap' }}>
              <button className="pb-btn pb-btn-primary" onClick={() => { this.setState({ error: null }); window.location.hash = '#/'; }}>返回首页 / Home</button>
              <button className="pb-btn pb-btn-ghost" onClick={() => window.location.reload()}>刷新 / Reload</button>
            </div>
          </div>
        </section>
        {typeof PBFooter !== 'undefined' ? <PBFooter /> : null}
      </div>
    );
  }
}
window.ErrorBoundary = ErrorBoundary;
