/**
 * A/B Test Click Tracking Script
 *
 * Handles tracking of shop product clicks and add-to-cart events for A/B tests.
 */
(function() {
	'use strict';

	if (typeof window.ugcAbTestConfig === 'undefined') {
		return;
	}

	var config = window.ugcAbTestConfig;
	var ajaxUrl = config.ajaxUrl;
	var nonce = config.nonce;
	var clickAction = config.clickAction;
	var shopAddToCartAction = config.shopAddToCartAction;
	var productPageAddToCartAction = config.productPageAddToCartAction;
	var isShop = config.isShop;
	var isSingleProduct = config.isSingleProduct;

	/**
	 * Send tracking request via fetch API.
	 *
	 * @param {string} action AJAX action name.
	 * @param {Object} data Tracking data.
	 */
	function sendTrackingRequest(action, data) {
		var formData = new FormData();
		formData.append('action', action);
		formData.append('_ajax_nonce', nonce);
		formData.append('test_id', data.testId);
		formData.append('product_id', data.productId);
		formData.append('variant', data.variant);

		if (navigator.sendBeacon && navigator.sendBeacon(ajaxUrl, formData)) {
			return;
		}

		if (window.fetch) {
			window.fetch(ajaxUrl, {
				method: 'POST',
				body: formData,
				credentials: 'same-origin',
				keepalive: true
			}).catch(function() {});
		}
	}

	/**
	 * Normalize a URL for click matching.
	 *
	 * @param {string} url URL to normalize.
	 * @return {string} Normalized URL.
	 */
	function normalizeUrl(url) {
		try {
			var parsed = new URL(url, window.location.href);
			parsed.hash = '';
			return parsed.href.replace(/\/$/, '');
		} catch (error) {
			return String(url || '').replace(/#.*$/, '').replace(/\/$/, '');
		}
	}

	/**
	 * Get tracking data from a marker element.
	 *
	 * @param {HTMLElement} marker Marker element.
	 * @return {Object|null} Tracking data or null.
	 */
	function getTrackingDataFromMarker(marker) {
		if (!marker) {
			return null;
		}

		var testId = marker.getAttribute('data-test-id');
		var productId = marker.getAttribute('data-product-id');
		var variant = marker.getAttribute('data-variant');

		if (!testId || !productId || !variant) {
			return null;
		}

		return {
			testId: testId,
			productId: parseInt(productId, 10),
			variant: variant
		};
	}

	/**
	 * Handle shop product click tracking.
	 */
	function initShopClickTracking() {
		if (!isShop) {
			return;
		}

		var markers = document.querySelectorAll('.ugcify-ab-shop-click-marker');
		if (!markers.length) {
			return;
		}

		// Map product URLs to tracking data for quick lookup
		var productTrackingMap = {};
		markers.forEach(function(marker) {
			var productUrl = marker.getAttribute('data-product-url');
			var trackingData = getTrackingDataFromMarker(marker);
			if (productUrl && trackingData) {
				productTrackingMap[normalizeUrl(productUrl)] = trackingData;
			}
		});

		// Track clicks on product links
		document.addEventListener('click', function(e) {
			var target = e.target;
			var link = target.closest('a');

			if (!link) {
				return;
			}

			var href = normalizeUrl(link.href || link.getAttribute('href'));
			if (!href || !productTrackingMap[href]) {
				return;
			}

			var trackingData = productTrackingMap[href];
			sendTrackingRequest(clickAction, trackingData);
		}, true);
	}

	/**
	 * Handle single product page add-to-cart tracking.
	 */
	function initProductPageAddToCartTracking() {
		if (!isSingleProduct) {
			return;
		}

		var marker = document.querySelector('.ugcify-ab-product-marker');
		var trackingData = getTrackingDataFromMarker(marker);

		if (!trackingData) {
			return;
		}

		// Track add-to-cart via AJAX
		if (window.jQuery) {
			window.jQuery(document).on('added_to_cart', function() {
				sendTrackingRequest(productPageAddToCartAction, trackingData);
			});
		}

		// Track add-to-cart via form submission (fallback)
		document.addEventListener('submit', function(e) {
			var form = e.target;
			if (form && form.classList.contains('cart')) {
				sendTrackingRequest(productPageAddToCartAction, trackingData);
			}
		}, true);
	}

	/**
	 * Handle shop page add-to-cart tracking.
	 */
	function initShopAddToCartTracking() {
		if (!isShop) {
			return;
		}

		// Track add-to-cart via AJAX on shop pages
		if (!window.jQuery) {
			return;
		}

		window.jQuery(document).on('added_to_cart', function(event, fragments, cartHash, button) {
			if (!button) {
				return;
			}

			// Find the closest product container
			var productContainer = button.closest('.product');
			if (!productContainer) {
				return;
			}

			var marker = productContainer.querySelector('.ugcify-ab-shop-click-marker');
			var trackingData = getTrackingDataFromMarker(marker);

			if (trackingData) {
				sendTrackingRequest(shopAddToCartAction, trackingData);
			}
		});
	}

	/**
	 * Handle single product page visit tracking.
	 */
	function initProductPageVisitTracking() {
		if (!isSingleProduct) {
			return;
		}

		var marker = document.querySelector('.ugcify-ab-product-marker');
		var trackingData = getTrackingDataFromMarker(marker);

		if (!trackingData) {
			return;
		}

		// Avoid duplicate tracking during the same session for the same test/product
		var visitKey = 'ugc_ab_visited_' + trackingData.testId + '_' + trackingData.productId;
		if (!sessionStorage.getItem(visitKey)) {
			sessionStorage.setItem(visitKey, '1');
			sendTrackingRequest(config.productPageVisitAction, trackingData);
		}
	}

	// Initialize tracking when DOM is ready
	if (document.readyState === 'loading') {
		document.addEventListener('DOMContentLoaded', function() {
			initShopClickTracking();
			initProductPageAddToCartTracking();
			initShopAddToCartTracking();
			initProductPageVisitTracking();
		});
	} else {
		initShopClickTracking();
		initProductPageAddToCartTracking();
		initShopAddToCartTracking();
		initProductPageVisitTracking();
	}
})();
