/**
 * Athena Analytics Helper
 * 1. Syncs LocalStorage UID to Cookie for server-side access
 * 2. Tracks Source & Channel Attribution for Analytics
 */
(function () {

	// ========================================
	// UID Synchronization
	// ========================================
	function getAthenaUidFromLS() {
		return localStorage.getItem('_athena-uid');
	}

	function setCookie(name, value, days) {
		let expires = "";
		if (days) {
			let date = new Date();
			date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
			expires = "; expires=" + date.toUTCString();
		}
		document.cookie = name + "=" + (value || "") + expires + "; path=/";
	}

	// Sync UID immediately
	const uid = getAthenaUidFromLS();
	if (uid) {
		setCookie("_athena-uid", uid, 365);
	}

	// ========================================
	// Source & Channel Attribution
	// ========================================

	// Runtime lock to prioritize URL attribution on the CURRENT page load only
	let runtimeLock = false;

	/**
	 * Map URL conversion-channel parameter to source/channel object
	 */
	function mapUrlChannelToAttribution(channelParam) {
		const mapping = {
			'voice': { source: 'search', channel: 'voice search' },
			'visual_camera': { source: 'visual search', channel: 'camera' },
			'visual_file_upload': { source: 'visual search', channel: 'file upload' },
			'visual_image_url': { source: 'visual search', channel: 'image url' }
		};
		return mapping[channelParam] || { source: '', channel: '' };
	}

	/**
	 * Save current attribution to SessionStorage
	 */
	function setCurrentAttribution(source, channel, isFromUrlParam = false) {
		// If URL found on THIS page load, events cannot overwrite it on same page
		if (runtimeLock && !isFromUrlParam) {
			return;
		}

		try {
			const attr = {
				source: source || '',
				channel: channel || '',
				timestamp: Date.now()
			};

			sessionStorage.setItem('athena_current_attr', JSON.stringify(attr));

			if (isFromUrlParam) {
				runtimeLock = true;
			}
		} catch (e) {
			console.warn('Athena: Unable to save attribution', e);
		}
	}

	/**
	 * Get current attribution from SessionStorage
	 */
	function getCurrentAttribution() {
		try {
			const data = sessionStorage.getItem('athena_current_attr');
			return data ? JSON.parse(data) : { source: '', channel: '' };
		} catch (e) {
			return { source: '', channel: '' };
		}
	}

	/**
	 * Detect if current page is the Athena Search Landing Page
	 */
	function isAthenaSearchResultPage() {
		const currentUrl = window.location.href;

		// 1. Configured URL check from settings
		const landingPageUrl = typeof athenaData !== 'undefined' ? athenaData.landingPageUrl : '';
		if (landingPageUrl && currentUrl.startsWith(landingPageUrl)) return true;

		// 2. Query parameter check (fallback)
		const urlParams = new URLSearchParams(window.location.search);
		if (urlParams.get('q')) return true;

		// 3. Search App Element check
		if (document.getElementById('athena-app') || document.querySelector('.athena-search-results')) return true;

		return false;
	}

	/**
	 * Detect if current page is part of the conversion funnel
	 * Funnel pages: Search Landing, Single Product, Cart, Checkout
	 */
	function isFunnelPage() {
		if (isAthenaSearchResultPage()) return true;

		// Single Product check: body class or element
		if (document.body.classList.contains('single-product') || document.querySelector('.woocommerce-product-details')) return true;

		// Cart / Checkout check: body classes
		if (document.body.classList.contains('woocommerce-cart') || document.body.classList.contains('woocommerce-checkout')) return true;

		return false;
	}

	/**
	 * Main Logic: Detect attribution on page load and handle navigation/resets
	 */
	function detectPageAttribution() {
		try {
			const urlParams = new URLSearchParams(window.location.search);
			const conversionChannel = urlParams.get('conversion-channel');

			const isLanding = isAthenaSearchResultPage();
			const isFunnel = isLanding || isFunnelPage();
			const existing = getCurrentAttribution();

			if (conversionChannel) {
				// 1. URL Entry Point - Highest priority!
				const attr = mapUrlChannelToAttribution(conversionChannel);
				setCurrentAttribution(attr.source, attr.channel, true);
			} else if (isLanding) {
				// 2. Landing Page load without Channel Param
				// This handles manual search or direct visits to search results.
				// We MUST set to 'search landing page' to ensure it's not empty and clears stale data.
				setCurrentAttribution('search', 'search landing page', false);
			} else if (isFunnel) {
				// 3. Funnel Navigation (Product/Cart) - Keep what we have
			} else {
				// 4. Distraction Page (Shop, Home, etc.) - RESET
				if (existing.source || existing.channel) {
					setCurrentAttribution('', '', false);
				}
			}
		} catch (e) {
			console.warn('Athena: Error detecting attribution', e);
		}
	}

	/**
	 * Sync Cookie with SessionStorage on page load
	 */
	function syncCookieWithSessionStorage() {
		try {
			const attr = getCurrentAttribution();

			// Always sync to the cookie for server-side access
			setCookie('_athena_last_attr', JSON.stringify({
				source: attr.source || '',
				channel: attr.channel || '',
				timestamp: Date.now()
			}), 1);
		} catch (e) {
			console.warn('[Athena] Error syncing Cookie:', e);
		}
	}

	// Run detection and sync on load
	detectPageAttribution();
	syncCookieWithSessionStorage();

	// ========================================
	// Event Listeners
	// ========================================

	/**
	 * First Click Data Event
	 * Triggered when user clicks on suggested/featured product
	 */
	window.addEventListener('first-click-data', function (event) {
		setCurrentAttribution('search', 'first click', false);
	});

	/**
	 * Autocomplete Data Event
	 * Triggered when user interacts with autocomplete dropdown
	 */
	window.addEventListener('autocomplete-data', function (event) {
		setCurrentAttribution('search', 'autocomplete', false);
	});

	/**
	 * Search Data Fetched Event
	 * Triggered when search landing page loads (Enter key search)
	 */
	window.addEventListener('searchDataFetched', function () {
		setCurrentAttribution('search', 'search landing page', false);
	});

	/**
	 * Keyword Redirect Event
	 * Triggered when search response contains a redirect URL
	 */
	window.addEventListener('keyword-redirect-data', function (event) {
		setCurrentAttribution('search', 'redirect', false);
	});

	// ========================================
	// Add to Cart Integration
	// ========================================

	/**
	 * Hook into WooCommerce AJAX "Add to Cart" event
	 * This fires BEFORE the actual cart update
	 */
	if (typeof jQuery !== 'undefined') {
		jQuery(document).on('adding_to_cart', function (event, button, data) {
			const attr = getCurrentAttribution();

			// Save to Cookie for PHP to read
			setCookie('_athena_last_attr', JSON.stringify({
				source: attr.source,
				channel: attr.channel,
				timestamp: Date.now()
			}), 1); // 1 day expiry
		});
	} else {
		console.warn('[Athena] jQuery not found - Add to Cart hook NOT registered!');
	}

	// ========================================
	// Expose getCurrentAttribution globally
	// ========================================
	window.athenaGetCurrentAttribution = getCurrentAttribution;

})();