/**
 * Ad attribution for the public site (client only). The UTM parameters and
 * Facebook click id from the landing URL are kept for the session so a
 * visitor who browses for a while and then leaves their number is still
 * credited to the campaign that brought them.
 */
export interface Attribution {
  utmSource?: string;
  utmMedium?: string;
  utmCampaign?: string;
  utmContent?: string;
  fbclid?: string;
  referrer?: string;
  page?: string;
}
const KEY = "lj_attr";

export function captureAttribution() {
  if (typeof window === "undefined") return;
  try {
    const p = new URLSearchParams(window.location.search);
    const fresh: Attribution = { utmSource: p.get("utm_source") ?? undefined, utmMedium: p.get("utm_medium") ?? undefined, utmCampaign: p.get("utm_campaign") ?? undefined, utmContent: p.get("utm_content") ?? undefined, fbclid: p.get("fbclid") ?? undefined };
    const has = Object.values(fresh).some(Boolean);
    const prev = getAttribution();
    const next: Attribution = { ...prev, ...(has ? fresh : {}), referrer: prev.referrer ?? (document.referrer && !document.referrer.startsWith(window.location.origin) ? document.referrer.slice(0, 120) : undefined), page: window.location.pathname + (has ? "" : window.location.search.slice(0, 80)) };
    sessionStorage.setItem(KEY, JSON.stringify(next));
  } catch {}
}

export function getAttribution(): Attribution {
  if (typeof window === "undefined") return {};
  try {
    return JSON.parse(sessionStorage.getItem(KEY) ?? "{}") as Attribution;
  } catch {
    return {};
  }
}
