/**
 * Page-level error boundary.
 *
 * Wraps entire page components to catch rendering errors while preserving
 * the app shell (navigation, theme, auth). When an error occurs, shows a
 * full-page fallback but the user can still navigate away via the sidebar.
 *
 * Use this for wrapping page components in App.tsx routes.
 */
import React from "react";
import { ErrorBoundary } from "./ErrorBoundary";
import { recordCritical } from "../utils/telemetry";

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

/**
 * Wraps a page component with error boundary protection.
 *
 * @param children - Page component to wrap
 * @param pageName - Name of page for error message (default: "Page")
 * @param onError - Optional callback for error logging
 */
export function PageErrorBoundary({
  children,
  pageName = "Page",
  onError,
}: PageErrorBoundaryProps): React.JSX.Element {
  // Enhanced error handler that includes page name in telemetry
  const handleError = (error: Error, errorInfo: React.ErrorInfo): void => {
    recordCritical("page_render_error", error, {
      page_name: pageName,
      component_stack: errorInfo.componentStack,
    });
    onError?.(error, errorInfo);
  };

  return (
    <ErrorBoundary
      title={`${pageName} Error`}
      message={`The ${pageName.toLowerCase()} encountered an error and could not load. Please try navigating to another page or reloading.`}
      showReloadButton={true}
      isFullPage={false}
      onError={handleError}
    >
      {children}
    </ErrorBoundary>
  );
}
