// LinkedIn Insight Tag helpers. Page-level privacy gating (the HIPAA allowlist)
// lives in ./marketing-pages and is shared with GA4.

// Partner ID is injected into an inline script, so keep it strictly numeric to
// avoid any script injection via a misconfigured env var. Empty => tag disabled.
export const LINKEDIN_PARTNER_ID = (
  process.env.NEXT_PUBLIC_LINKEDIN_PARTNER_ID || ''
).replace(/[^0-9]/g, '');

export const LINKEDIN_CONVERSION_ID = (
  process.env.NEXT_PUBLIC_LINKEDIN_CONVERSION_ID || ''
).replace(/[^0-9]/g, '');

export const LINKEDIN_INSIGHT_SRC =
  'https://snap.licdn.com/li.lms-analytics/insight.min.js';

/**
 * Fire a LinkedIn conversion event (e.g. on successful signup). No-op unless a
 * conversion ID is configured and the Insight Tag has loaded (`lintrk` present),
 * which only happens on allowed pages with marketing consent — so this is
 * automatically consent- and privacy-safe.
 */
export function trackLinkedInConversion(): void {
  if (typeof window === 'undefined' || !LINKEDIN_CONVERSION_ID) return;
  const w = window as unknown as {
    lintrk?: (action: string, data: { conversion_id: number }) => void;
  };
  if (typeof w.lintrk === 'function') {
    w.lintrk('track', { conversion_id: Number(LINKEDIN_CONVERSION_ID) });
  }
}
