type EventParams = Record<string, string | number | boolean | undefined>;

const GA_MEASUREMENT_ID = import.meta.env.VITE_GA_MEASUREMENT_ID as string | undefined;
const MIXPANEL_TOKEN = import.meta.env.VITE_MIXPANEL_TOKEN as string | undefined;
const META_PIXEL_ID = import.meta.env.VITE_META_PIXEL_ID as string | undefined;
const LINKEDIN_PARTNER_ID = import.meta.env.VITE_LINKEDIN_PARTNER_ID as string | undefined;

declare global {
  interface Window {
    gtag?: (command: string, target: string, params?: EventParams) => void;
    mixpanel?: { track: (event: string, params?: EventParams) => void; init?: (token: string) => void };
    dataLayer?: unknown[];
    fbq?: (...args: unknown[]) => void;
    _fbq?: unknown;
    lintrk?: (...args: unknown[]) => void;
  }
}

function initGA() {
  if (!GA_MEASUREMENT_ID || typeof window === 'undefined') return;
  if (window.gtag) return;

  const script = document.createElement('script');
  script.async = true;
  script.src = `https://www.googletagmanager.com/gtag/js?id=${GA_MEASUREMENT_ID}`;
  document.head.appendChild(script);

  window.dataLayer = window.dataLayer || [];
  window.gtag = function gtag() {
    window.dataLayer!.push(arguments);
  };
  window.gtag('js', new Date());
  window.gtag('config', GA_MEASUREMENT_ID);
}

function initMixpanel() {
  if (!MIXPANEL_TOKEN || typeof window === 'undefined') return;
  if (window.mixpanel) return;

  const script = document.createElement('script');
  script.async = true;
  script.src = 'https://cdn.mxpnl.com/libs/mixpanel-2-latest.min.js';
  document.head.appendChild(script);

  script.onload = () => {
    window.mixpanel = window.mixpanel || { track: () => {} };
    window.mixpanel.init?.(MIXPANEL_TOKEN);
  };
}

function initMetaPixel() {
  if (!META_PIXEL_ID || typeof window === 'undefined') return;
  if (window.fbq) return;

  window.fbq = function fbq() { window._fbq = window._fbq || []; window._fbq.push(arguments); };
  const script = document.createElement('script');
  script.async = true;
  script.src = `https://connect.facebook.net/en_US/fbevents.js`;
  document.head.appendChild(script);

  window.fbq('init', META_PIXEL_ID);
  window.fbq('track', 'PageView');
}

function initLinkedInInsight() {
  if (!LINKEDIN_PARTNER_ID || typeof window === 'undefined') return;
  if (window.lintrk) return;

  window.lintrk = function lintrk() { window.lintrk.q.push(arguments); };
  window.lintrk.q = [];
  const script = document.createElement('script');
  script.async = true;
  script.src = `https://snap.licdn.com/li.lms-analytics/insight.min.js`;
  document.head.appendChild(script);
}

export function initAnalytics() {
  initGA();
  initMixpanel();
  initMetaPixel();
  initLinkedInInsight();
}

export function trackMetaEvent(eventName: string, params?: EventParams) {
  if (typeof window === 'undefined' || !window.fbq) return;
  window.fbq('track', eventName, params);
}

export function trackLinkedInEvent() {
  if (typeof window === 'undefined' || !window.lintrk) return;
  window.lintrk('track', { conversion_id: null });
}

export function trackEvent(name: string, params?: EventParams) {
  if (typeof window === 'undefined') return;

  if (window.gtag) {
    window.gtag('event', name, params);
  }

  if (window.mixpanel) {
    window.mixpanel.track(name, params);
  }
}

function hashEmail(email: string): string {
  let hash = 0;
  for (let i = 0; i < email.length; i++) {
    const char = email.charCodeAt(i);
    hash = ((hash << 5) - hash) + char;
    hash = hash & hash;
  }
  return Math.abs(hash).toString(16);
}

export function trackWaitlistSignup(email: string, source?: string, tier?: string) {
  trackEvent('waitlist_signup', {
    email,
    source: source || 'landing_page',
    tier: tier || 'unknown',
  });
  trackMetaEvent('Lead', { value: 5.00, currency: 'USD', eventID: hashEmail(email) });
}

export function trackPageView(path: string, title?: string) {
  trackEvent('page_view', {
    page_path: path,
    page_title: title || document.title,
  });
}
