'use client';
import {useEffect}from 'react';
import {usePathname}from 'next/navigation';
/** Counts page views and ordinary same-site link clicks; does not collect identities. */
export function InsightsBeacon(){
 const path=usePathname();
 useEffect(()=>{
  if(!path)return;
  const send=(data:Record<string,string>)=>void fetch('/api/insights/event',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(data),keepalive:true,credentials:'same-origin'}).catch(()=>{});
  send({kind:'page_view',path});
  const handler=(event:MouseEvent)=>{
   if(!(event.target instanceof Element))return;
   const link=event.target.closest('a[href]');if(!(link instanceof HTMLAnchorElement))return;
   const destination=new URL(link.href,location.origin);
   if(destination.origin!==location.origin||destination.pathname===path&&destination.search==='')return;
   send({kind:'link_click',path,destination:destination.pathname});
  };
  document.addEventListener('click',handler,{capture:true});
  return()=>document.removeEventListener('click',handler,{capture:true});
 },[path]);
 return null;
}
