// Catches render errors so users see a calm fallback instead of a blank page.
class OAErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { error: null };
  }
  static getDerivedStateFromError(error) {
    return { error };
  }
  componentDidCatch(error, info) {
    try { console.error('Rain error:', error, info); } catch (e) {}
  }
  reset = () => {
    this.setState({ error: null });
  };
  reload = () => {
    try { window.location.reload(); } catch (e) {}
  };
  resetData = () => {
    try {
      localStorage.removeItem('rain:v1');
      localStorage.removeItem('rain:install-dismissed');
      localStorage.removeItem('oma-aktif:v1');
      localStorage.removeItem('oma-aktif:install-dismissed');
    } catch (e) {}
    this.reload();
  };
  render() {
    if (!this.state.error) return this.props.children;
    return (
      <div style={{
        minHeight: '100dvh',
        display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
        padding: 28, textAlign: 'center',
        background: 'linear-gradient(180deg, #DDE9DF 0%, #EDE6DC 100%)',
        color: OA_THEME.ink,
      }}>
        <div style={{ marginBottom: 20 }}>
          <Mascot size={140} mood="calm" />
        </div>
        <h1 style={{
          fontFamily: 'Lora, serif', fontStyle: 'italic', fontWeight: 600,
          fontSize: 32, margin: '0 0 10px', color: OA_THEME.sageDeep,
        }}>Maaf, ada yang tersendat</h1>
        <p style={{ fontSize: 19, lineHeight: 1.45, margin: '0 0 28px', maxWidth: 320 }}>
          Tidak apa-apa. Mari kita coba muat ulang. Data Oma tetap aman.
        </p>
        <div style={{ width: '100%', maxWidth: 320, display: 'flex', flexDirection: 'column', gap: 12 }}>
          <OABigButton dark color={OA_THEME.sageDeep} onClick={this.reload}>
            Muat ulang
          </OABigButton>
          <OABigButton color={OA_THEME.sage} onClick={this.resetData}>
            Mulai bersih
          </OABigButton>
        </div>
      </div>
    );
  }
}

window.OAErrorBoundary = OAErrorBoundary;
