'use client';

import { useEffect } from 'react';

/**
 * Client component that initialises Core Web Vitals reporting.
 *
 * Tracks: LCP, FCP, CLS, TTFB, INP (the five web-vitals v5 metrics).
 * FID was deprecated — INP is the modern responsiveness metric;
 * FCP (First Contentful Paint) replaces FID in the library.
 *
 * Metrics are batched and sent to the backend `/web-vitals` endpoint via
 * `navigator.sendBeacon` for reliability during page transitions.
 */
export function WebVitals() {
  useEffect(() => {
    // Dynamic import so the library is only loaded in the browser
    import('web-vitals').then(({ onLCP, onFCP, onCLS, onTTFB, onINP }) => {
      import('@/lib/web-vitals').then(({ reportWebVital, flushWebVitals }) => {
        onLCP(reportWebVital);
        onFCP(reportWebVital);
        onCLS(reportWebVital);
        onTTFB(reportWebVital);
        onINP(reportWebVital);

        // Flush remaining metrics when the page is hidden (tab switch, close, navigate)
        const handleVisibilityChange = () => {
          if (document.visibilityState === 'hidden') {
            flushWebVitals();
          }
        };
        document.addEventListener('visibilitychange', handleVisibilityChange);

        return () => {
          document.removeEventListener('visibilitychange', handleVisibilityChange);
        };
      });
    });
  }, []);

  return null;
}
