# Error Handling & Loading States Implementation Guide

This guide covers the comprehensive error handling and loading state system implemented for the Black Canyon Tickets React rebuild.

## 🎯 Overview

The system provides robust error boundaries, loading states, and skeleton components that:
- Catch and gracefully handle JavaScript errors
- Provide smooth loading experiences with skeleton UI
- Follow the glassmorphism design system
- Include accessibility features
- Support timeout handling for slow connections

## 📁 File Structure

```
src/
├── components/
│   ├── errors/
│   │   ├── AppErrorBoundary.tsx    # Main error boundary component
│   │   └── index.ts                # Error components exports
│   ├── loading/
│   │   ├── LoadingSpinner.tsx      # Spinner components with variants
│   │   ├── RouteSuspense.tsx       # Suspense wrapper with timeout
│   │   ├── Skeleton.tsx            # Skeleton loading components
│   │   └── index.ts                # Loading components exports
│   └── ErrorBoundaryDemo.tsx       # Demo component (optional)
├── pages/
│   └── ErrorPage.tsx               # Error page components (404, 500, etc.)
└── types/
    └── errors.ts                   # Error type definitions
```

## 🚨 Error Handling Components

### AppErrorBoundary

**Location:** `src/components/errors/AppErrorBoundary.tsx`

**Purpose:** Catches JavaScript errors in React component tree and displays fallback UI.

**Features:**
- ✅ Automatic error detection and categorization
- ✅ Retry functionality with attempt limits
- ✅ Error severity assessment
- ✅ Development mode debugging info
- ✅ Recovery strategies (retry, reload, redirect)
- ✅ Glassmorphism fallback UI
- ✅ Error reporting integration points

**Usage:**
```tsx
import { AppErrorBoundary } from './components/errors/AppErrorBoundary';

// Wrap your app or components
<AppErrorBoundary 
  onError={(error) => console.log('Error:', error)}
  maxRetries={3}
>
  <YourAppComponents />
</AppErrorBoundary>
```

**Error Types Supported:**
- `network` - Connection and API errors
- `auth` - Authentication/authorization errors  
- `permission` - Access control errors
- `validation` - Form/data validation errors
- `timeout` - Request timeout errors
- `rate_limit` - Rate limiting errors
- `generic` - General JavaScript errors

### ErrorPage Components

**Location:** `src/pages/ErrorPage.tsx`

**Purpose:** Dedicated error pages for different error scenarios.

**Components Available:**
- `ErrorPage` - Base error page component
- `NotFoundPage` - 404 page
- `UnauthorizedPage` - 403 page  
- `ServerErrorPage` - 500 page
- `NetworkErrorPage` - Network error page
- `TimeoutErrorPage` - Timeout error page
- `MaintenancePage` - Maintenance mode page

**Features:**
- ✅ Glassmorphism styling
- ✅ Contextual error messages
- ✅ Action buttons (retry, go home, go back)
- ✅ Support information
- ✅ Development debugging details

**Usage:**
```tsx
import { NotFoundPage, UnauthorizedPage } from './pages/ErrorPage';

// In your router
<Route path="/unauthorized" element={<UnauthorizedPage />} />
<Route path="*" element={<NotFoundPage />} />
```

## ⏳ Loading State Components

### LoadingSpinner

**Location:** `src/components/loading/LoadingSpinner.tsx`

**Purpose:** Animated loading spinners with multiple variants.

**Variants:**
- `LoadingSpinner` - Main animated spinner
- `PulseLoader` - Simple pulse animation
- `ShimmerLoader` - Shimmer effect with gradient
- `DotsLoader` - Three-dot bouncing animation

**Features:**
- ✅ Multiple sizes (sm, md, lg, xl)
- ✅ Color variants (primary, secondary, accent, muted)
- ✅ Overlay mode for full-screen loading
- ✅ Optional text labels
- ✅ Glassmorphism styling

**Usage:**
```tsx
import { LoadingSpinner } from './components/loading/LoadingSpinner';

<LoadingSpinner 
  size="lg" 
  variant="accent" 
  text="Loading..." 
  overlay={true}
/>
```

### RouteSuspense

**Location:** `src/components/loading/RouteSuspense.tsx`

**Purpose:** Enhanced Suspense wrapper for route-level code splitting.

**Features:**
- ✅ Timeout handling (default 10s)
- ✅ Progressive loading states
- ✅ Multiple skeleton types
- ✅ Retry functionality
- ✅ Accessibility announcements

**Usage:**
```tsx
import { RouteSuspense } from './components/loading/RouteSuspense';

<RouteSuspense 
  skeletonType="page"
  loadingText="Loading application..."
  timeout={15000}
>
  <LazyLoadedComponent />
</RouteSuspense>
```

**Skeleton Types:**
- `page` - Full page skeleton layout
- `card` - Card-based skeleton layout
- `list` - List item skeleton layout
- `table` - Table skeleton layout
- `custom` - Simple spinner fallback

### Skeleton Components

**Location:** `src/components/loading/Skeleton.tsx`

**Purpose:** Comprehensive skeleton loading components.

