
// ─── GTM / DataLayer Utility ─────────────────────────────────────────────────
// Single source of truth for all GTM tracking.
// tagmanager.ts re-exports from this file for backward compatibility.
// ─────────────────────────────────────────────────────────────────────────────

const GTM_SCRIPT_ID = '__gtm_main_script__';
const GTM_NOSCRIPT_ID = '__gtm_noscript__';

/**
 * Remove any previously injected GTM script / noscript from the DOM
 * and reset state so initGTM can re-run with a fresh ID.
 */
export const removeGTM = () => {
  const oldScript = document.getElementById(GTM_SCRIPT_ID);
  if (oldScript) oldScript.parentNode?.removeChild(oldScript);

  const oldInner = document.getElementById(`${GTM_SCRIPT_ID}_inner`);
  if (oldInner) oldInner.parentNode?.removeChild(oldInner);

  const oldNoscript = document.getElementById(GTM_NOSCRIPT_ID);
  if (oldNoscript) oldNoscript.parentNode?.removeChild(oldNoscript);

  (window as any).dataLayer = [];
  delete (window as any)._gtm_initialized;
  delete (window as any)._gtm_current_id;

  console.log('[GTM] Previous instance removed.');
};

/**
 * Initialize (or re-initialize) GTM with a given ID.
 * - Same ID → skips (no-op)
 * - Different ID → removes old, injects new
 */
export const initGTM = (gtmId: string) => {
  if (typeof window === 'undefined' || !gtmId) return;

  const cleanId = gtmId.replace(/\s+/g, '').toUpperCase();
  if (!cleanId.startsWith('GTM-')) {
    console.warn(`[GTM] Invalid ID: "${cleanId}" — must start with GTM-`);
    return;
  }

  if ((window as any)._gtm_current_id === cleanId) {
    console.log(`[GTM] Already active: ${cleanId} — skipping.`);
    return;
  }

  if ((window as any)._gtm_initialized) {
    removeGTM();
  }

  // ── <script> in <head> ──────────────────────────────────────────
  const script = document.createElement('script');
  script.id = GTM_SCRIPT_ID;
  script.async = true;
  script.innerHTML = `
    (function(w,d,s,l,i){
      w[l]=w[l]||[];
      w[l].push({'gtm.start':new Date().getTime(),event:'gtm.js'});
      var f=d.getElementsByTagName(s)[0],
          j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';
      j.async=true;
      j.src='https://www.googletagmanager.com/gtm.js?id='+i+dl;
      j.id='${GTM_SCRIPT_ID}_inner';
      f.parentNode.insertBefore(j,f);
    })(window,document,'script','dataLayer','${cleanId}');
  `;
  document.head.insertBefore(script, document.head.firstChild);

  // ── <noscript> in <body> ────────────────────────────────────────
  const noscript = document.createElement('noscript');
  noscript.id = GTM_NOSCRIPT_ID;
  noscript.innerHTML = `<iframe src="https://www.googletagmanager.com/ns.html?id=${cleanId}"
    height="0" width="0" style="display:none;visibility:hidden"></iframe>`;
  if (document.body) {
    document.body.insertBefore(noscript, document.body.firstChild);
  }

  (window as any)._gtm_initialized = true;
  (window as any)._gtm_current_id = cleanId;
  console.log(`[GTM] ✅ Initialized: ${cleanId}`);
};

// ─────────────────────────────────────────────────────────────────────────────
// Backend tracking — saves each event to PHP API / MySQL
// ─────────────────────────────────────────────────────────────────────────────

const ANALYTICS_API = '/api/analytics';

/** Events we want to persist to the backend DB */
const BACKEND_TRACKED_EVENTS = new Set([
  'page_view',
  'view_item',
  'ViewContent',
  'add_to_cart',
  'AddToCart',
  'begin_checkout',
  'InitiateCheckout',
  'purchase',
  'Purchase',
  'search',
]);

/**
 * Fire-and-forget POST to backend analytics API.
 * Never throws — silently fails if server is unavailable.
 */
const trackBackend = (event: string, data: Record<string, any> = {}) => {
  if (!BACKEND_TRACKED_EVENTS.has(event)) return;
  if (typeof window === 'undefined') return;

  // Get or create session ID
  let sessionId = sessionStorage.getItem('shf_session_id');
  if (!sessionId) {
    sessionId = `S-${Date.now()}-${Math.random().toString(36).substr(2, 7)}`;
    sessionStorage.setItem('shf_session_id', sessionId);
  }

  const payload: Record<string, any> = {
    event_type: event,
    session_id: sessionId,
  };

  // Extract item details from ecommerce.items[0] or top-level
  const items = data?.ecommerce?.items || data?.items;
  if (items && items.length > 0) {
    payload.item_id   = items[0].item_id   || items[0].productId || '';
    payload.item_name = items[0].item_name || items[0].name      || '';
  } else {
    payload.item_id   = data.item_id   || data.content_ids?.[0] || '';
    payload.item_name = data.item_name || data.content_name      || '';
  }

  payload.value = data?.ecommerce?.value ?? data?.value ?? 0;
  payload.extra = { ...data };

  fetch(ANALYTICS_API, {
    method: 'POST',
    headers: { 'Content-Type': 'text/plain', Accept: 'application/json' },
    body: JSON.stringify(payload),
    keepalive: true,  // ensures it fires even if page navigates away
  }).catch(() => { /* silent fail */ });
};

// ─────────────────────────────────────────────────────────────────────────────
// Core push function
// ─────────────────────────────────────────────────────────────────────────────

