"use client";

import { Component, type ReactNode } from "react";
import { AlertTriangle, RefreshCw } from "lucide-react";

interface Props { children: ReactNode; fallbackLabel?: string }
interface State { error: Error | null }

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

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

  render() {
    if (this.state.error) {
      return (
        <div className="glass p-6 text-center space-y-3">
          <AlertTriangle size={24} className="mx-auto text-amber-400" />
          <p className="text-sm text-zinc-400">
            {this.props.fallbackLabel || "Something went wrong"}
          </p>
          <p className="text-xs text-zinc-600 font-mono">{this.state.error.message}</p>
          <button
            onClick={() => this.setState({ error: null })}
            className="flex items-center gap-1.5 mx-auto px-3 py-1.5 rounded-lg text-xs text-amber-400 active:bg-white/[0.04]"
          >
            <RefreshCw size={12} /> Retry
          </button>
        </div>
      );
    }
    return this.props.children;
  }
}
