jQuery(
	function ($) {
		var startTime = Date.now();
		var maxScroll = 0;
		var lastActivity = Date.now();
		var hasSentReferrer = false;
		var initialSent = false;

		// Update last activity on user interaction
		$( document ).on(
			'mousemove keypress scroll click touchstart',
			function () {
				lastActivity = Date.now();
			}
		);

		// Initial delayed load (5 seconds) to filter out immediate bounces
		setTimeout(
			function () {
				if ( ! initialSent ) {
					sendTrackingData();
					initialSent = true;
				}
			},
			5000
		);

		function updateScroll() {
			var scrollTop     = $( window ).scrollTop();
			var docHeight     = $( document ).height();
			var winHeight     = $( window ).height();
			var scrollPercent = (scrollTop / (docHeight - winHeight)) * 100;
			if (scrollPercent > maxScroll) {
				maxScroll = Math.round( scrollPercent );
			}
		}

		function sendTrackingData() {
			// Skip sending if the tab is hidden or user has been idle for more than 2 minutes
			if ( document.hidden || (Date.now() - lastActivity > 120000) ) {
				return;
			}

			updateScroll();
			var now = Date.now();

			var data = {
				action: 'wac_track_page',
				page_url: window.location.href,
				page_title: document.title,
				timestamp: Math.floor( now / 1000 ),
				time_spent: Math.round( (now - startTime) / 1000 ),
				scroll_percent: maxScroll,
				screen_size: window.screen.width + 'x' + window.screen.height
			};

			if ( ! hasSentReferrer ) {
				data.referrer   = document.referrer;
				hasSentReferrer = true;
			}

			var restUrl = wac_track_params.rest_url + '/track-page';

			if ( navigator.sendBeacon ) {
				const ok = navigator.sendBeacon(
					restUrl,
					new URLSearchParams( data )
				);
				if ( ! ok ) {
					$.post( restUrl, data );
				}
			} else {
				$.post( restUrl, data );
			}

			startTime = now;
			maxScroll = 0;
		}

		$( window ).on(
			'beforeunload',
			function () {
				sendTrackingData();
			}
		);

		$( 'a' ).on(
			'click',
			function () {
				sendTrackingData();
			}
		);

		// Smart interval increased to 30 seconds (down from 10s)
		setInterval( sendTrackingData, 30000 );

		$( window ).on( 'scroll', updateScroll );
	}
);