window.WPRecipeMaker = typeof window.WPRecipeMaker === "undefined" ? {} : window.WPRecipeMaker;

window.WPRecipeMaker.analytics = {
	init: () => {
		if ( wprm_public.settings.analytics_enabled || wprm_public.settings.google_analytics_enabled ) {
			document.addEventListener( 'click', function(e) {
				const target = e.target.closest ? e.target.closest( '.wprm-recipe-jump, .wprm-recipe-jump-video, .wprm-recipe-pin, .wprm-recipe-facebook-share, .wprm-recipe-messenger-share, .wprm-recipe-twitter-share, .wprm-recipe-bluesky-share, .wprm-recipe-mastodon-share, .wprm-recipe-tumblr-share, .wprm-recipe-text-share, .wprm-recipe-whatsapp-share, .wprm-recipe-email-share, .wprm-recipe-favorite, .wprm-recipe-add-to-collection-recipe, .wprm-recipe-add-to-shopping-list, .wprm-recipe-cook-mode, .wprm-recipe-equipment a, .wprm-recipe-ingredient a, .wprm-recipe-instruction a' ) : false;
				if ( target ) {
					window.WPRecipeMaker.analytics.checkClick( target, e );
				}
			}, false );
		}
	},
	checkClick: ( target, e ) => {
		if ( target.matches( '.wprm-recipe-jump' ) ) {
			const recipeId = target.dataset.hasOwnProperty( 'recipe' ) ? target.dataset.recipe : false;

			if ( recipeId ) {
				window.WPRecipeMaker.analytics.registerAction( recipeId, wprm_public.post_id, 'jump-to-recipe' );
			}
			return true;
		} else if ( target.matches( '.wprm-recipe-jump-video' ) ) {
			const recipeId = target.dataset.hasOwnProperty( 'recipe' ) ? target.dataset.recipe : false;

			if ( recipeId ) {
				window.WPRecipeMaker.analytics.registerAction( recipeId, wprm_public.post_id, 'jump-to-video' );
			}
			return true;
		} else if ( target.matches( '.wprm-recipe-pin' ) ) {
			const recipeId = target.dataset.hasOwnProperty( 'recipe' ) ? target.dataset.recipe : false;

			if ( recipeId ) {
				window.WPRecipeMaker.analytics.registerAction( recipeId, wprm_public.post_id, 'pin-button' );
			}
			return true;
		} else if ( target.matches( '.wprm-recipe-facebook-share' ) ) {
			const recipeId = target.dataset.hasOwnProperty( 'recipe' ) ? target.dataset.recipe : false;

			if ( recipeId ) {
				window.WPRecipeMaker.analytics.registerAction( recipeId, wprm_public.post_id, 'facebook-share-button' );
			}
			return true;
		} else if ( target.matches( '.wprm-recipe-messenger-share' ) ) {
			const recipeId = target.dataset.hasOwnProperty( 'recipe' ) ? target.dataset.recipe : false;

			if ( recipeId ) {
				window.WPRecipeMaker.analytics.registerAction( recipeId, wprm_public.post_id, 'messenger-share-button' );
			}
			return true;
		} else if ( target.matches( '.wprm-recipe-twitter-share' ) ) {
			const recipeId = target.dataset.hasOwnProperty( 'recipe' ) ? target.dataset.recipe : false;

			if ( recipeId ) {
				window.WPRecipeMaker.analytics.registerAction( recipeId, wprm_public.post_id, 'twitter-share-button' );
			}
			return true;
		} else if ( target.matches( '.wprm-recipe-bluesky-share' ) ) {
			const recipeId = target.dataset.hasOwnProperty( 'recipe' ) ? target.dataset.recipe : false;

			if ( recipeId ) {
				window.WPRecipeMaker.analytics.registerAction( recipeId, wprm_public.post_id, 'bluesky-share-button' );
			}
			return true;
		} else if ( target.matches( '.wprm-recipe-mastodon-share' ) ) {
			const recipeId = target.dataset.hasOwnProperty( 'recipe' ) ? target.dataset.recipe : false;

			if ( recipeId ) {
				window.WPRecipeMaker.analytics.registerAction( recipeId, wprm_public.post_id, 'mastodon-share-button' );
			}
			return true;
		} else if ( target.matches( '.wprm-recipe-tumblr-share' ) ) {
			const recipeId = target.dataset.hasOwnProperty( 'recipe' ) ? target.dataset.recipe : false;

			if ( recipeId ) {
				window.WPRecipeMaker.analytics.registerAction( recipeId, wprm_public.post_id, 'tumblr-share-button' );
			}
			return true;
		} else if ( target.matches( '.wprm-recipe-text-share' ) ) {
			const recipeId = target.dataset.hasOwnProperty( 'recipe' ) ? target.dataset.recipe : false;

			if ( recipeId ) {
				window.WPRecipeMaker.analytics.registerAction( recipeId, wprm_public.post_id, 'text-share-button' );
			}
			return true;
		} else if ( target.matches( '.wprm-recipe-whatsapp-share' ) ) {
			const recipeId = target.dataset.hasOwnProperty( 'recipe' ) ? target.dataset.recipe : false;

			if ( recipeId ) {
				window.WPRecipeMaker.analytics.registerAction( recipeId, wprm_public.post_id, 'whatsapp-share-button' );
			}
			return true;
		} else if ( target.matches( '.wprm-recipe-email-share' ) ) {
			const recipeId = target.dataset.hasOwnProperty( 'recipe' ) ? target.dataset.recipe : false;

			if ( recipeId ) {
				window.WPRecipeMaker.analytics.registerAction( recipeId, wprm_public.post_id, 'email-share-button' );
			}
			return true;
		} else if ( target.matches( '.wprm-recipe-favorite' ) ) {
			const recipeId = target.dataset.hasOwnProperty( 'recipeId' ) ? target.dataset.recipeId : false;

			if ( recipeId ) {
				window.WPRecipeMaker.analytics.registerAction( recipeId, wprm_public.post_id, 'favorite-button', {
					action: target.classList.contains( 'wprm-recipe-favorite-active' ) ? 'remove' : 'add',
				} );
			}
			return true;
		} else if ( target.matches( '.wprm-recipe-add-to-collection-recipe' ) ) {
			const recipeId = target.dataset.hasOwnProperty( 'recipe' ) ? target.dataset.recipeId : false;

			if ( recipeId ) {
				window.WPRecipeMaker.analytics.registerAction( recipeId, wprm_public.post_id, 'add-to-collections-button' );
			}
			return true;
		} else if ( target.matches( '.wprm-recipe-add-to-shopping-list' ) ) {
			const recipeId = target.dataset.hasOwnProperty( 'recipe' ) ? target.dataset.recipeId : false;

			if ( recipeId ) {
				window.WPRecipeMaker.analytics.registerAction( recipeId, wprm_public.post_id, 'add-to-shopping-list-button' );
			}
			return true;
		} else if ( target.matches( '.wprm-recipe-cook-mode' ) ) {
			const recipeId = target.dataset.hasOwnProperty( 'recipeId' ) ? target.dataset.recipeId : false;

			if ( recipeId ) {
				window.WPRecipeMaker.analytics.registerAction( recipeId, wprm_public.post_id, 'cook-mode-button' );
			}
			return true;
		} else if ( target.matches( '.wprm-recipe-equipment a' ) ) {
			const container = target.closest( '.wprm-recipe-equipment-container' );

			if ( container ) {
				const item = target.closest( '.wprm-recipe-equipment-item' );
				const type = item && item.classList.contains( 'wprm-recipe-equipment-item-has-image' ) ? 'image' : 'text';
				const name = item ? item.querySelector( '.wprm-recipe-equipment-name' ) : target;
				const recipeId = container.dataset.recipe; 

				if ( recipeId ) {
					window.WPRecipeMaker.analytics.registerAction( recipeId, wprm_public.post_id, 'equipment-link', {
						url: target.href,
						type,
						name: name ? name.innerText : 'unknown',
					} );
				}
			}
			return true;
		} else if ( target.matches( '.wprm-recipe-ingredient a' ) ) {
			const container = target.closest( '.wprm-recipe-ingredients-container' );

			// Get ingredient name.
			let name = false;
			const parent = target.closest( '.wprm-recipe-ingredient' );
			if ( parent) {
				name = parent.querySelector( '.wprm-recipe-ingredient-name' );
			}

			if ( container ) {
				const recipeId = container.dataset.recipe; 

				if ( recipeId ) {
					window.WPRecipeMaker.analytics.registerAction( recipeId, wprm_public.post_id, 'ingredient-link', {
						url: target.href,
						name: name ? name.innerText : 'unknown',
					} );
				}
			}
			return true;
		} else if ( target.matches( '.wprm-recipe-instruction a' ) ) {
			const container = target.closest( '.wprm-recipe-instructions-container' );

			if ( container ) {
				const recipeId = container.dataset.recipe; 

				if ( recipeId ) {
					window.WPRecipeMaker.analytics.registerAction( recipeId, wprm_public.post_id, 'instruction-link', {
						url: target.href,
					} );
				}
			}
			return true;
		}

		return false;
	},
	registerAction: ( recipeId, postId, type, meta = {} ) => {		
		window.WPRecipeMaker.analytics.registerActionLocal( recipeId, postId, type, meta );
		window.WPRecipeMaker.analytics.registerActionGoogleAnalytics( recipeId, postId, type, meta );
	},
	registerActionOnce: ( recipeId, postId, type, meta = {} ) => {		
		if ( window.WPRecipeMaker.analytics.registeredActions.hasOwnProperty( `recipe-${recipeId}` ) && window.WPRecipeMaker.analytics.registeredActions[`recipe-${recipeId}`].hasOwnProperty( type ) ) {
			// Already tracked this action for this recipe on this pageload, ignore.
			return;
		}

		// Track action as already registered for this recipe.
		if ( ! window.WPRecipeMaker.analytics.registeredActions.hasOwnProperty( `recipe-${recipeId}` ) ) {
			window.WPRecipeMaker.analytics.registeredActions[`recipe-${recipeId}`] = {};
		}
		window.WPRecipeMaker.analytics.registeredActions[`recipe-${recipeId}`][ type ] = true;

		// Hadn't been tracked yet, so do it now.
		window.WPRecipeMaker.analytics.registerAction( recipeId, postId, type, meta );
	},
	registerActionLocal: ( recipeId, postId, type, meta = {} ) => {
		if ( wprm_public.settings.analytics_enabled ) {
			// Ignore these for local tracking, tracked in PHP.
			if ( 'comment-rating' === type || 'user-rating' === type ) {
				return;
			}

			let headers = {
				'Accept': 'application/json',
				'Content-Type': 'application/json',
			};

			// Only require nonce when logged in to prevent caching problems for regular visitors.
			if ( 0 < parseInt( wprm_public.user ) ) {
				headers['X-WP-Nonce'] = wprm_public.api_nonce;
			}

			// Register action through API.
			fetch( wprm_public.endpoints.analytics, {
				method: 'POST',
				headers,
				credentials: 'same-origin',
				body: JSON.stringify({
					recipeId,
					postId,
					type,
					meta,
					uid: getAnalyticsVisitorId(),
					nonce: wprm_public.nonce,
				}),
			});
		}
	},
	registerActionGoogleAnalytics: ( recipeId, postId, type, meta = {} ) => {
		if ( wprm_public.settings.google_analytics_enabled && window.hasOwnProperty( 'gtag' ) ) {
			const event = 'wprm_' + type.replace( /-/g, '_' );
			const label = type.replace( /-/g, ' ' );

			let eventData = {
				event_category: 'wprecipemaker',
				event_label: 'WPRM ' + label.charAt(0).toUpperCase() + label.slice(1),
				wprm_recipe_id: '' + recipeId,
				wprm_post_id: '' + postId,
			};
			
			// Check if recipe object is available.
			const recipe = window.WPRecipeMaker.manager.getRecipeImmediately( recipeId );
			
			if ( recipe ) {
				if ( recipe.data.hasOwnProperty( 'name' ) ) {
					eventData.wprm_recipe_name = recipe.data.name;
				}
				if ( recipe.data.hasOwnProperty( 'slug' ) ) {
					eventData.wprm_recipe_slug = recipe.data.slug;
				}
			}

			// Special case for ratings.
			if ( ( 'comment-rating' === type || 'user-rating' === type ) && meta.hasOwnProperty( 'rating' ) ) {
				eventData.value = meta.rating;
				delete meta.rating;
			}

			// Pass along other meta.
			if ( meta && 'object' === typeof meta ) {
				Object.keys( meta ).forEach( ( key ) => {
					if ( '' !== meta[key] && null !== meta[key] && typeof meta[key] !== 'undefined' ) {
						eventData[`wprm_event_${key}`] = '' + meta[key];
					}
				} );
			}

			window.gtag( 'event', event, eventData );
		}
	},
	registeredActions: {},
};

