'use client';

import { useEffect } from 'react';

/** First-party analytics beacon (PostHog can be added via NEXT_PUBLIC_POSTHOG_KEY). No cookies, no PII. */
export function Beacon({ event = 'page_view', entityType, entityId }: { event?: string; entityType?: string; entityId?: number }) {
  useEffect(() => {
    let sid: string | null = null;
    try {
      sid = sessionStorage.getItem('lr_sid');
      if (!sid) {
        sid = Math.random().toString(36).slice(2) + Date.now().toString(36);
        sessionStorage.setItem('lr_sid', sid);
      }
    } catch {
      /* storage blocked */
    }
    // Referrer host only (e.g. "www.google.com") — never the full URL, which can carry personal data
    let referrer: string | undefined;
    try {
      const host = document.referrer ? new URL(document.referrer).host : '';
      referrer = host && host !== location.host ? host.slice(0, 200) : undefined;
    } catch {
      /* malformed referrer */
    }
    const body = JSON.stringify({ event, path: location.pathname, entityType, entityId, sessionId: sid ?? undefined, ...(referrer ? { properties: { referrer } } : {}) });
    if (navigator.sendBeacon) navigator.sendBeacon('/api/v1/analytics/events/', new Blob([body], { type: 'application/json' }));
    else fetch('/api/v1/analytics/events/', { method: 'POST', headers: { 'content-type': 'application/json' }, body, keepalive: true }).catch(() => {});
  }, [event, entityType, entityId]);
  return null;
}
