// components/error-boundary.jsx — shared soft failure UI (store + admin)

class AppErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { error: null };
  }

  static getDerivedStateFromError(error) {
    return { error: error || true };
  }

  componentDidCatch(error, info) {
    try {
      console.error('[AppErrorBoundary]', error, info);
    } catch (e) { /* ignore */ }
  }

  render() {
    if (!this.state.error) return this.props.children;

    const homeHref = this.props.homeHref || '#/';
    const openRinpo = () => {
      if (window.RinpoRuntime) window.RinpoRuntime.open({ tab: 'chat', source: 'error_boundary' });
    };

    return (
      <main className="container section" style={{ maxWidth: 520, paddingBlock: 48, textAlign: 'center' }}>
        <h1 className="serif" style={{ fontSize: '1.6rem' }}>Something didn’t load</h1>
        <p className="muted" style={{ marginTop: 10 }}>
          RINPO is checking the problem. Your cart and account data stay safe.
        </p>
        <div style={{ display: 'flex', gap: 10, justifyContent: 'center', flexWrap: 'wrap', marginTop: 22 }}>
          <button type="button" className="btn btn--primary" onClick={() => location.reload()}>Try again</button>
          <a className="btn btn--ghost" href={homeHref}>Go Home</a>
          <button type="button" className="btn btn--ghost" onClick={openRinpo}>Open RINPO</button>
        </div>
      </main>
    );
  }
}

function NotFoundPage({ homeHref, title }) {
  const openRinpo = () => {
    if (window.RinpoRuntime) window.RinpoRuntime.open({ tab: 'chat', source: 'not_found' });
  };
  return (
    <main className="container section" style={{ maxWidth: 520, paddingBlock: 48, textAlign: 'center' }}>
      <h1 className="serif" style={{ fontSize: '1.6rem' }}>{title || 'Page not found'}</h1>
      <p className="muted" style={{ marginTop: 10 }}>That route isn’t available. Try home or ask RINPO.</p>
      <div style={{ display: 'flex', gap: 10, justifyContent: 'center', flexWrap: 'wrap', marginTop: 22 }}>
        <a className="btn btn--primary" href={homeHref || '#/'}>Go Home</a>
        <button type="button" className="btn btn--ghost" onClick={openRinpo}>Open RINPO</button>
      </div>
    </main>
  );
}

window.AppErrorBoundary = AppErrorBoundary;
window.NotFoundPage = NotFoundPage;
