// Campaign (UTM) attribution helpers. UTM params arrive on the first landing
// URL (e.g. /?utm_source=linkedin) but are lost once the visitor navigates
// internally to /signup, so we persist them for the session. Capture is
// consent-gated by the caller (AnalyticsGate), matching the analytics policy.

const STORAGE_KEY = 'mbhs_utm';

export const UTM_KEYS = [
  'utm_source',
  'utm_medium',
  'utm_campaign',
  'utm_term',
  'utm_content',
] as const;

export type UtmParams = Partial<Record<(typeof UTM_KEYS)[number], string>>;

/**
 * Persist any UTM params present in the current URL to sessionStorage.
 * First-touch: if UTMs are already stored this session, they are NOT
 * overwritten, so the original campaign that referred the visitor wins.
 */
export function captureUtmParams(): void {
  if (typeof window === 'undefined') return;
  try {
    if (window.sessionStorage.getItem(STORAGE_KEY)) return; // first-touch wins
    const search = new URLSearchParams(window.location.search);
    const captured: UtmParams = {};
    for (const key of UTM_KEYS) {
      const value = search.get(key);
      if (value) captured[key] = value;
    }
    if (Object.keys(captured).length > 0) {
      window.sessionStorage.setItem(STORAGE_KEY, JSON.stringify(captured));
    }
  } catch {
    // sessionStorage can throw in private mode / when disabled — attribution
    // is best-effort, so fail silently rather than break the page.
  }
}

/** Read the UTM params captured this session (empty object if none). */
export function getUtmParams(): UtmParams {
  if (typeof window === 'undefined') return {};
  try {
    const raw = window.sessionStorage.getItem(STORAGE_KEY);
    return raw ? (JSON.parse(raw) as UtmParams) : {};
  } catch {
    return {};
  }
}
