(function($) {
    'use strict';

    // Cart Session Tracker - Works with backend cron system
    class WPNTSCartSessionTracker {
        constructor() {
            // console.log('[WPNTS] 🛒 Cart Session Tracker initializing...');
            this.sessionKey = this.getSessionKey();
            this.lastActivity = Date.now();
            this.heartbeatInterval = null;
            this.activityTimeout = null;
            
            this.init();
        }

        /**
         * Get session key from cookie or create new one
         */
        getSessionKey() {
            // Try to get from cookie first
            const cookies = document.cookie.split(';');
            for (let cookie of cookies) {
                const [name, value] = cookie.trim().split('=');
                if (name === 'wpnts_cart_session') {
                    return value;
                }
            }
            
            // Create new session key
            const sessionKey = 'wpnts_' + Date.now() + '_' + Math.floor(Math.random() * 1000000);
            document.cookie = `wpnts_cart_session=${sessionKey}; path=/; max-age=${30 * 24 * 60 * 60}`;
            return sessionKey;
        }

        /**
         * Initialize tracking
         */
        init() {
            // Only track if we have a cart or are on relevant pages
            if (!this.shouldTrack()) {
                // console.log('[WPNTS] ⏭️ Cart session tracking not needed on this page');
                return;
            }

            // console.log('[WPNTS] ✅ Starting cart session tracking');
            
            // Send initial activity
            this.trackActivity({ action: 'page_load', page: window.location.pathname });
            
            // Set up activity tracking
            this.setupActivityTracking();
            
            // Set up heartbeat (every 2 minutes while active)
            this.startHeartbeat();
            
            // Track page unload
            this.setupUnloadTracking();
        }

        /**
         * Check if we should track this page/session
         */
        shouldTrack() {
            // Track on cart, checkout, shop pages
            const relevantPages = [
                'cart', 'checkout', 'shop', 'product'
            ];
            
            const currentPath = window.location.pathname.toLowerCase();
            const bodyClasses = document.body.className.toLowerCase();
            
            // Check if it's a WooCommerce page
            const isWooCommercePage = relevantPages.some(page => 
                currentPath.includes(page) || bodyClasses.includes(page)
            );
            
            // Check if cart has items (from WooCommerce global)
            const hasCartItems = this.hasCartItems();
            
            return isWooCommercePage || hasCartItems;
        }

        /**
         * Check if cart has items
         */
        hasCartItems() {
            // Check WooCommerce cart indicators
            const cartIndicators = [
                '.cart_item',
                '.wc-block-cart-items__row',
                '.woocommerce-cart-form__cart-item'
            ];
            
            return cartIndicators.some(selector => $(selector).length > 0);
        }

        /**
         * Set up activity tracking
         */
        setupActivityTracking() {
            // Track various user activities
            const events = ['click', 'scroll', 'keypress', 'mousemove'];
            
            events.forEach(event => {
                document.addEventListener(event, () => {
                    this.updateLastActivity();
                }, { passive: true });
            });

            // Track WooCommerce specific events
            $(document.body).on('added_to_cart removed_from_cart updated_cart_totals', (e) => {
                // console.log('[WPNTS] 🛒 WooCommerce cart event:', e.type);
                this.trackActivity({ action: e.type, timestamp: Date.now() });
                
                // Also update cart session immediately when cart changes
                setTimeout(() => {
                    this.trackActivity({ action: 'cart_updated', timestamp: Date.now() });
                }, 1000);
            });

            // Track quantity changes
            $(document).on('change', 'input[type="number"].qty, .wc-block-components-quantity-selector__input', (e) => {
                const quantity = $(e.target).val();
                // console.log('[WPNTS] 🔢 Quantity changed:', quantity);
                this.trackActivity({ action: 'quantity_change', quantity: quantity });
            });

            // Track add to cart button clicks
            $(document).on('click', '.add_to_cart_button, .single_add_to_cart_button, .wc-block-cart__submit-button', (e) => {
                // console.log('[WPNTS] 🛒 Add to cart clicked');
                this.trackActivity({ action: 'add_to_cart_clicked', timestamp: Date.now() });
            });

            // Track remove from cart
            $(document).on('click', '.remove, .wc-block-cart-item__remove-link', (e) => {
                // console.log('[WPNTS] 🗑️ Remove from cart clicked');
                this.trackActivity({ action: 'remove_from_cart_clicked', timestamp: Date.now() });
            });
        }

        /**
         * Update last activity timestamp
         */
        updateLastActivity() {
            const now = Date.now();
            
            // Only update if it's been more than 30 seconds since last update
            if (now - this.lastActivity > 30000) {
                this.lastActivity = now;
                
                // Clear existing timeout
                if (this.activityTimeout) {
                    clearTimeout(this.activityTimeout);
                }
                
                // Set timeout to send activity update
                this.activityTimeout = setTimeout(() => {
                    this.trackActivity({ action: 'user_activity', timestamp: now });
                }, 5000); // Send after 5 seconds of inactivity
            }
        }

        /**
         * Start heartbeat to keep session alive
         */
        startHeartbeat() {
            // Send heartbeat every 2 minutes while page is active
            this.heartbeatInterval = setInterval(() => {
                if (!document.hidden) {
                    this.trackActivity({ action: 'heartbeat', timestamp: Date.now() });
                }
            }, 120000); // 2 minutes
        }

        /**
         * Set up page unload tracking
         */
        setupUnloadTracking() {
            // Track when user leaves the page
            window.addEventListener('beforeunload', () => {
                this.trackActivity({ action: 'page_unload', timestamp: Date.now() });
            });

            // Track page visibility changes
            document.addEventListener('visibilitychange', () => {
                if (document.hidden) {
                    // console.log('[WPNTS] 👁️ Page hidden - potential abandonment');
                    this.trackActivity({ action: 'page_hidden', timestamp: Date.now() });
                } else {
                    // console.log('[WPNTS] 👁️ Page visible - user returned');
                    this.trackActivity({ action: 'page_visible', timestamp: Date.now() });
                }
            });
        }

        /**
         * Track activity to backend
         */
        trackActivity(activityData) {
            // Don't send if we don't have the necessary data
            if (!wpnts_cart_session_ajax || !wpnts_cart_session_ajax.ajax_url) {
                return;
            }

            const data = {
                action: 'wpnts_track_cart_session',
                nonce: wpnts_cart_session_ajax.nonce,
                session_key: this.sessionKey,
                activity: activityData
            };

            // Use sendBeacon for reliability on page unload
            if (activityData.action === 'page_unload' && navigator.sendBeacon) {
                const formData = new FormData();
                formData.append('action', 'wpnts_track_cart_session');
                formData.append('nonce', wpnts_cart_session_ajax.nonce);
                formData.append('session_key', this.sessionKey);
                formData.append('activity', JSON.stringify(activityData));
                
                navigator.sendBeacon(wpnts_cart_session_ajax.ajax_url, formData);
                return;
            }

            // Regular AJAX for other activities
            $.ajax({
                url: wpnts_cart_session_ajax.ajax_url,
                type: 'POST',
                data: {
                    action: 'wpnts_track_cart_session',
                    nonce: wpnts_cart_session_ajax.nonce,
                    session_key: this.sessionKey,
                    activity: JSON.stringify(activityData)
                },
                success: (response) => {
                    if (response.success) {
                        // console.log('[WPNTS] ✅ Cart session activity tracked:', activityData.action);
                    }
                },
                error: (xhr, status, error) => {
                    console.warn('[WPNTS] ⚠️ Failed to track cart session:', error);
                }
            });
        }

        /**
         * Cleanup on destroy
         */
        destroy() {
            if (this.heartbeatInterval) {
                clearInterval(this.heartbeatInterval);
            }
            if (this.activityTimeout) {
                clearTimeout(this.activityTimeout);
            }
        }
    }

    // Initialize when DOM is ready
    $(document).ready(function() {
        // Only initialize if we have the AJAX data
        if (typeof wpnts_cart_session_ajax !== 'undefined') {
            window.wpntsCartSessionTracker = new WPNTSCartSessionTracker();
        } else {
            // console.log('[WPNTS] ⚠️ Cart session AJAX data not available');
        }
    });

})(jQuery);