// Web Vitals reporting for performance monitoring
import { Metric } from 'web-vitals'

const vitalsUrl = '/api/vitals'

// Function to send vitals to analytics
function sendToAnalytics(metric: Metric) {
  // Log to console in development
  if (process.env.NODE_ENV === 'development') {
    console.log('📊 Web Vitals:', {
      name: metric.name,
      value: metric.value,
      rating: metric.rating,
      delta: metric.delta,
      id: metric.id,
    })
  }

  // Send to Google Analytics if available
  if (typeof window !== 'undefined' && window.gtag) {
    window.gtag('event', metric.name, {
      value: Math.round(metric.name === 'CLS' ? metric.value * 1000 : metric.value),
      event_category: 'Web Vitals',
      event_label: metric.id,
      non_interaction: true,
    })
  }

  // Send to custom API endpoint (optional)
  const body = JSON.stringify({
    name: metric.name,
    value: metric.value,
    rating: metric.rating,
    delta: metric.delta,
    id: metric.id,
    navigationType: metric.navigationType,
  })

  // Use `navigator.sendBeacon()` if available, falling back to `fetch()`
  if (navigator.sendBeacon) {
    navigator.sendBeacon(vitalsUrl, body)
  } else {
    fetch(vitalsUrl, {
      body,
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      keepalive: true,
    }).catch(console.error)
  }
}

// Export the reporting function
export function reportWebVitals(metric: Metric) {
  sendToAnalytics(metric)
}

// Performance thresholds (in milliseconds)
export const PERFORMANCE_THRESHOLDS = {
  // Largest Contentful Paint (LCP)
  LCP: {
    good: 2500,
    needsImprovement: 4000,
  },
  // First Input Delay (FID)
  FID: {
    good: 100,
    needsImprovement: 300,
  },
  // Cumulative Layout Shift (CLS)
  CLS: {
    good: 0.1,
    needsImprovement: 0.25,
  },
  // First Contentful Paint (FCP)
  FCP: {
    good: 1800,
    needsImprovement: 3000,
  },
  // Time to First Byte (TTFB)
  TTFB: {
    good: 800,
    needsImprovement: 1800,
  },
  // Interaction to Next Paint (INP)
  INP: {
    good: 200,
    needsImprovement: 500,
  },
}

// Get rating based on thresholds
export function getRating(
  metricName: keyof typeof PERFORMANCE_THRESHOLDS,
  value: number
): 'good' | 'needs-improvement' | 'poor' {
  const thresholds = PERFORMANCE_THRESHOLDS[metricName]
  
  if (!thresholds) return 'good'
  
  if (value <= thresholds.good) {
    return 'good'
  } else if (value <= thresholds.needsImprovement) {
    return 'needs-improvement'
  } else {
    return 'poor'
  }
}

// Format vitals for display
export function formatVitals(metric: Metric): string {
  const value = metric.name === 'CLS' 
    ? metric.value.toFixed(3)
    : Math.round(metric.value)
  
  const unit = metric.name === 'CLS' ? '' : 'ms'
  
  return `${value}${unit}`
}

// Get performance insights
export function getPerformanceInsights(metrics: Metric[]) {
  const insights: { metric: string; value: string; rating: string; suggestion?: string }[] = []
  
  metrics.forEach((metric) => {
    const formatted = formatVitals(metric)
    const rating = metric.rating || 'unknown'
    
    let suggestion: string | undefined
    
    // Add suggestions based on poor metrics
    if (rating === 'poor') {
      switch (metric.name) {
        case 'LCP':
          suggestion = 'Consider optimizing images, reducing server response times, and removing render-blocking resources'
          break
        case 'FID':
          suggestion = 'Reduce JavaScript execution time and split code into smaller chunks'
          break
        case 'CLS':
          suggestion = 'Add size attributes to images and embeds, and avoid inserting content above existing content'
          break
        case 'FCP':
          suggestion = 'Optimize font loading, eliminate render-blocking resources, and reduce server response times'
          break
        case 'TTFB':
          suggestion = 'Use a CDN, optimize server response times, and implement caching strategies'
          break
        case 'INP':
          suggestion = 'Optimize event handlers, reduce JavaScript execution time, and avoid layout thrashing'
          break
      }
    }
    
    insights.push({
      metric: metric.name,
      value: formatted,
      rating,
      suggestion,
    })
  })
  
  return insights
}

