import React, { Component, ErrorInfo, ReactNode } from 'react'; import { AlertCircle, Home, RefreshCw } from 'lucide-react'; import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'; import { Button } from '@/components/ui/button'; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; import { handleError } from '@/lib/errorHandler'; interface ErrorBoundaryProps { children: ReactNode; fallback?: ReactNode; onError?: (error: Error, errorInfo: ErrorInfo) => void; context?: string; // e.g., "PhotoUpload", "ParkDetail" } interface ErrorBoundaryState { hasError: boolean; error: Error | null; errorInfo: ErrorInfo | null; } type ErrorWithId = Error & { errorId: string }; export class ErrorBoundary extends Component { constructor(props: ErrorBoundaryProps) { super(props); this.state = { hasError: false, error: null, errorInfo: null, }; } static getDerivedStateFromError(error: Error): Partial { return { hasError: true, error, }; } componentDidCatch(error: Error, errorInfo: ErrorInfo) { // Log to database and get error ID for user reference const errorId = handleError(error, { action: `Component error in ${this.props.context || 'unknown context'}`, metadata: { context: this.props.context, componentStack: errorInfo.componentStack, }, }); this.setState({ errorInfo, error: { ...error, errorId } as ErrorWithId }); this.props.onError?.(error, errorInfo); } handleRetry = () => { this.setState({ hasError: false, error: null, errorInfo: null, }); }; handleGoHome = () => { window.location.href = '/'; }; render() { if (this.state.hasError) { if (this.props.fallback) { return this.props.fallback; } return (
Something Went Wrong {this.props.context ? `An error occurred in ${this.props.context}` : 'An unexpected error occurred'} Error Details

{this.state.error?.message || 'An unexpected error occurred'}

{(this.state.error as ErrorWithId)?.errorId && (

Reference ID: {(this.state.error as ErrorWithId).errorId.slice(0, 8)}

)}
{import.meta.env.DEV && this.state.errorInfo && (
Show Component Stack (Development Only)
                    {this.state.errorInfo.componentStack}
                  
)}
); } return this.props.children; } }