declare global {
  interface Window {
    dataLayer: any[];
    fbq: any;
    gtag: any;
  }
}

export const trackEvent = (eventName: string, eventData: Record<string, any>) => {
  if (typeof window === 'undefined') return;

  // 1. GTM dataLayer
  window.dataLayer = window.dataLayer || [];
  window.dataLayer.push({
    event: eventName,
    ...eventData,
  });

  // 2. Facebook Pixel (Meta Pixel)
  if (typeof window.fbq === 'function') {
    let fbEvent = eventName;
    if (eventName === 'view_item') fbEvent = 'ViewContent';
    else if (eventName === 'add_to_cart') fbEvent = 'AddToCart';
    else if (eventName === 'begin_checkout') fbEvent = 'InitiateCheckout';
    else if (eventName === 'purchase') fbEvent = 'Purchase';

    // Map GA4 payload to Facebook payload
    const fbData: Record<string, any> = {};
    
    if (eventData.value !== undefined) {
      fbData.value = eventData.value;
      fbData.currency = eventData.currency || 'BDT';
    }

    if (eventData.items && Array.isArray(eventData.items)) {
      fbData.content_type = 'product';
      fbData.content_ids = eventData.items.map((i: any) => String(i.item_id));
      fbData.contents = eventData.items.map((i: any) => ({
        id: String(i.item_id),
        quantity: i.quantity || 1,
        price: i.price,
        item_name: i.item_name
      }));
    }

    const { custom_fb_data, ...restData } = eventData;
    window.fbq('track', fbEvent, { ...fbData, ...restData, ...custom_fb_data });
  }

  // 3. Google Analytics (gtag.js)
  if (typeof window.gtag === 'function') {
    window.gtag('event', eventName, eventData);
  }
};

// Specific helper: View Product
export const trackViewItem = (product: any) => {
  if (!product) return;
  trackEvent('view_item', {
    currency: 'BDT',
    value: Number(product.price || product.sale_price),
    items: [
      {
        item_id: String(product.id),
        item_name: product.name,
        price: Number(product.price || product.sale_price),
        item_category: product.category?.name || '',
      },
    ],
  });
};

// Specific helper: Add to Cart
export const trackAddToCart = (product: any, quantity: number = 1) => {
  if (!product) return;
  trackEvent('add_to_cart', {
    currency: 'BDT',
    value: Number(product.price || product.sale_price) * quantity,
    items: [
      {
        item_id: String(product.id),
        item_name: product.name,
        price: Number(product.price || product.sale_price),
        quantity: quantity,
        item_category: product.category?.name || '',
      },
    ],
  });
};

// Specific helper: Begin Checkout
export const trackBeginCheckout = (cartItems: any[], subtotal: number) => {
  trackEvent('begin_checkout', {
    currency: 'BDT',
    value: subtotal,
    items: cartItems.map((item) => ({
      item_id: String(item.product_id),
      item_name: item.name,
      price: Number(item.price),
      quantity: item.quantity,
    })),
  });
};

// Specific helper: Purchase
export const trackPurchase = (order: any, customerInfo?: any) => {
  if (!order) return;
  
  const items = Array.isArray(order.items)
    ? order.items.map((item: any) => ({
        item_id: String(item.product_id),
        item_name: item.name || item.product_name || 'Product',
        price: Number(item.price),
        quantity: item.quantity,
      }))
    : [];

  trackEvent('purchase', {
    transaction_id: String(order.id || order.order_number),
    value: Number(order.total || order.grand_total),
    currency: 'BDT',
    shipping: Number(order.shipping_fee || 0),
    items: items,
    // Add user parameters for Advanced Matching in Meta Pixel
    custom_fb_data: customerInfo ? {
      em: customerInfo.email,
      ph: customerInfo.phone,
      fn: customerInfo.name,
    } : undefined
  });
};
