/**
 * Grid Features Analytics Tracking
 *
 * Tracks user interactions with Grid Features for analytics purposes.
 * Supports Google Analytics 4 (gtag), Google Tag Manager (dataLayer),
 * and legacy Universal Analytics (ga).
 *
 * @package Shoptimizer
 */

(function() {
	'use strict';

	/**
	 * Send event to available analytics platforms
	 *
	 * @param {string} eventName - The event name
	 * @param {Object} eventData - The event data
	 */
	function sendAnalyticsEvent(eventName, eventData) {
		// Google Analytics 4 (gtag.js)
		if (typeof gtag !== 'undefined') {
			gtag('event', eventName, eventData);
		}

		// Google Tag Manager (dataLayer)
		if (typeof window.dataLayer !== 'undefined') {
			window.dataLayer.push({
				'event': eventName,
				'eventCategory': 'Grid Features',
				'eventAction': eventData.action || eventName,
				'eventLabel': eventData.label || '',
				'gridFeaturePosition': eventData.position || '',
				'gridFeatureUrl': eventData.url || ''
			});
		}

		// Universal Analytics (legacy ga.js)
		if (typeof ga !== 'undefined') {
			ga('send', 'event', 'Grid Features', eventData.action || eventName, eventData.label || '');
		}
	}

	/**
	 * Track grid feature impressions
	 */
	function trackImpressions() {
		var gridFeatures = document.querySelectorAll('.cg-grid-feature');

		if (gridFeatures.length === 0) {
			return;
		}

		// Use Intersection Observer for accurate impression tracking
		if ('IntersectionObserver' in window) {
			var observerOptions = {
				root: null,
				rootMargin: '0px',
				threshold: 0.5 // Feature must be 50% visible
			};

			var observer = new IntersectionObserver(function(entries) {
				entries.forEach(function(entry) {
					if (entry.isIntersecting && !entry.target.dataset.impressionTracked) {
						var position = entry.target.dataset.position || 'unknown';

						sendAnalyticsEvent('grid_feature_impression', {
							action: 'impression',
							label: 'Position: ' + position,
							position: position
						});

						// Mark as tracked to avoid duplicate events
						entry.target.dataset.impressionTracked = 'true';
					}
				});
			}, observerOptions);

			gridFeatures.forEach(function(feature) {
				observer.observe(feature);
			});
		} else {
			// Fallback for browsers without Intersection Observer
			gridFeatures.forEach(function(feature) {
				var position = feature.dataset.position || 'unknown';

				sendAnalyticsEvent('grid_feature_impression', {
					action: 'impression',
					label: 'Position: ' + position,
					position: position
				});
			});
		}
	}

	/**
	 * Track grid feature clicks
	 */
	function trackClicks() {
		var gridFeatures = document.querySelectorAll('.cg-grid-feature');

		gridFeatures.forEach(function(feature) {
			var links = feature.querySelectorAll('a');

			links.forEach(function(link) {
				link.addEventListener('click', function(e) {
					var position = feature.dataset.position || 'unknown';
					var url = this.href || '';
					var linkText = this.textContent.trim() || 'unknown';

					sendAnalyticsEvent('grid_feature_click', {
						action: 'click',
						label: 'Position: ' + position + ' | Link: ' + linkText,
						position: position,
						url: url
					});

					// Allow the click to proceed normally
				});
			});
		});
	}

	/**
	 * Initialize tracking when DOM is ready
	 */
	function init() {
		if (document.readyState === 'loading') {
			document.addEventListener('DOMContentLoaded', function() {
				trackImpressions();
				trackClicks();
			});
		} else {
			trackImpressions();
			trackClicks();
		}
	}

	// Start tracking
	init();

})();
