import { Component } from "preact";
import type { ComponentChildren } from "preact";

interface Props {
  children: ComponentChildren;
  fallback?: ComponentChildren;
}

interface State {
  error: Error | null;
}

/** Catches render errors in child components without crashing the whole app. */
export class ErrorBoundary extends Component<Props, State> {
  state: State = { error: null };

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

  render() {
    if (this.state.error) {
      if (this.props.fallback) return this.props.fallback;
      return (
        <div class="p-4 rounded-lg mb-3" style={{ border: "1px solid rgba(239,68,68,0.2)", background: "rgba(239,68,68,0.05)" }}>
          <p class="text-xs font-semibold text-red-400 mb-1">Component Error</p>
          <p class="text-xs font-mono" style={{ color: "var(--z-muted)" }}>{this.state.error.message}</p>
        </div>
      );
    }
    return this.props.children;
  }
}