ready(() => {
	window.WPRecipeMaker.analytics.init();
});

function ready( fn ) {
    if (document.readyState != 'loading'){
        fn();
    } else {
        document.addEventListener('DOMContentLoaded', fn);
    }
}

function getCookieValue( a ) {
    var b = document.cookie.match('(^|;)\\s*' + a + '\\s*=\\s*([^;]+)');
    return b ? b.pop() : '';
}

function getAnalyticsVisitorId() {
	let visitorId = getCookieValue( 'wprm_analytics_visitor' );

	if ( ! visitorId ) {
		visitorId = generateAnalyticsVisitorId();
		setCookieValue( 'wprm_analytics_visitor', visitorId );
	}

	return visitorId;
}

function generateAnalyticsVisitorId() {
	if ( window.crypto && window.crypto.getRandomValues ) {
		const values = new Uint32Array( 2 );
		window.crypto.getRandomValues( values );

		return Date.now().toString( 36 ) + values[0].toString( 36 ) + values[1].toString( 36 );
	}

	return Date.now().toString( 36 ) + Math.random().toString( 36 ).substring( 2, 12 );
}

function setCookieValue( name, value ) {
	let cookie = name + '=' + encodeURIComponent( value ) + '; expires=Tue, 19 Jan 2038 03:14:07 GMT; path=/; SameSite=Lax';

	if ( 'https:' === window.location.protocol ) {
		cookie += '; Secure';
	}

	document.cookie = cookie;
}
