// Public tag identifiers from the existing Google Ads conversion action.
export const ADS_TAG_ID = process.env.NEXT_PUBLIC_GOOGLE_ADS_ID || 'AW-17794642163';
export const ADS_CART_DESTINATION = process.env.NEXT_PUBLIC_GOOGLE_ADS_CART_DESTINATION
  || 'AW-17794642163/aX3DCPu9q88bEPPhkqVC';

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

export function hasAnalyticsConsent(): boolean {
  if (typeof window === 'undefined') return false;
  try {
    return window.localStorage.getItem('cookieConsent') === 'accepted';
  } catch {
    return false;
  }
}

export function trackAddToCart(item: {
  variantId: number; productName: string; brandName: string; volume: string; price: number;
}): void {
  if (!hasAnalyticsConsent() || !window.gtag || !Number.isFinite(item.price) || item.price <= 0) return;
  window.gtag('event', 'add_to_cart', {
    currency: 'CZK',
    value: item.price,
    items: [{
      item_id: `variant-${item.variantId}`,
      item_name: item.productName,
      item_brand: item.brandName,
      item_variant: item.volume,
      price: item.price,
      quantity: 1,
    }],
  });
  window.gtag('event', 'conversion', {
    send_to: ADS_CART_DESTINATION,
    currency: 'CZK',
    value: item.price,
  });
}
