/**
 * Google Analytics 4 Events Tracking
 * ID: G-LYGFMS3PJS
 */

declare global {
  interface Window {
    gtag?: (...args: any[]) => void;
  }
}

export const trackEvent = (eventName: string, eventData?: Record<string, any>) => {
  if (typeof window !== "undefined" && window.gtag) {
    window.gtag("event", eventName, eventData);
  }
};

export const trackViewItem = (product: {
  id: string;
  title: string;
  price: number;
  category?: string;
  image?: string;
}) => {
  trackEvent("view_item", {
    items: [
      {
        item_id: product.id,
        item_name: product.title,
        price: product.price,
        item_category: product.category,
        item_image: product.image,
      },
    ],
  });
};

export const trackAddToCart = (product: {
  id: string;
  title: string;
  price: number;
  quantity: number;
  category?: string;
}) => {
  trackEvent("add_to_cart", {
    items: [
      {
        item_id: product.id,
        item_name: product.title,
        price: product.price,
        quantity: product.quantity,
        item_category: product.category,
      },
    ],
  });
};

export const trackBeginCheckout = (items: Array<{
  item_id: string;
  item_name: string;
  price: number;
  quantity: number;
  item_category?: string;
}>) => {
  trackEvent("begin_checkout", {
    items,
  });
};

export const trackRemoveFromCart = (product: {
  id: string;
  title: string;
  price: number;
  quantity: number;
  category?: string;
}) => {
  trackEvent("remove_from_cart", {
    items: [
      {
        item_id: product.id,
        item_name: product.title,
        price: product.price,
        quantity: product.quantity,
        item_category: product.category,
      },
    ],
  });
};

export const trackPurchase = (order: {
  transaction_id: string;
  value: number;
  currency: string;
  tax?: number;
  shipping?: number;
  coupon?: string;
  items: Array<{
    item_id: string;
    item_name: string;
    price: number;
    quantity: number;
    item_category?: string;
  }>;
}) => {
  trackEvent("purchase", {
    transaction_id: order.transaction_id,
    value: order.value,
    currency: order.currency,
    tax: order.tax,
    shipping: order.shipping,
    coupon: order.coupon,
    items: order.items,
  });
};

export const trackViewCart = (items: Array<{
  item_id: string;
  item_name: string;
  price: number;
  quantity: number;
  item_category?: string;
}>) => {
  trackEvent("view_cart", {
    items,
  });
};

export const trackSearch = (searchTerm: string, itemCount?: number) => {
  trackEvent("search", {
    search_term: searchTerm,
    number_of_items: itemCount,
  });
};

export const trackPageView = (pagePath: string, pageTitle?: string) => {
  trackEvent("page_view", {
    page_path: pagePath,
    page_title: pageTitle,
  });
};
