'use client';

import { usePathname } from 'next/navigation';
import { useEffect, useRef } from 'react';

/**
 * Cookie-less page-view beacon. Sends only the path (and, on the first view, the referrer, which
 * the server reduces to a host). Skips entirely when the browser signals Do Not Track or Global
 * Privacy Control — the server re-checks both headers anyway.
 */
export function AnalyticsBeacon() {
  const pathname = usePathname();
  const lastSent = useRef<string | null>(null);

  useEffect(() => {
    // Dedupe: StrictMode re-runs effects in dev, and the same path must not count twice.
    if (!pathname || lastSent.current === pathname) return;
    const nav = navigator as Navigator & { globalPrivacyControl?: boolean };
    if (nav.doNotTrack === '1' || nav.globalPrivacyControl === true) return;

    const isFirstView = lastSent.current === null;
    lastSent.current = pathname;
    const body = JSON.stringify({ p: pathname, r: isFirstView && document.referrer ? document.referrer : null });
    try {
      // A plain string is sent as text/plain: no CORS preflight, survives page unloads.
      if (typeof nav.sendBeacon === 'function' && nav.sendBeacon('/api/a', body)) return;
      void fetch('/api/a', { method: 'POST', body, keepalive: true, credentials: 'omit' }).catch(() => undefined);
    } catch {
      // Analytics must never break the page.
    }
  }, [pathname]);

  return null;
}
