# Performance Optimization Documentation

## Code Splitting

### Route-based Splitting
- Chat page: Lazy loaded TypingIndicator
- Admin dashboard: Lazy loaded chart components (UserGrowthChart, RevenueChart)
- Admin settings: Lazy loaded settings forms (GeneralSettings, EmailSettings, SecuritySettings)
- Admin users: Lazy loaded UserDetailsModal

### Component-based Splitting
- Heavy components wrapped with `React.lazy()` and `React.Suspense`
- Fallback loading states provided for better UX

## Image Optimization

### Next.js Image Configuration
- **Formats**: AVIF and WebP (automatic format selection)
- **Device sizes**: Responsive breakpoints (640px to 3840px)
- **Image sizes**: Optimized sizes for different use cases
- **Lazy loading**: All images use `loading="lazy"` attribute

### Implementation
- Avatar images: Using Radix UI AvatarImage (supports lazy loading)
- QR codes: Using `<img>` with `loading="lazy"` (data URLs not supported by Next.js Image)

## Lazy Loading

### Components
- TypingIndicator: Lazy loaded in chat page
- Chart components: Lazy loaded in admin dashboard
- Modal components: Lazy loaded when needed
- Settings forms: Lazy loaded per tab

### Images
- All images use `loading="lazy"` attribute
- Avatar images support lazy loading through Radix UI

### Routes
- Dynamic imports for route-based code splitting (Next.js App Router handles this automatically)

## Caching Strategy

### Browser Caching
- **Static assets**: 1 year cache (`Cache-Control: public, max-age=31536000, immutable`)
- Configured in `next.config.js` headers

### API Response Caching
- **React Query**: 5 minutes stale time, 10 minutes cache time
- Automatic refetching on window focus (disabled for better UX)
- Retry failed requests once

### Session Storage
- User data: Stored in Zustand stores with persistence
- Chat conversations: Persisted to localStorage
- Theme preferences: Persisted to localStorage

## Performance Targets

### Lighthouse Scores
- **Performance**: 90+
- **Accessibility**: 95+
- **Best Practices**: 95+
- **SEO**: 100

### Core Web Vitals
- **LCP** (Largest Contentful Paint): < 2.5s
- **FID** (First Input Delay): < 100ms
- **CLS** (Cumulative Layout Shift): < 0.1

## Optimization Techniques

1. **Code Splitting**: Route and component-based splitting
2. **Image Optimization**: WebP/AVIF formats, responsive images, lazy loading
3. **Caching**: Browser caching for static assets, React Query for API responses
4. **Compression**: Gzip/Brotli compression enabled
5. **Console Removal**: Production builds remove console.log (except errors/warnings)
