/**
 * ActiveTrail Event Tracker
 * Frontend JavaScript for tracking ecommerce events
 */

(function ($) {
	'use strict';

	// Event tracker object
	var ActiveTrailEventTracker = {

		// Configuration
		config: {
			ajax_url: activetrail_events.ajax_url,
			nonce: activetrail_events.nonce,
			customer_email: activetrail_events.customer_email,
			session_id: activetrail_events.session_id,
			currency: activetrail_events.currency,
			debug: activetrail_events.debug
		},

		// Event queue for batching
		eventQueue: [],

		// Initialize the tracker
		init: function () {
			this.bindEvents();
			this.trackPageView();
			this.setupPeriodicSync();

			if (this.config.debug) {
				console.log( 'ActiveTrail Event Tracker initialized' );
			}
		},

		// Bind event listeners
		bindEvents: function () {
			var self = this;

			// Track product view on product pages
			if ($( 'body' ).hasClass( 'single-product' )) {
				this.trackProductView();
			}

			// Track add to cart button clicks
			$( document ).on(
				'click',
				'.single_add_to_cart_button',
				function (e) {
					var $form     = $( this ).closest( 'form.cart' );
					var productId = $form.find( 'input[name="add-to-cart"]' ).val() ||
								$form.find( 'button[name="add-to-cart"]' ).val();
					var quantity  = $form.find( 'input[name="quantity"]' ).val() || 1;

					if (productId) {
						self.trackAddToCartIntent( productId, quantity );
					}
				}
			);

			// Track AJAX add to cart
			$( document.body ).on(
				'added_to_cart',
				function (event, fragments, cart_hash, $button) {
					var productId = $button.data( 'product_id' ) || $button.val();
					var quantity  = $button.data( 'quantity' ) || 1;

					if (productId) {
						self.trackAddToCart( productId, quantity );
					}
				}
			);

			// Track cart page interactions
			if ($( 'body' ).hasClass( 'woocommerce-cart' )) {
				this.bindCartEvents();
			}

			// Track checkout page
			if ($( 'body' ).hasClass( 'woocommerce-checkout' )) {
				this.trackCheckoutStart();
				this.bindCheckoutEvents();
			}

			// Track remove from cart
			$( document ).on(
				'click',
				'.remove',
				function (e) {
					var $link     = $( this );
					var productId = self.extractProductIdFromRemoveLink( $link.attr( 'href' ) );

					if (productId) {
						self.trackRemoveFromCart( productId );
					}
				}
			);

			// Track quantity updates in cart
			$( document ).on(
				'change',
				'.cart .qty',
				function () {
					var $input      = $( this );
					var productId   = self.extractProductIdFromCartRow( $input.closest( 'tr' ) );
					var newQuantity = parseInt( $input.val() ) || 0;
					var oldQuantity = parseInt( $input.data( 'old-quantity' ) ) || 0;

					if (productId && newQuantity !== oldQuantity) {
						self.trackCartQuantityUpdate( productId, oldQuantity, newQuantity );
					}

					// Store new quantity as old quantity for next change
					$input.data( 'old-quantity', newQuantity );
				}
			);

			// Store initial quantities
			$( '.cart .qty' ).each(
				function () {
					$( this ).data( 'old-quantity', parseInt( $( this ).val() ) || 0 );
				}
			);
		},

		// Bind cart-specific events
		bindCartEvents: function () {
			var self = this;

			// Track cart view
			this.trackEvent(
				'cart_view',
				{
					cart_total: this.getCartTotal(),
					cart_items_count: this.getCartItemsCount()
				}
			);

			// Track proceed to checkout clicks
			$( document ).on(
				'click',
				'.checkout-button',
				function () {
					self.trackEvent(
						'proceed_to_checkout',
						{
							cart_total: self.getCartTotal(),
							cart_items_count: self.getCartItemsCount()
						}
					);
				}
			);
		},

		// Bind checkout-specific events
		bindCheckoutEvents: function () {
			var self = this;

			// Track checkout steps
			$( document ).on(
				'change',
				'#billing_email',
				function () {
					if ($( this ).val()) {
						self.trackEvent(
							'checkout_email_entered',
							{
								email: $( this ).val(),
								cart_total: self.getCartTotal()
							}
						);
					}
				}
			);

			// Track payment method selection
			$( document ).on(
				'change',
				'input[name="payment_method"]',
				function () {
					self.trackEvent(
						'checkout_payment_method_selected',
						{
							payment_method: $( this ).val(),
							cart_total: self.getCartTotal()
						}
					);
				}
			);

			// Track place order attempts
			$( document ).on(
				'click',
				'#place_order',
				function () {
					self.trackEvent(
						'checkout_place_order_clicked',
						{
							cart_total: self.getCartTotal(),
							payment_method: $( 'input[name="payment_method"]:checked' ).val()
						}
					);
				}
			);
		},

		// Track page view
		trackPageView: function () {
			var pageType = this.getPageType();

			this.trackEvent(
				'page_view',
				{
					page_type: pageType,
					page_url: window.location.href,
					page_title: document.title,
					referrer: document.referrer
				}
			);
		},

		// Track product view
		trackProductView: function () {
			var productData = this.getProductData();

			if (productData.product_id) {
				this.trackEvent( 'product_view', productData, productData.product_price );
			}
		},

		// Track add to cart intent (button click)
		trackAddToCartIntent: function (productId, quantity) {
			var productData      = this.getProductData( productId );
			productData.quantity = quantity;
			productData.intent   = true;

			this.trackEvent( 'add_to_cart_intent', productData, productData.product_price * quantity );
		},

		// Track successful add to cart
		trackAddToCart: function (productId, quantity) {
			var productData      = this.getProductData( productId );
			productData.quantity = quantity;

			this.trackEvent( 'add_to_cart', productData, productData.product_price * quantity );
		},

		// Track remove from cart
		trackRemoveFromCart: function (productId) {
			this.trackEvent(
				'remove_from_cart',
				{
					product_id: productId,
					cart_total: this.getCartTotal()
				}
			);
		},

		// Track cart quantity update
		trackCartQuantityUpdate: function (productId, oldQuantity, newQuantity) {
			this.trackEvent(
				'cart_quantity_update',
				{
					product_id: productId,
					old_quantity: oldQuantity,
					new_quantity: newQuantity,
					quantity_change: newQuantity - oldQuantity,
					cart_total: this.getCartTotal()
				}
			);
		},

		// Track checkout start
		trackCheckoutStart: function () {
			this.trackEvent(
				'checkout_start',
				{
					cart_total: this.getCartTotal(),
					cart_items_count: this.getCartItemsCount(),
					currency: this.config.currency
				},
				this.getCartTotal()
			);
		},

		// Generic event tracking method
		trackEvent: function (eventType, eventData, eventValue) {
			eventData  = eventData || {};
			eventValue = eventValue || 0;

			// Add common data
			eventData.timestamp         = new Date().toISOString();
			eventData.user_agent        = navigator.userAgent;
			eventData.screen_resolution = screen.width + 'x' + screen.height;
			eventData.viewport_size     = $( window ).width() + 'x' + $( window ).height();

			var event = {
				event_type: eventType,
				event_data: eventData,
				event_value: parseFloat( eventValue ) || 0,
				customer_email: this.config.customer_email,
				session_id: this.config.session_id,
				currency: this.config.currency
			};

			// Add to queue
			this.eventQueue.push( event );

			// Send immediately for critical events
			if (this.isCriticalEvent( eventType )) {
				this.sendEvent( event );
			}

			if (this.config.debug) {
				console.log( 'Event tracked:', eventType, eventData );
			}
		},

		// Check if event is critical and should be sent immediately
		isCriticalEvent: function (eventType) {
			var criticalEvents = [
				'add_to_cart',
				'remove_from_cart',
				'checkout_start',
				'checkout_place_order_clicked'
			];

			return criticalEvents.indexOf( eventType ) !== -1;
		},

		// Send single event to server
		sendEvent: function (event) {
			var self = this;

			$.ajax(
				{
					url: this.config.ajax_url,
					type: 'POST',
					data: {
						action: 'activetrail_track_event',
						nonce: this.config.nonce,
						event_type: event.event_type,
						event_data: event.event_data,
						event_value: event.event_value
					},
					success: function (response) {
						if (self.config.debug) {
							console.log( 'Event sent successfully:', event.event_type );
						}
					},
					error: function (xhr, status, error) {
						if (self.config.debug) {
							console.error( 'Failed to send event:', event.event_type, error );
						}

						// Store in localStorage for retry
						self.storeEventForRetry( event );
					}
				}
			);
		},

		// Send queued events in batch
		sendQueuedEvents: function () {
			if (this.eventQueue.length === 0) {
				return;
			}

			var eventsToSend = this.eventQueue.splice( 0, 10 ); // Send max 10 at a time
			var self         = this;

			eventsToSend.forEach(
				function (event) {
					if ( ! self.isCriticalEvent( event.event_type )) {
						self.sendEvent( event );
					}
				}
			);
		},

		// Store event in localStorage for retry
		storeEventForRetry: function (event) {
			try {
				var storedEvents = JSON.parse( localStorage.getItem( 'activetrail_failed_events' ) || '[]' );
				storedEvents.push( event );

				// Keep only last 50 failed events
				if (storedEvents.length > 50) {
					storedEvents = storedEvents.slice( -50 );
				}

				localStorage.setItem( 'activetrail_failed_events', JSON.stringify( storedEvents ) );
			} catch (e) {
				if (this.config.debug) {
					console.error( 'Failed to store event for retry:', e );
				}
			}
		},

		// Retry failed events from localStorage
		retryFailedEvents: function () {
			try {
				var storedEvents = JSON.parse( localStorage.getItem( 'activetrail_failed_events' ) || '[]' );

				if (storedEvents.length > 0) {
					var self = this;

					storedEvents.forEach(
						function (event) {
							self.sendEvent( event );
						}
					);

					// Clear stored events after retry
					localStorage.removeItem( 'activetrail_failed_events' );
				}
			} catch (e) {
				if (this.config.debug) {
					console.error( 'Failed to retry events:', e );
				}
			}
		},

		// Setup periodic sync
		setupPeriodicSync: function () {
			var self = this;

			// Send queued events every 30 seconds
			setInterval(
				function () {
					self.sendQueuedEvents();
				},
				30000
			);

			// Retry failed events every 5 minutes
			setInterval(
				function () {
					self.retryFailedEvents();
				},
				300000
			);

			// Send events before page unload
			$( window ).on(
				'beforeunload',
				function () {
					self.sendQueuedEvents();
				}
			);
		},

		// Helper methods
		getPageType: function () {
			var body = $( 'body' );

			if (body.hasClass( 'single-product' )) {
				return 'product';
			}
			if (body.hasClass( 'woocommerce-cart' )) {
				return 'cart';
			}
			if (body.hasClass( 'woocommerce-checkout' )) {
				return 'checkout';
			}
			if (body.hasClass( 'woocommerce-account' )) {
				return 'account';
			}
			if (body.hasClass( 'woocommerce-shop' ) || body.hasClass( 'archive' )) {
				return 'shop';
			}

			return 'other';
		},

		getProductData: function (productId) {
			var data = {
				product_id: productId || this.getProductIdFromPage(),
				product_name: this.getProductName(),
				product_price: this.getProductPrice(),
				product_category: this.getProductCategory(),
				product_sku: this.getProductSku(),
				product_url: window.location.href
			};

			return data;
		},

		getProductIdFromPage: function () {
			// Try multiple methods to get product ID
			var productId = $( 'input[name="add-to-cart"]' ).val() ||
							$( 'button[name="add-to-cart"]' ).val() ||
							$( '.single_add_to_cart_button' ).data( 'product_id' ) ||
							$( 'body' ).attr( 'class' ).match( /postid-(\d+)/ );

			if (Array.isArray( productId )) {
				productId = productId[1];
			}

			return parseInt( productId ) || 0;
		},

		getProductName: function () {
			return $( '.product_title' ).text() ||
					$( 'h1.entry-title' ).text() ||
					document.title.split( ' - ' )[0] || '';
		},

		getProductPrice: function () {
			var priceText = $( '.price .amount' ).first().text() ||
							$( '.price' ).text() ||
							$( '.woocommerce-Price-amount' ).first().text() || '';

			// Extract numeric value
			var price = priceText.replace( /[^\d.,]/g, '' ).replace( ',', '.' );
			return parseFloat( price ) || 0;
		},

		getProductCategory: function () {
			var categories = [];
			$( '.posted_in a' ).each(
				function () {
					categories.push( $( this ).text() );
				}
			);
			return categories.join( ', ' );
		},

		getProductSku: function () {
			return $( '.sku' ).text() || '';
		},

		getCartTotal: function () {
			var totalText = $( '.cart-subtotal .amount' ).text() ||
							$( '.order-total .amount' ).text() ||
							$( '.cart_totals .amount' ).last().text() || '';

			var total = totalText.replace( /[^\d.,]/g, '' ).replace( ',', '.' );
			return parseFloat( total ) || 0;
		},

		getCartItemsCount: function () {
			return parseInt( $( '.cart_item' ).length ) ||
					parseInt( $( '.cart-contents-count' ).text() ) || 0;
		},

		extractProductIdFromRemoveLink: function (href) {
			if ( ! href) {
				return null;
			}

			var match = href.match( /remove_item=([^&]+)/ );
			return match ? match[1] : null;
		},

		extractProductIdFromCartRow: function ($row) {
			var classes = $row.attr( 'class' ) || '';
			var match   = classes.match( /cart_item_(\d+)/ );
			return match ? parseInt( match[1] ) : null;
		}
	};

	// Initialize when document is ready
	$( document ).ready(
		function () {
			ActiveTrailEventTracker.init();
		}
	);

	// Make it globally available for manual tracking
	window.ActiveTrailEventTracker = ActiveTrailEventTracker;

})( jQuery );
