# Web Vitals Integration Guide

Step-by-step guide to integrate Web Vitals tracking into your Mawidi application.

## Prerequisites

✅ `web-vitals` package is already installed (v5.1.0)
✅ Sentry is already configured in the project

## Integration Steps

### Step 1: Add to Root Layout

Edit `mawidi-site/app/layout.tsx`:

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

export default async function RootLayout({
  children,
  params,
}: {
  children: React.ReactNode;
  params: { lang: string };
}) {
  // ... existing code ...

  return (
    <html lang={lang} dir={dir}>
      <body>
        {/* Add Web Vitals tracking */}
        <WebVitalsReporter />

        {/* Rest of your app */}
        {children}
      </body>
    </html>
  );
}
```

### Step 2: Verify Sentry Configuration

Ensure `NEXT_PUBLIC_SENTRY_DSN` is set in your `.env.local`:

```env
NEXT_PUBLIC_SENTRY_DSN=https://your-sentry-dsn@sentry.io/project-id
```

### Step 3: Test in Development

```bash
npm run dev
```

Open http://localhost:9000 and check the browser console for:

```
[Web Vitals] {
  name: 'LCP',
  value: 1234.56,
  rating: 'good',
  id: 'v3-...'
}
```

### Step 4: Verify in Sentry

1. Navigate to your app
2. Go to Sentry → Performance → Web Vitals
3. You should see metrics for:
   - LCP (Largest Contentful Paint)
   - FID (First Input Delay)
   - CLS (Cumulative Layout Shift)
   - TTFB (Time to First Byte)
   - FCP (First Contentful Paint)
   - INP (Interaction to Next Paint)

## Testing

Run the test suite:

```bash
# Install dependencies first
npm install

# Run Web Vitals tests
npm test -- __tests__/lib/monitoring/web-vitals.test.ts

# Run all tests
npm test
```

## What Gets Tracked

### Automatically Tracked

- **LCP**: Largest element paint time
- **FID**: First user interaction delay
- **CLS**: Layout shift score
- **TTFB**: Server response time
- **FCP**: First content paint
- **INP**: Interaction responsiveness

### Sent to Sentry

Each metric is sent with:
- **Measurement**: Raw value
- **Breadcrumb**: Context for debugging
- **Warning**: If performance is poor

### Sent to Google Analytics (if configured)

If you have GA4 configured with `gtag`, metrics are automatically sent there too.

## Performance Thresholds

| Metric | Good | Needs Improvement | Poor | Action |
|--------|------|-------------------|------|--------|
| LCP | ≤ 2.5s | ≤ 4.0s | > 4.0s | ⚠️ Warning sent to Sentry |
| FID | ≤ 100ms | ≤ 300ms | > 300ms | ⚠️ Warning sent to Sentry |
| CLS | ≤ 0.1 | ≤ 0.25 | > 0.25 | ⚠️ Warning sent to Sentry |
| TTFB | ≤ 800ms | ≤ 1.8s | > 1.8s | ⚠️ Warning sent to Sentry |
| FCP | ≤ 1.8s | ≤ 3.0s | > 3.0s | ⚠️ Warning sent to Sentry |
| INP | ≤ 200ms | ≤ 500ms | > 500ms | ⚠️ Warning sent to Sentry |

## Setting Up Alerts

### In Sentry

1. Go to **Alerts** → **Create Alert**
2. Choose **Web Vitals**
3. Set thresholds:
   - LCP > 4000ms
   - FID > 300ms
   - CLS > 0.25
4. Configure notification channels

### Example Alert Rules

```javascript
// LCP Alert
if (LCP > 4000) {
  alert('Poor LCP performance detected');
}

// FID Alert
if (FID > 300) {
  alert('Poor interactivity detected');
}

// CLS Alert
if (CLS > 0.25) {
  alert('High layout shift detected');
}
```

## Debugging Poor Performance

### High LCP (> 4s)

**Causes:**
- Large images not optimized
- Slow server response
- Render-blocking resources

**Solutions:**
- Use Next.js Image component
- Implement CDN
- Preload critical resources
- Use `priority` prop on hero images

### High FID (> 300ms)

**Causes:**
- Heavy JavaScript execution
- Long tasks blocking main thread
- Unoptimized event handlers

**Solutions:**
- Code split with dynamic imports
- Use Web Workers for heavy computation
- Optimize React renders with useMemo/useCallback
- Defer non-critical JavaScript

### High CLS (> 0.25)

**Causes:**
- Images without dimensions
- Ads/embeds loading dynamically
- Web fonts causing layout shift

**Solutions:**
- Always set width/height on images
- Reserve space for dynamic content
- Use `font-display: swap`
- Avoid inserting content above existing content

## Advanced Usage

### Custom Metric Tracking

```tsx
import { getCurrentMetrics } from '@/lib/monitoring/web-vitals';

// Get current metrics programmatically
async function analyzePerformance() {
  const metrics = await getCurrentMetrics();

  metrics.forEach(metric => {
    console.log(`${metric.name}: ${metric.value}`);
  });
}
```

### Display Metrics in UI (Debug Mode)

```tsx
'use client';

import { useEffect, useState } from 'react';
import { getCurrentMetrics } from '@/lib/monitoring/web-vitals';
import type { Metric } from 'web-vitals';

export function PerformanceDebugPanel() {
  const [metrics, setMetrics] = useState<Metric[]>([]);

  useEffect(() => {
    getCurrentMetrics().then(setMetrics);
  }, []);

  if (process.env.NODE_ENV !== 'development') {
    return null;
  }

  return (
    <div className="fixed bottom-4 right-4 bg-black/80 text-white p-4 rounded-lg text-xs">
      <h3 className="font-bold mb-2">Performance Metrics</h3>
      {metrics.map((metric) => (
        <div key={metric.name} className="flex justify-between gap-4">
          <span>{metric.name}:</span>
          <span className="font-mono">{metric.value.toFixed(2)}</span>
        </div>
      ))}
    </div>
  );
}
```

## Production Checklist

Before deploying to production:

- [ ] Web Vitals tracking is initialized in root layout
- [ ] Sentry DSN is configured in environment variables
- [ ] Tests pass: `npm test -- __tests__/lib/monitoring/web-vitals.test.ts`
- [ ] Verified metrics appear in Sentry dashboard
- [ ] Set up alerts for poor performance thresholds
- [ ] Review baseline metrics from staging environment
- [ ] Document performance budget for your app

## Monitoring Best Practices

1. **Track Trends**: Monitor week-over-week performance
2. **Segment by Page**: Compare performance across different routes
3. **Device Segmentation**: Track mobile vs desktop separately
4. **Geographic Segmentation**: Monitor by region/country
5. **Set Budgets**: Define acceptable performance thresholds
6. **Regular Reviews**: Weekly performance review meetings
7. **Alert Fatigue**: Set realistic thresholds to avoid noise

## Resources

- [Web Vitals Official](https://web.dev/vitals/)
- [Sentry Performance Docs](https://docs.sentry.io/product/performance/)
- [Next.js Performance](https://nextjs.org/docs/app/building-your-application/optimizing)
- [Chrome DevTools Performance](https://developer.chrome.com/docs/devtools/performance/)
