/**
 * Section-level error boundary.
 *
 * Wraps individual data-heavy sections (charts, tables, forms) within a page
 * to provide graceful degradation. When an error occurs, only that section
 * fails to render; the rest of the page remains functional.
 *
 * Use this to wrap:
 * - Charts (BanTrendChart, TopCountriesBarChart, etc.)
 * - Data tables (BanTable, JailOverviewSection, etc.)
 * - Forms with complex logic
 * - Any component that fetches data or has risky side effects
 */
import React from "react";
import { ErrorBoundary } from "./ErrorBoundary";
import { recordWarning } from "../utils/telemetry";

interface SectionErrorBoundaryProps {
  children: React.ReactNode;
  sectionName?: string;
  onError?: (error: Error, errorInfo: React.ErrorInfo) => void;
}

/**
 * Wraps a section component with error boundary protection.
 *
 * @param children - Section component to wrap
 * @param sectionName - Name of section for error message (default: "Section")
 * @param onError - Optional callback for error logging
 */
export function SectionErrorBoundary({
  children,
  sectionName = "Section",
  onError,
}: SectionErrorBoundaryProps): React.JSX.Element {
  // Enhanced error handler that includes section name in telemetry
  const handleError = (error: Error, errorInfo: React.ErrorInfo): void => {
    recordWarning("section_render_error", error.message, {
      section_name: sectionName,
      error_type: error.name,
    });
    onError?.(error, errorInfo);
  };

  return (
    <ErrorBoundary
      title={`${sectionName} Unavailable`}
      message={`Could not load ${sectionName.toLowerCase()}. The rest of the page is still functional.`}
      showReloadButton={true}
      isFullPage={false}
      onError={handleError}
    >
      {children}
    </ErrorBoundary>
  );
}