**Components Available:**
- `BaseSkeleton` - Core skeleton element
- `TextSkeleton` - Multi-line text skeleton
- `AvatarSkeleton` - Circular avatar skeleton
- `ButtonSkeleton` - Button-shaped skeleton
- `Skeleton.Card` - Card layout skeleton
- `Skeleton.List` - List layout skeleton
- `Skeleton.Table` - Table layout skeleton
- `Skeleton.Page` - Full page layout skeleton
- `Skeleton.Form` - Form layout skeleton

**Features:**
- ✅ Glassmorphism styling
- ✅ Animate pulse effect
- ✅ Responsive layouts
- ✅ Realistic content shapes
- ✅ Loading text indicators

**Usage:**
```tsx
import { Skeleton } from './components/loading/Skeleton';

// Full page skeleton
<Skeleton.Page loadingText="Loading dashboard..." />

// Individual skeleton elements
<Skeleton.Text lines={3} />
<Skeleton.Avatar size="lg" />
<Skeleton.Button size="md" />
```

## 🔧 Integration Guide

### 1. App-Level Integration

**Update App.tsx:**
```tsx
import { AppErrorBoundary } from './components/errors/AppErrorBoundary';
import { RouteSuspense } from './components/loading/RouteSuspense';

function App() {
  return (
    <AppErrorBoundary>
      <AuthProvider>
        <Router>
          <RouteSuspense skeletonType="page" timeout={15000}>
            <Routes>
              {/* Your routes */}
            </Routes>
          </RouteSuspense>
        </Router>
      </AuthProvider>
    </AppErrorBoundary>
  );
}
```

### 2. Route-Level Protection

**Update ProtectedRoute.tsx:**
```tsx
import { Skeleton } from '../loading/Skeleton';

// Show skeleton during auth check
if (isLoading) {
  return <Skeleton.Page loadingText="Verifying authentication..." />;
}
```

### 3. Error Route Setup

**Add error routes:**
```tsx
import { 
  NotFoundPage, 
  UnauthorizedPage, 
  ServerErrorPage 
} from './pages/ErrorPage';

// In your Routes
<Route path="/unauthorized" element={<UnauthorizedPage />} />
<Route path="/error/server" element={<ServerErrorPage />} />
<Route path="*" element={<NotFoundPage />} />
```

## 🎨 Design System Integration

All components use the established design tokens:

**Colors:**
- `background-primary/secondary` - Page backgrounds
- `glass-bg/border` - Glassmorphism elements
- `text-primary/secondary/muted` - Text hierarchy
- `error/warning/info/success-*` - Semantic colors
- `gold-*` - Accent colors

**Spacing:**
- `p-lg, space-y-lg` - Large spacing
- `p-md, space-y-md` - Medium spacing  
- `p-sm, space-y-sm` - Small spacing

**Animations:**
- `animate-pulse` - Skeleton animations
- `animate-spin` - Spinner rotations
- `animate-shimmer` - Shimmer effects

## ♿ Accessibility Features

**Screen Reader Support:**
- Loading announcements with `aria-live="polite"`
- Proper `role="status"` for loading states
- Descriptive `aria-label` attributes

**Keyboard Navigation:**
- Focus management in error states
- Accessible action buttons
- Proper heading hierarchy

**Visual Accessibility:**
- High contrast colors
- Smooth animations (respects prefers-reduced-motion)
- Clear error messaging

## 🧪 Testing

**Demo Component:**
Use `ErrorBoundaryDemo` component to test all functionality:

```tsx
import { ErrorBoundaryDemo } from './components/ErrorBoundaryDemo';

// Add to your routes for testing
<Route path="/demo/errors" element={<ErrorBoundaryDemo />} />
```

**Features Tested:**
- ✅ Error boundary catching
- ✅ Loading state transitions
- ✅ Skeleton component variants
- ✅ Spinner animations
- ✅ Timeout handling
- ✅ Recovery mechanisms

## 📋 Best Practices

### Error Boundaries
1. **Wrap at Multiple Levels:** Use both app-level and component-level boundaries
2. **Error Logging:** Always integrate with error reporting service
3. **User-Friendly Messages:** Avoid technical error details in production
4. **Recovery Options:** Provide clear next steps for users

### Loading States
1. **Immediate Feedback:** Show loading UI within 100ms
2. **Skeleton Matching:** Make skeleton shapes match final content
3. **Timeout Handling:** Always handle slow network scenarios
4. **Progressive Loading:** Load critical content first

### Performance
1. **Lazy Loading:** Use React.lazy() with RouteSuspense
2. **Code Splitting:** Split large components and routes
3. **Skeleton Efficiency:** Use CSS animations over JavaScript
4. **Error Boundary Scope:** Keep boundaries focused to prevent large UI breaks

## 🔮 Future Enhancements

**Planned Features:**
- [ ] Offline error handling
- [ ] Progressive Web App integration
- [ ] Advanced error analytics
- [ ] Custom skeleton builder
- [ ] Animation customization
- [ ] Error boundary testing utilities

**Integration Opportunities:**
- [ ] Sentry error reporting
- [ ] LogRocket session replay
- [ ] Performance monitoring
- [ ] A/B testing for error UX
- [ ] User feedback collection

This implementation provides a solid foundation for error handling and loading states that can evolve with your application's needs while maintaining excellent user experience.