
export const initPixel = (pixelId: string) => {
  if (typeof window === 'undefined' || !pixelId || (window as any)._fb_initialized) return;
  
  const f = window as any;
  if (!f.fbq) {
    const n = (f.fbq = function() {
      n.callMethod ? n.callMethod.apply(n, arguments) : n.queue.push(arguments);
    }) as any;
    if (!f._fbq) f._fbq = n;
    n.push = n;
    n.loaded = !0;
    n.version = '2.0';
    n.queue = [];
    const t = document.createElement('script');
    t.async = !0;
    t.src = 'https://connect.facebook.net/en_US/fbevents.js';
    const s = document.getElementsByTagName('script')[0];
    s.parentNode?.insertBefore(t, s);
  }
  
  f.fbq('init', pixelId);
  f.fbq('track', 'PageView');
  f._fb_initialized = true;
  console.log(`[Meta Pixel] Initialized: ${pixelId}`);
};

export const trackPixelEvent = (event: string, data?: any) => {
  const f = window as any;
  if (f.fbq) {
    f.fbq('track', event, data);
    console.debug(`[Meta Pixel Event]: ${event}`, data);
  }
};
