export interface WebVitalsClientOptions {
  endpoint?: string;
  sampleRate?: number;
}

export function webVitalsClient(options: WebVitalsClientOptions = {}): string {
  const endpoint = JSON.stringify(options.endpoint ?? "/__wrnexus/metrics/vitals");
  const sampleRate = Math.max(0, Math.min(1, options.sampleRate ?? 0.1));
  return `(function(){
  if (!window.PerformanceObserver || Math.random() > ${sampleRate}) return;
  var endpoint = ${endpoint};
  var cls = 0;
  var lcp = 0;
  var inp = 0;
  var flushed = false;
  function rating(name, value) {
    if (name === "LCP") return value <= 2500 ? "good" : value <= 4000 ? "needs-improvement" : "poor";
    if (name === "INP") return value <= 200 ? "good" : value <= 500 ? "needs-improvement" : "poor";
    if (name === "CLS") return value <= 0.1 ? "good" : value <= 0.25 ? "needs-improvement" : "poor";
    return "unknown";
  }
  function send(name, value) {
    var body = JSON.stringify({ name: name, value: value, rating: rating(name, value), route: location.pathname, navigationType: performance.getEntriesByType("navigation")[0]?.type });
    if (navigator.sendBeacon) navigator.sendBeacon(endpoint, new Blob([body], { type: "application/json" }));
    else fetch(endpoint, { method: "POST", headers: { "content-type": "application/json" }, body: body, keepalive: true }).catch(function(error){ console.warn("[wrnexus:observability] web-vitals delivery failed", error); });
  }
  function flush() {
    if (flushed) return;
    flushed = true;
    if (lcp) send("LCP", lcp);
    if (inp) send("INP", inp);
    if (cls) send("CLS", cls);
  }
  function observe(type, callback, options) {
    try { new PerformanceObserver(callback).observe(options); }
    catch(error) { console.warn("[wrnexus:observability] PerformanceObserver unavailable for " + type, error); }
  }
  observe("largest-contentful-paint", function(list){ var entries=list.getEntries(); var last=entries[entries.length-1]; if(last) lcp = Math.max(lcp, last.startTime); }, {type:"largest-contentful-paint",buffered:true});
  observe("layout-shift", function(list){ list.getEntries().forEach(function(e){ if(!e.hadRecentInput) cls += e.value; }); }, {type:"layout-shift",buffered:true});
  observe("event", function(list){ list.getEntries().forEach(function(e){ inp=Math.max(inp,e.duration||0); }); }, {type:"event",durationThreshold:40,buffered:true});
  addEventListener("visibilitychange", function(){ if(document.visibilityState === "hidden") flush(); });
  addEventListener("pagehide", flush, { once: true });
})();`;
}
