/**
 * AIEO thin Facebook Pixel (Track B / B2b).
 *
 * Vanilla JS, no jQuery, deferred/footer. Fires PageView site-wide and, on the
 * thank-you page, Purchase with the SHARED per-order event_id so Meta
 * de-duplicates the browser event against the server CAPI event.
 *
 * The access token NEVER reaches this file — only pixel_id, event_id and
 * purchase data are localized (window.aieoFbPixel / window.aieoFbPixelPurchase).
 */
(function () {
	var cfg = window.aieoFbPixel;
	if ( ! cfg || ! cfg.pixel_id ) {
		return;
	}
	// Live per-visitor marketing consent — NOT the cache-baked cfg.consent.
	// Anonymous / ad pages are full-page cached, so cfg.consent is frozen at
	// build time; read the first-party aieo_consent cookie ({marketing:truthy})
	// per request so an opt-out shopper never fires the pixel off a cached page.
	// No cookie yet (no choice) → fall back to the server-rendered default.
	function aieoFbConsentOk() {
		try {
			var m = document.cookie.match( /(?:^|;\s*)aieo_consent=([^;]*)/ );
			if ( m ) {
				var raw = JSON.parse( decodeURIComponent( m[1] ) );
				if ( raw && typeof raw === 'object' && 'marketing' in raw ) {
					return !! raw.marketing;
				}
			}
		} catch ( e ) {}
		return !! cfg.consent && '0' !== String( cfg.consent );
	}
	if ( ! aieoFbConsentOk() ) {
		return;
	}

	// Load the standard Meta Pixel bootstrap only if no other tool already did
	// (avoids a double fbevents.js during a PixelYourSite parallel-run).
	if ( typeof window.fbq !== 'function' ) {
		!function ( f, b, e, v, n, t, s ) {
			if ( f.fbq ) { return; }
			n = f.fbq = function () { n.callMethod ? n.callMethod.apply( n, arguments ) : n.queue.push( arguments ); };
			if ( ! f._fbq ) { f._fbq = n; }
			n.push = n; n.loaded = !0; n.version = '2.0'; n.queue = [];
			t = b.createElement( e ); t.async = !0; t.src = v;
			s = b.getElementsByTagName( e )[0]; s.parentNode.insertBefore( t, s );
		}( window, document, 'script', 'https://connect.facebook.net/en_US/fbevents.js' );
	}

	// Advanced Matching: pass the shopper's normalized identifiers to init so
	// Meta hashes them client-side (manual advanced matching). cfg.am is only
	// present with marketing consent and only carries the shopper's own data.
	try {
		if ( cfg.am && typeof cfg.am === 'object' ) {
			window.fbq( 'init', String( cfg.pixel_id ), cfg.am );
		} else {
			window.fbq( 'init', String( cfg.pixel_id ) );
		}
	} catch ( e ) {}
	try { window.fbq( 'track', 'PageView' ); } catch ( e ) {}

	// ViewContent — single product page.
	if ( cfg.view_content && cfg.view_content.content_ids ) {
		try {
			window.fbq( 'track', 'ViewContent', {
				content_ids:  cfg.view_content.content_ids,
				content_type: 'product',
				value:        cfg.view_content.value,
				currency:     cfg.currency
			} );
		} catch ( e ) {}
	}

	// InitiateCheckout — checkout page.
	if ( cfg.initiate_checkout && cfg.initiate_checkout.content_ids ) {
		try {
			window.fbq( 'track', 'InitiateCheckout', {
				content_ids:  cfg.initiate_checkout.content_ids,
				content_type: 'product',
				value:        cfg.initiate_checkout.value,
				currency:     cfg.currency,
				num_items:    cfg.initiate_checkout.num_items
			} );
		} catch ( e ) {}
	}

	// AddToCart — non-AJAX adds (single product page form submit) are stashed
	// server-side and flushed here WITH value/contents. AJAX adds fire live from
	// the jQuery listener below instead, so this never double-counts them.
	if ( cfg.add_to_cart && cfg.add_to_cart.content_ids && cfg.add_to_cart.content_ids.length ) {
		try {
			window.fbq( 'track', 'AddToCart', {
				content_ids:  cfg.add_to_cart.content_ids,
				contents:     cfg.add_to_cart.contents,
				content_type: 'product',
				value:        cfg.add_to_cart.value,
				currency:     cfg.currency,
				num_items:    cfg.add_to_cart.num_items
			} );
		} catch ( e ) {}
	}

	// Search — search results page.
	if ( cfg.search && cfg.search.search_string ) {
		try {
			window.fbq( 'track', 'Search', {
				search_string: cfg.search.search_string,
				content_type:  'product'
			} );
		} catch ( e ) {}
	}

	// AddToCart — WooCommerce's AJAX add-to-cart event (needs jQuery; degrades
	// gracefully when absent). Product id comes from the clicked button.
	if ( window.jQuery ) {
		try {
			window.jQuery( document.body ).on( 'added_to_cart', function ( ev, fragments, cart_hash, $button ) {
				try {
					var pid = ( $button && $button.data ) ? ( $button.data( 'product_id' ) || $button.attr( 'data-product_id' ) ) : 0;
					if ( pid ) {
						window.fbq( 'track', 'AddToCart', {
							content_ids:  [ String( pid ) ],
							content_type: 'product',
							currency:     cfg.currency
						} );
					}
				} catch ( e ) {}
			} );
		} catch ( e ) {}
	}

	// AddToWishlist — our wishlist broadcasts `aieo_wishlist_updated` [pid, isAdd,
	// itemType] from EVERY add surface (heart, Interactivity API, side-cart). Fire
	// only on a product ADD. Marketing consent was already verified above before
	// any of this code runs, so the listener itself is consent-safe.
	if ( window.jQuery ) {
		try {
			window.jQuery( window ).on( 'aieo_wishlist_updated', function ( ev, pid, isAdd, itemType ) {
				try {
					if ( isAdd && pid && ( ! itemType || 'product' === itemType ) ) {
						window.fbq( 'track', 'AddToWishlist', {
							content_ids:  [ String( pid ) ],
							content_type: 'product',
							currency:     cfg.currency
						} );
					}
				} catch ( e ) {}
			} );
		} catch ( e ) {}
	}

	var pur = window.aieoFbPixelPurchase;
	if ( pur && pur.event_id ) {
		try {
			window.fbq( 'track', 'Purchase', {
				value:        pur.value,
				currency:     pur.currency,
				contents:     pur.contents,
				content_ids:  pur.content_ids,
				content_type: 'product',
				num_items:    pur.num_items
			}, { eventID: pur.event_id } );
		} catch ( e ) {}
	}
})();
