/**
 * React Error Boundary component.
 *
 * Catches JavaScript errors anywhere in the child component tree,
 * logs them, and displays a fallback UI instead of a crashed app.
 *
 * Usage:
 *   <ErrorBoundary fallback={<AnalyticsErrorFallback />}>
 *     <CampaignAnalytics />
 *   </ErrorBoundary>
 */

"use client";

import { Component, type ErrorInfo, type ReactNode } from "react";
import { reportError } from "@/lib/error-reporting";

interface ErrorBoundaryProps {
  children: ReactNode;
  fallback?: ReactNode | ((props: { error: Error; reset: () => void }) => ReactNode);
  onError?: (error: Error, errorInfo: ErrorInfo) => void;
}

interface ErrorBoundaryState {
  hasError: boolean;
  error: Error | null;
}

export class ErrorBoundary extends Component<ErrorBoundaryProps, ErrorBoundaryState> {
  constructor(props: ErrorBoundaryProps) {
    super(props);
    this.state = { hasError: false, error: null };
  }

  static getDerivedStateFromError(error: Error): ErrorBoundaryState {
    return { hasError: true, error };
  }

  componentDidCatch(error: Error, errorInfo: ErrorInfo) {
    // Report to Slack via /api/report-error
    reportError(error, {
      componentStack: errorInfo.componentStack,
      source: "ErrorBoundary",
    });

    // Call optional external error handler
    this.props.onError?.(error, errorInfo);
  }

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

  render() {
    if (this.state.hasError) {
      const { fallback } = this.props;
      if (typeof fallback === "function") {
        return fallback({ error: this.state.error!, reset: this.reset });
      }
      if (fallback) {
        return fallback;
      }
      // Default fallback
      return (
        <div className="flex flex-col items-center justify-center p-8 text-center">
          <div className="text-4xl mb-4">⚠️</div>
          <h2 className="text-lg font-semibold text-gray-900 mb-2">Something went wrong</h2>
          <p className="text-sm text-gray-500 mb-4 max-w-md">
            {this.state.error?.message || "An unexpected error occurred."}
          </p>
          <button
            onClick={this.reset}
            className="px-4 py-2 text-sm font-medium text-blue-600 bg-blue-50 rounded-lg hover:bg-blue-100 transition-colors"
          >
            Try again
          </button>
        </div>
      );
    }

    return this.props.children;
  }
}

/**
 * Pre-built fallback UI for analytics components.
 */
export function AnalyticsErrorFallback({
  error,
  reset,
}: {
  error: Error;
  reset: () => void;
}) {
  return (
    <div className="rounded-lg border border-red-200 bg-red-50 p-6">
      <div className="flex items-start gap-3">
        <span className="text-2xl">📊</span>
        <div className="flex-1">
          <h3 className="text-sm font-semibold text-red-800">Analytics failed to load</h3>
          <p className="mt-1 text-xs text-red-600">{error.message}</p>
          <button
            onClick={reset}
            className="mt-3 px-3 py-1.5 text-xs font-medium text-red-700 bg-red-100 rounded-md hover:bg-red-200 transition-colors"
          >
            Retry
          </button>
        </div>
      </div>
    </div>
  );
}
