import { Component, type ReactNode } from "react";

interface Props {
  children: ReactNode;
}

interface State {
  error: Error | null;
}

// ponytail: a tiny class component. New dep (`react-error-boundary`) is 4KB
// for a feature that's 20 lines. Roll it by hand.
export class ErrorBoundary extends Component<Props, State> {
  state: State = { error: null };

  static getDerivedStateFromError(error: Error): State {
    return { error };
  }

  componentDidCatch(error: Error) {
    console.error("Uncaught error in DM-Pal:", error);
  }

  render() {
    if (this.state.error) {
      return (
        <div className="flex flex-col items-center justify-center h-full gap-3 p-8 text-center">
          <h2 className="font-heading text-[var(--color-gold-bright)] text-lg">
            Something went wrong
          </h2>
          <pre className="max-w-xl text-xs text-[var(--color-text-dim)] whitespace-pre-wrap break-words">
            {this.state.error.message}
          </pre>
          <button
            onClick={() => location.reload()}
            className="rounded-lg bg-[var(--color-gold-bright)] text-[var(--color-bg-deep)] px-4 py-2 text-sm font-semibold hover:bg-[var(--color-gold-muted)] transition-colors cursor-pointer"
          >
            Reload
          </button>
        </div>
      );
    }
    return this.props.children;
  }
}
