'use client';

import { useEffect } from 'react';
import { onLCP, onINP, onCLS, onFCP, onTTFB, type Metric } from 'web-vitals';

const VITALS_ENDPOINT = '/api/v1/internal/vitals';

/**
 * Reports Core Web Vitals to the backend so we have a baseline before
 * any perf-optimisation work. Sends via `sendBeacon` (survives unload)
 * with a `fetch` fallback for browsers that don't support beacon.
 *
 * Mounted in the dashboard layout - fires once per page lifecycle for
 * each metric. Vitals are reported when stable (LCP locked in, INP after
 * meaningful interaction, etc.), not on every render.
 */
export function WebVitalsReporter() {
  useEffect(() => {
    function report(metric: Metric) {
      const path = typeof window !== 'undefined' ? window.location.pathname : null;

      const body = JSON.stringify({
        name: metric.name,
        value: metric.value,
        rating: metric.rating,
        id: metric.id,
        delta: metric.delta,
        navigationType: metric.navigationType,
        path,
      });

      if (typeof navigator !== 'undefined' && navigator.sendBeacon) {
        navigator.sendBeacon(VITALS_ENDPOINT, new Blob([body], { type: 'application/json' }));
        return;
      }

      // Fallback for browsers without sendBeacon.
      fetch(VITALS_ENDPOINT, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body,
        keepalive: true,
      }).catch(() => {
        // Swallow - vitals are best-effort.
      });
    }

    onLCP(report);
    onINP(report);
    onCLS(report);
    onFCP(report);
    onTTFB(report);
  }, []);

  return null;
}
