'use client';

import { useReportWebVitals } from 'next/web-vitals';
import { useSelectedLayoutSegment } from 'next/navigation';
import { usePathname } from 'next/navigation';
import settings from 'settings';

export function WebVitals() {
  let layoutSegment = useSelectedLayoutSegment();
  const pathname = usePathname();
  const { enabled } = settings.webVitals || { enabled: false };

  if (pathname === '/' && layoutSegment === null) {
    layoutSegment = 'home';
  }

  useReportWebVitals((metric) => {
    if (process.env.NODE_ENV !== 'development' || !enabled) {
      return;
    }

    const { name, value, rating } = metric;
    const page = layoutSegment || 'unknown';

    fetch(`/api/web-vitals`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ name, value, rating, page, pathname })
    });
  });

  return null;
}
