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

interface Props {
  children: ReactNode;
}

interface State {
  error: Error | null;
}

export class ErrorBoundary extends Component<Props, State> {
  state: State = { error: null };

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

  componentDidCatch(error: Error, info: React.ErrorInfo) {
    console.error("Tusk render crash:", error, info.componentStack);
  }

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

  render() {
    if (this.state.error) {
      return (
        <div className="flex h-screen items-center justify-center bg-background p-6">
          <div className="max-w-xl space-y-3">
            <h1 className="text-base font-semibold text-destructive">Something broke while rendering Tusk</h1>
            <pre className="overflow-auto rounded-md border border-border/50 bg-muted/40 p-3 text-xs">
              {this.state.error.message}
              {this.state.error.stack ? `\n\n${this.state.error.stack}` : ""}
            </pre>
            <p className="text-xs text-muted-foreground">
              Open the developer console for the full stack. Click "Try again" to re-mount the UI.
            </p>
            <button
              type="button"
              className="rounded-md border border-border/60 px-3 py-1 text-xs hover:bg-accent/40"
              onClick={this.reset}
            >
              Try again
            </button>
          </div>
        </div>
      );
    }
    return this.props.children;
  }
}
