// components/error-boundary.jsx — last-line crash net.
// React 18's createRoot still has no hook-based equivalent for
// componentDidCatch, so this stays as a class. Renders a recovery card and
// pipes the error through the same crash stack as window.onerror.

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

  static getDerivedStateFromError(error) {
    return { error };
  }

  componentDidCatch(error, info) {
    try {
      const crash = window.WordraCrash;
      if (crash && crash.report) {
        crash.report(error, { componentStack: info && info.componentStack });
      }
    } catch (_) {}
  }

  reset = () => {
    this.setState({ error: null });
  };

  hardReset = () => {
    try {
      Object.keys(localStorage).forEach((k) => {
        if (k.indexOf("wordra:") === 0) localStorage.removeItem(k);
      });
    } catch (_) {}
    location.reload();
  };

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

    return (
      <div className="eb-root">
        <div className="eb-card">
          <div className="eb-icon">💥</div>
          <div className="eb-title">Something broke</div>
          <div className="eb-sub">
            We logged it and will look. Reload to continue, or hard-reset to
            clear local data.
          </div>
          <pre className="eb-trace">
            {String(error && (error.message || error))}
          </pre>
          <div className="eb-actions">
            <button className="eb-btn primary" onClick={this.reset}>Try again</button>
            <button className="eb-btn ghost"  onClick={() => location.reload()}>Reload</button>
            <button className="eb-btn danger" onClick={this.hardReset}>Hard reset</button>
          </div>
        </div>
      </div>
    );
  }
}

window.WordraErrorBoundary = WordraErrorBoundary;
