# Performance Optimization Guide

This document outlines the performance optimizations implemented in the customer portal and provides guidelines for maintaining optimal performance.

## Bundle Size Optimization

### Code Splitting Strategy

The application implements several code splitting strategies:

1. **Route-level splitting**: Each page is automatically split by Next.js
2. **Feature-level splitting**: Heavy features are lazy-loaded using dynamic imports
3. **Component-level splitting**: Heavy components are lazy-loaded on demand

### Lazy Loading Components

Use the lazy loading utilities for heavy components:

```typescript
import { LazyComponent } from '@/components/common';
import { LazyDataUsageChart } from '@/components/lazy';

// Wrap heavy components
<LazyComponent>
  <LazyDataUsageChart usage={usage} />
</LazyComponent>
```

### Bundle Analysis

Monitor bundle size using the built-in analyzer:

```bash
# Analyze bundle size
pnpm run build:analyze

# Monitor bundle size with reporting
pnpm run build:monitor
```

## Performance Monitoring

### Core Web Vitals

The application automatically monitors Core Web Vitals:

```typescript
import { WebVitalsMonitor } from '@/components/common';

// Add to your app root
<WebVitalsMonitor
  onMetric={(metric) => console.log(metric)}
  reportToAnalytics={true}
/>
```

### Performance Hooks

Use performance monitoring hooks:

```typescript
import { usePerformanceMonitor, useComponentLoadTime } from "@/hooks/use-performance-monitor";

function MyComponent() {
  useComponentLoadTime("MyComponent");
  const { performanceData } = usePerformanceMonitor();

  // Component logic
}
```

## React Query Optimization

### Optimized Query Hooks

Use optimized query hooks for better caching:

```typescript
import { useOptimizedQuery } from "@/hooks/use-optimized-query";

// Use with data type for optimal caching
const { data } = useOptimizedQuery({
  queryKey: ["invoices"],
  queryFn: fetchInvoices,
  dataType: "financial", // Shorter cache for financial data
});
```

### Query Key Factories

Use consistent query keys for better cache management:

```typescript
import { queryKeys } from "@/lib/query-client";

// Consistent query keys
const invoicesQuery = useQuery({
  queryKey: queryKeys.billing.invoices({ status: "unpaid" }),
  queryFn: () => fetchInvoices({ status: "unpaid" }),
});
```

## Image Optimization

### Optimized Image Components

Use optimized image components for better performance:

```typescript
import { OptimizedImage, LazyImage, EagerImage } from '@/components/common';

// For above-the-fold images
<EagerImage src="/hero.jpg" alt="Hero" width={800} height={400} />

// For below-the-fold images
<LazyImage src="/product.jpg" alt="Product" width={400} height={300} />

// With fallback
<OptimizedImage
  src="/image.jpg"
  fallbackSrc="/placeholder.jpg"
  alt="Image"
  width={300}
  height={200}
/>
```

## Route Preloading

### Preloading Links

Use preloading links for better navigation performance:

```typescript
import { PreloadingLink } from '@/components/common';

// Automatically preloads route on hover
<PreloadingLink href="/dashboard">
  Dashboard
</PreloadingLink>
```

### Manual Preloading

Preload routes programmatically:

```typescript
import { preloadRoute } from '@/lib/utils/route-preloader';

// Preload route when user shows intent
onMouseEnter={() => preloadRoute('/billing')}
```

## Performance Budget

### Bundle Size Limits

- Total bundle size: 1MB
- Individual chunks: 250KB
- Vendor chunks: 500KB

### Core Web Vitals Targets

- **FCP (First Contentful Paint)**: < 1.8s
- **LCP (Largest Contentful Paint)**: < 2.5s
- **FID (First Input Delay)**: < 100ms
- **CLS (Cumulative Layout Shift)**: < 0.1
- **TTFB (Time to First Byte)**: < 800ms

## Best Practices

### 1. Component Design

- Keep components small and focused
- Use React.memo for expensive components
- Implement proper loading states
- Avoid unnecessary re-renders

### 2. Data Fetching

- Use appropriate cache strategies
- Implement optimistic updates
- Prefetch critical data
- Use background synchronization

### 3. Asset Optimization

- Optimize images with proper formats
- Use lazy loading for non-critical assets
- Implement proper caching headers
- Minimize CSS and JavaScript

### 4. Monitoring

- Monitor Core Web Vitals regularly
- Track bundle size changes
- Set up performance alerts
- Use real user monitoring (RUM)

## Development Tools

### Performance Monitor (Development Only)

The development performance monitor shows real-time metrics:

```typescript
import { PerformanceToggle } from '@/components/dev/performance-monitor';

// Add to development layout
{process.env.NODE_ENV === 'development' && <PerformanceToggle />}
```

### Bundle Analysis

Regular bundle analysis helps identify optimization opportunities:

```bash
# Generate bundle analysis report
pnpm run build:analyze

# Monitor bundle size over time
pnpm run build:monitor
```

## Troubleshooting

### Large Bundle Size

1. Check for duplicate dependencies
2. Implement code splitting
3. Use dynamic imports
4. Remove unused code

### Poor Core Web Vitals

1. Optimize images and assets
2. Reduce JavaScript execution time
3. Minimize layout shifts
4. Improve server response times

### Slow Route Transitions

1. Implement route preloading
2. Use lazy loading for heavy components
3. Optimize data fetching
4. Reduce component complexity

## Continuous Monitoring

Set up automated monitoring:

1. **CI/CD Integration**: Add bundle size checks to CI/CD pipeline
2. **Performance Alerts**: Set up alerts for performance regressions
3. **Regular Audits**: Schedule regular performance audits
4. **User Monitoring**: Implement real user monitoring

## Resources

- [Next.js Performance](https://nextjs.org/docs/advanced-features/measuring-performance)
- [Web Vitals](https://web.dev/vitals/)
- [React Query Performance](https://tanstack.com/query/latest/docs/react/guides/performance)
- [Bundle Analysis](https://nextjs.org/docs/advanced-features/analyzing-bundles)
