/**
 * AIEO thin TikTok Pixel (Track B).
 *
 * Vanilla JS, no jQuery, deferred/footer. Fires PageView site-wide and, on the
 * thank-you page, CompletePayment with the SHARED per-order event_id so TikTok
 * de-duplicates the browser event against the server Events API event.
 *
 * The access token NEVER reaches this file — only pixel_id, event_id and
 * purchase data are localized (window.aieoTtPixel / window.aieoTtPixelPurchase).
 */
(function () {
	var cfg = window.aieoTtPixel;
	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 aieoTtConsentOk() {
		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 ( ! aieoTtConsentOk() ) {
		return;
	}

	// Load the standard TikTok Pixel bootstrap only if no other tool already did
	// (avoids a double events.js during a parallel run with another pixel tool).
	if ( typeof window.ttq === 'undefined' || ! window.ttq.load ) {
		!function ( w, d, t ) {
			w.TiktokAnalyticsObject = t;
			var ttq = w[ t ] = w[ t ] || [];
			ttq.methods = [ 'page', 'track', 'identify', 'instances', 'debug', 'on', 'off', 'once', 'ready', 'alias', 'group', 'enableCookie', 'disableCookie', 'holdConsent', 'revokeConsent', 'grantConsent' ];
			ttq.setAndDefer = function ( a, e ) { a[ e ] = function () { a.push( [ e ].concat( Array.prototype.slice.call( arguments, 0 ) ) ); }; };
			for ( var i = 0; i < ttq.methods.length; i++ ) { ttq.setAndDefer( ttq, ttq.methods[ i ] ); }
			ttq.instance = function ( e ) { for ( var n = ttq._i[ e ] || [], r = 0; r < ttq.methods.length; r++ ) { ttq.setAndDefer( n, ttq.methods[ r ] ); } return n; };
			ttq.load = function ( e, n ) {
				var r = 'https://analytics.tiktok.com/i18n/pixel/events.js';
				ttq._i = ttq._i || {}; ttq._i[ e ] = []; ttq._i[ e ]._u = r;
				ttq._t = ttq._t || {}; ttq._t[ e ] = +new Date();
				ttq._o = ttq._o || {}; ttq._o[ e ] = n || {};
				var o = d.createElement( 'script' ); o.type = 'text/javascript'; o.async = !0; o.src = r + '?sdkid=' + e + '&lib=' + t;
				var s = d.getElementsByTagName( 'script' )[ 0 ]; s.parentNode.insertBefore( o, s );
			};
		}( window, document, 'ttq' );
	}

	try { window.ttq.load( String( cfg.pixel_id ) ); } catch ( e ) {}
	try { window.ttq.page(); } catch ( e ) {}

	// ViewContent — single product page.
	if ( cfg.view_content && cfg.view_content.content_id ) {
		try {
			window.ttq.track( 'ViewContent', {
				contents: [ { content_id: cfg.view_content.content_id, content_type: 'product' } ],
				value:    cfg.view_content.value,
				currency: cfg.currency
			} );
		} catch ( e ) {}
	}

	// AddToCart — WooCommerce's AJAX add-to-cart (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.ttq.track( 'AddToCart', {
							contents: [ { content_id: String( pid ), content_type: 'product' } ],
							currency: cfg.currency
						} );
					}
				} catch ( e ) {}
			} );
		} catch ( e ) {}
	}

	var pur = window.aieoTtPixelPurchase;
	if ( pur && pur.event_id ) {
		try {
			window.ttq.track( 'Purchase', {
				contents:     pur.contents,
				content_type: 'product',
				value:        pur.value,
				currency:     pur.currency
			}, { event_id: pur.event_id } );
		} catch ( e ) {}
	}
})();