/**
 * Push any event + data to GTM dataLayer.
 * Safe to call before GTM loads (events queue until GTM is ready).
 */
export const pushToDataLayer = (event: string, data: Record<string, any> = {}) => {
  if (typeof window === 'undefined') return;
  (window as any).dataLayer = (window as any).dataLayer || [];

  // GA4 standard: reset ecommerce before each event
  if (data.ecommerce) {
    (window as any).dataLayer.push({ ecommerce: null });
  }

  (window as any).dataLayer.push({
    event,
    timestamp: new Date().toISOString(),
    ...data,
  });

  console.debug(`[GTM DataLayer] 📤 ${event}`, data);
};

// ─────────────────────────────────────────────────────────────────────────────
// Typed event helpers — use these across the app
// ─────────────────────────────────────────────────────────────────────────────

export interface GTMProduct {
  item_id: string;
  item_name: string;
  item_name_bn?: string;
  item_category?: string;
  item_variant?: string;    // selected size
  price: number;
  quantity?: number;
  currency?: string;
}

export const gtmEvents = {

  /** 🏠 Page / screen view */
  pageView: (view: string, path: string, gtmId?: string) => {
    pushToDataLayer('page_view', {
      page_path: path,
      page_view: view,
      gtm_id: gtmId || '',
    });
  },

  /** 👁 User views a product detail — fires on ProductDetailPage / LandingPages */
  viewItem: (product: GTMProduct) => {
    pushToDataLayer('view_item', {
      ecommerce: {
        currency: 'BDT',
        value: product.price,
        items: [{
          item_id: product.item_id,
          item_name: product.item_name,
          item_name_bn: product.item_name_bn || '',
          item_category: product.item_category || '',
          item_variant: product.item_variant || '',
          price: product.price,
          quantity: 1,
        }],
      },
    });
  },

  /** 👁 Facebook pixel style — ViewContent */
  viewContent: (product: GTMProduct) => {
    pushToDataLayer('ViewContent', {
      content_ids: [product.item_id],
      content_name: product.item_name,
      content_type: 'product',
      value: product.price,
      currency: 'BDT',
    });
  },

  /** 📋 User views a list of products (shop / trending / category) */
  viewItemList: (listName: string, products: GTMProduct[]) => {
    pushToDataLayer('view_item_list', {
      ecommerce: {
        item_list_name: listName,
        items: products.map((p, idx) => ({
          item_id: p.item_id,
          item_name: p.item_name,
          item_category: p.item_category || '',
          price: p.price,
          index: idx,
        })),
      },
    });
  },

  /** 🛒 User adds a product to cart */
  addToCart: (product: GTMProduct) => {
    pushToDataLayer('add_to_cart', {
      ecommerce: {
        currency: 'BDT',
        value: product.price * (product.quantity || 1),
        items: [{
          item_id: product.item_id,
          item_name: product.item_name,
          item_name_bn: product.item_name_bn || '',
          item_category: product.item_category || '',
          item_variant: product.item_variant || '',
          price: product.price,
          quantity: product.quantity || 1,
        }],
      },
    });
    // Also fire Facebook Pixel style
    pushToDataLayer('AddToCart', {
      content_ids: [product.item_id],
      content_name: product.item_name,
      value: product.price,
      currency: 'BDT',
    });
  },

  /** 💳 Checkout popup/form opens — initial checkout intent */
  beginCheckout: (items: GTMProduct[], total: number) => {
    pushToDataLayer('begin_checkout', {
      ecommerce: {
        currency: 'BDT',
        value: total,
        checkout_step: 1,
        checkout_option: 'Cash on Delivery',
        items: items.map(p => ({
          item_id: p.item_id,
          item_name: p.item_name,
          item_name_bn: p.item_name_bn || '',
          item_category: p.item_category || '',
          item_variant: p.item_variant || '',
          price: p.price,
          quantity: p.quantity || 1,
        })),
      },
    });
    // Facebook pixel style
    pushToDataLayer('InitiateCheckout', {
      content_ids: items.map(p => p.item_id),
      value: total,
      currency: 'BDT',
      num_items: items.length,
    });
  },

  /** ✅ Order successfully placed */
  purchase: (params: {
    orderId: string;
    items: GTMProduct[];
    subtotal: number;
    deliveryCharge: number;
    total: number;
    customerPhone?: string;
    source?: string;
  }) => {
    pushToDataLayer('purchase', {
      ecommerce: {
        transaction_id: params.orderId,
        currency: 'BDT',
        value: params.total,
        tax: 0,
        shipping: params.deliveryCharge,
        items: params.items.map(p => ({
          item_id: p.item_id,
          item_name: p.item_name,
          item_name_bn: p.item_name_bn || '',
          item_category: p.item_category || '',
          item_variant: p.item_variant || '',
          price: p.price,
          quantity: p.quantity || 1,
        })),
      },
      order_id: params.orderId,
      source: params.source || 'unknown',
    });
    // Facebook pixel style Purchase
    pushToDataLayer('Purchase', {
      content_ids: params.items.map(p => p.item_id),
      value: params.total,
      currency: 'BDT',
      num_items: params.items.length,
    });
    console.log(`[GTM] ✅ purchase fired — ${params.orderId} | ৳${params.total}`);
  },

  /** 🔍 User searches */
  search: (query: string) => {
    pushToDataLayer('search', { search_term: query });
  },

  /** 📞 User clicks phone / WhatsApp CTA */
  ctaClick: (cta: string, location: string) => {
    pushToDataLayer('cta_click', { cta_name: cta, cta_location: location });
  },
};
