# Performance Optimization Testing Guide

This guide will help you test and verify the performance improvements implemented in the home page.

## Quick Start Testing

### 1. Check Cache Implementation
Open browser developer tools and run:
```javascript
// Check if cache is working
console.log('Cache stats:', window.CacheManager?.getAnalytics());

// Test cache functionality
localStorage.setItem('cache_test', JSON.stringify({data: 'test', timestamp: Date.now()}));
console.log('Cache test:', localStorage.getItem('cache_test'));
```

### 2. Monitor Network Requests
1. Open Developer Tools (F12)
2. Go to Network tab
3. Refresh the page
4. Look for:
   - Reduced API calls on subsequent loads
   - Faster load times for cached data
   - Optimized image loading

### 3. Performance Monitoring
The built-in performance panel shows:
- Cache hit rates
- API response times
- Memory usage
- Loading performance

## Detailed Testing Scenarios

### Cache Performance
```javascript
// Test product cache
const testProductCache = async () => {
  console.time('First load');
  const response1 = await fetch('/api/products');
  console.timeEnd('First load');
  
  console.time('Cached load');
  const response2 = await fetch('/api/products');
  console.timeEnd('Cached load');
  
  console.log('Cache should make second load faster');
};

testProductCache();
```

### Lazy Loading Test
1. Open Network tab
2. Scroll slowly down the page
3. Watch components load as they come into view
4. Components should load with the configured delays

### Image Optimization
1. Check Network tab for image requests
2. Verify WebP format is used (when supported)
3. Look for blur placeholders during loading
4. Test on slow network (throttle to 3G)

## Performance Metrics to Monitor

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

### Custom Metrics
- **Cache Hit Rate**: Target 80%+
- **API Response Time**: Target < 1s
- **Page Load Time**: Target < 3s

## Testing Commands

### Network Simulation
```javascript
// Simulate slow connection
navigator.connection = {
  effectiveType: '2g',
  downlink: 0.5,
  rtt: 200,
  saveData: true
};
```

### Cache Analysis
```javascript
// Analyze cache performance
const analyzeCache = () => {
  const stats = window.CacheManager.getAnalytics();
  console.table(stats);
  
  const health = window.CacheManager.healthCheck();
  console.log('Cache health:', health);
};

analyzeCache();
```

### Performance Profiling
```javascript
// Measure page load performance
const measurePageLoad = () => {
  const navigation = performance.getEntriesByType('navigation')[0];
  console.log('Page load metrics:', {
    dns: navigation.domainLookupEnd - navigation.domainLookupStart,
    tcp: navigation.connectEnd - navigation.connectStart,
    request: navigation.responseStart - navigation.requestStart,
    response: navigation.responseEnd - navigation.responseStart,
    domComplete: navigation.domComplete - navigation.navigationStart,
    loadComplete: navigation.loadEventEnd - navigation.navigationStart
  });
};

// Run after page loads
window.addEventListener('load', measurePageLoad);
```

## Expected Results

### Before Optimization
- Multiple API calls for same data
- Slower image loading
- All components load immediately
- No caching between visits

### After Optimization
- ✅ Cached data reduces API calls by 60-80%
- ✅ Images load progressively with placeholders
- ✅ Components lazy load as needed
- ✅ Data persists between page visits
- ✅ Faster perceived loading
- ✅ Better Core Web Vitals scores

## Troubleshooting

### Cache Not Working
```javascript
// Clear and test cache
localStorage.clear();
window.CacheManager.warmCache();
```

### Slow Loading
1. Check Network tab for failed requests
2. Verify cache is enabled
3. Check console for errors
4. Test on faster connection

### Images Not Optimizing
1. Verify Next.js Image component is used
2. Check image formats in Network tab
3. Ensure proper sizes are configured

## Browser Support

### Required Features
- ✅ LocalStorage (all modern browsers)
- ✅ Intersection Observer (IE11+ with polyfill)
- ✅ Fetch API (all modern browsers)

### Enhanced Features
- WebP images (90%+ browser support)
- Connection API (Chrome, Firefox)
- Device Memory API (Chrome only)

## Performance Benchmarks

Run these tests to validate improvements:

### Lighthouse Audit
1. Open DevTools
2. Go to Lighthouse tab
3. Run Performance audit
4. Target scores:
   - Performance: 90+
   - Accessibility: 95+
   - Best Practices: 95+
   - SEO: 95+

### WebPageTest
Use https://webpagetest.org with your deployed URL:
- First View: < 3s
- Repeat View: < 1s (with cache)
- Speed Index: < 2s

## Monitoring Setup

### Development
The performance panel automatically tracks:
- Cache statistics
- API response times
- Component render times
- Memory usage

### Production
Consider adding:
- Real User Monitoring (RUM)
- Core Web Vitals tracking
- Error monitoring
- Performance alerts

## Cache Management

### Manual Cache Control
```javascript
// Clear specific cache
delete localStorage.cache_products_page1;

// Warm critical cache
CacheManager.preloadHomePageData();

// Full cache cleanup
CacheManager.smartCleanup();

// Export cache for debugging
const cacheData = CacheManager.exportCacheData();
console.log('Cache export:', cacheData);
```

### Automatic Cleanup
The cache automatically:
- Removes expired items
- Cleans up every 5 minutes
- Limits total size to 10MB
- Maintains max 100 items

This comprehensive optimization should significantly improve your home page performance! 🚀