// GA4 Ecommerce DataLayer helpers

declare global {
  interface Window {
    dataLayer: Record<string, any>[];
  }
}

function push(data: Record<string, any>) {
  window.dataLayer = window.dataLayer || [];
  window.dataLayer.push({ ecommerce: null });
  window.dataLayer.push(data);
}

export interface AnalyticsItem {
  item_id: string;
  item_name: string;
  item_brand: string;
  price: number;
  index?: number;
  item_list_id?: string;
  item_list_name?: string;
  item_category?: string;
}

export function pushViewItemList(listId: string, listName: string, items: AnalyticsItem[]) {
  push({
    event: 'view_item_list',
    ecommerce: {
      item_list_id: listId,
      item_list_name: listName,
      items: items.map((item, i) => ({
        ...item,
        index: item.index ?? i,
        item_list_id: listId,
        item_list_name: listName,
      })),
    },
  });
}

export function pushSelectItem(item: AnalyticsItem) {
  push({
    event: 'select_item',
    ecommerce: {
      items: [item],
    },
  });
}

export function pushViewItem(item: AnalyticsItem) {
  push({
    event: 'view_item',
    ecommerce: {
      items: [item],
    },
  });
}

export function pushSelectPromotion(shopName: string, item: AnalyticsItem, destinationUrl: string) {
  push({
    event: 'select_promotion',
    ecommerce: {
      promotion_id: shopName,
      promotion_name: shopName,
      items: [item],
    },
  });
  // Also fire outbound_click
  window.dataLayer = window.dataLayer || [];
  window.dataLayer.push({
    event: 'outbound_click',
    destination_url: destinationUrl,
    shop_name: shopName,
  });
}

export function pushSearch(searchTerm: string) {
  window.dataLayer = window.dataLayer || [];
  window.dataLayer.push({
    event: 'search',
    search_term: searchTerm,
  });
}

export function pushViewSearchResults(searchTerm: string, resultsCount: number) {
  window.dataLayer = window.dataLayer || [];
  window.dataLayer.push({
    event: 'view_search_results',
    search_term: searchTerm,
    results_count: resultsCount,
  });
}
