"use client";

import { useReportWebVitals } from "next/web-vitals";

/**
 * Web Vitals monitoring component
 * Tracks Core Web Vitals and sends to analytics
 */
export function WebVitals() {
  useReportWebVitals((metric) => {
    // Log to console in development
    if (process.env.NODE_ENV === "development") {
      console.log("📊 Web Vital:", metric);
    }

    // Send to analytics in production
    if (process.env.NODE_ENV === "production") {
      // Example: Send to Google Analytics
      // window.gtag?.('event', metric.name, {
      //   value: Math.round(metric.name === 'CLS' ? metric.value * 1000 : metric.value),
      //   event_label: metric.id,
      //   non_interaction: true,
      // });
      // Example: Send to custom analytics endpoint
      // fetch('/api/analytics', {
      //   method: 'POST',
      //   body: JSON.stringify({
      //     name: metric.name,
      //     value: metric.value,
      //     rating: metric.rating,
      //     delta: metric.delta,
      //     id: metric.id,
      //   }),
      // }).catch(() => {});
    }

    // Performance thresholds
    const thresholds = {
      LCP: { good: 2500, needsImprovement: 4000 },
      FID: { good: 100, needsImprovement: 300 },
      CLS: { good: 0.1, needsImprovement: 0.25 },
      FCP: { good: 1800, needsImprovement: 3000 },
      TTFB: { good: 800, needsImprovement: 1800 },
      INP: { good: 200, needsImprovement: 500 },
    };

    const threshold = thresholds[metric.name as keyof typeof thresholds];
    if (threshold) {
      const { good, needsImprovement } = threshold;
      const value = metric.name === "CLS" ? metric.value * 1000 : metric.value;

      if (value <= good) {
        // Good performance - no action needed
      } else if (value <= needsImprovement) {
        console.warn(`⚠️ ${metric.name} needs improvement:`, value);
      } else {
        console.warn(`❌ ${metric.name} is poor:`, value);
      }
    }
  });

  return null;
}
