(function($) {
    'use strict';

    // Enhanced WPNTS Checkout Tracker Class
    class WPNTSEnhancedCheckoutTracker {
        constructor(pageInfo) {
            // console.log('[WPNTS] 🚀 Enhanced Checkout Tracker initializing...');
            this.sessionKey = this.getSessionKey();
            this.throttleTimer = null;
            this.lastSentData = null;
            this.pageInfo = pageInfo || {};
            this.abandonmentTimer = null;
            this.userInteractions = [];
            this.cartInteractions = [];
            this.isCheckoutStarted = false;
            this.checkoutStartTime = null;
            this.minimumTimeBeforeAbandon = 30000; // 30 seconds minimum
            this.abandonmentDelay = 120000; // 2 minutes before marking as abandoned
            
            // console.log('[WPNTS] 🔑 Session Key:', this.sessionKey);
            // console.log('[WPNTS] 📄 Page Info:', this.pageInfo);
            this.init();
        }

        /**
         * Get or create session key
         */
        getSessionKey() {
            try {
                let key = sessionStorage.getItem('wpnts_session_key');
                if (!key) {
                    key = 'wpnts_' + Date.now() + '_' + Math.floor(Math.random() * 1000000);
                    sessionStorage.setItem('wpnts_session_key', key);
                    // console.log('[WPNTS] 🆕 Created new session key:', key);
                } else {
                    // console.log('[WPNTS] 🔄 Using existing session key:', key);
                }
                return key;
            } catch (e) {
                console.warn('[WPNTS] ⚠️ SessionStorage not available, using fallback');
                return 'wpnts_' + Date.now() + '_' + Math.floor(Math.random() * 1000000);
            }
        }

        /**
         * Enhanced product detection for WooCommerce Blocks and classic themes
         */
        collectProductNames() {
            // console.log('[WPNTS] 🔍 Starting enhanced product name collection...');
            const product_names = [];

            // First, try to get products from cart interactions (most reliable)
            if (this.cartInteractions && this.cartInteractions.length > 0) {
                // console.log('[WPNTS] 🔄 Extracting products from cart interactions...');
                this.cartInteractions.forEach(interaction => {
                    if (interaction.product && interaction.product !== 'Unknown Product' && interaction.product !== 'Test Product') {
                        product_names.push(interaction.product);
                    }
                });
            }

            // Enhanced selectors for WooCommerce Blocks and various themes
            const nameSelectors = [
                // WooCommerce Blocks (new) - more specific
                '.wc-block-cart-items__row .wc-block-cart-item__product .wc-block-cart-item__product-name',
                '.wc-block-cart-items__row .wc-block-cart-item__product-name',
                '.wc-block-cart-item__product-name',
                '.wc-block-checkout-order-summary__item .wc-block-checkout-order-summary__item-name',
                
                // Classic WooCommerce
                '.woocommerce-checkout-review-order-table .product-name',
                '.woocommerce-cart-form .product-name',
                'table.shop_table.cart .product-name',
                '.cart_item .product-name',
                '.order_item .product-name',
                
                // Generic selectors
                '.product-name',
                '.wc-order-review .product-name',
                '.cart_item td.product-name',
                '.shop_table tbody tr td:nth-child(2)',
                '.cart-item-name',
                '.item-name',
                'tr.cart_item .product-name a',
                '.checkout-review-order .product-name',
                
                // More specific selectors
                '.cart_item td:first-child + td',
                '.cart_item td:nth-child(2) a',
                '.woocommerce-cart-form tbody tr td:nth-child(2)',
                '.shop_table.cart tbody tr td:nth-child(2) a'
            ];

            nameSelectors.forEach(selector => {
                const elements = $(selector);
                // console.log('[WPNTS] 🔍 Checking selector:', selector, 'found:', elements.length);
                
                elements.each(function() {
                    const el = $(this).clone();
                    // Remove quantity and other elements
                    el.find('strong, .quantity, .product-quantity, .woocommerce-Price-amount, .remove').remove();
                    let txt = el.text().trim();
                    
                    // If no text, try getting from link or data attributes
                    if (!txt) {
                        txt = $(this).find('a').text().trim();
                    }
                    if (!txt) {
                        txt = $(this).attr('data-product-name') || $(this).data('product-name') || '';
                    }
                    
                    // Clean up common patterns
                    txt = txt.replace(/×\s*\d+/g, '').trim(); // Remove quantity like "× 2"
                    txt = txt.replace(/\s+/g, ' ').trim(); // Clean up whitespace
                    txt = txt.replace(/^Remove\s+/i, '').trim(); // Remove "Remove" prefix
                    
                    if (txt && txt.length > 2) {
                        // console.log('[WPNTS] ✅ Found product:', txt);
                        product_names.push(txt);
                    }
                });
            });

            // Fallback: Try aria-labels from quantity buttons (since they work)
            if (product_names.length === 0) {
                // console.log('[WPNTS] 🔄 Trying aria-labels from quantity buttons...');
                $('.wc-block-components-quantity-selector__button').each(function() {
                    const ariaLabel = $(this).attr('aria-label') || '';
                    const match = ariaLabel.match(/(?:Reduce|Increase) quantity of (.+?)$/i);
                    if (match && match[1]) {
                        const productName = match[1].trim();
                        if (productName && productName.length > 2) {
                            // console.log('[WPNTS] ✅ Found product from aria-label:', productName);
                            product_names.push(productName);
                        }
                    }
                });
            }

            // Fallback: Try remove button aria-labels
            if (product_names.length === 0) {
                // console.log('[WPNTS] 🔄 Trying remove button aria-labels...');
                $('.wc-block-cart-item__remove-link, .remove').each(function() {
                    const ariaLabel = $(this).attr('aria-label') || '';
                    const match = ariaLabel.match(/Remove (.+?) from/i);
                    if (match && match[1]) {
                        const productName = match[1].trim();
                        if (productName && productName.length > 2) {
                            // console.log('[WPNTS] ✅ Found product from remove aria-label:', productName);
                            product_names.push(productName);
                        }
                    }
                });
            }

            // console.log('[WPNTS] 📦 Total products found:', product_names.length, product_names);
            return this.uniqueArray(product_names);
        }

        /**
         * Extract products from WooCommerce cart fragments
         */
        extractProductsFromCartFragments(product_names) {
            try {
                // Check if cart fragments are available
                if (typeof Storage !== 'undefined') {
                    const cartFragments = sessionStorage.getItem('wc_fragments') || localStorage.getItem('wc_fragments');
                    if (cartFragments) {
                        const fragments = JSON.parse(cartFragments);
                        // console.log('[WPNTS] 🧩 Found cart fragments:', fragments);
                        
                        // Extract product names from fragments
                        Object.values(fragments).forEach(fragment => {
                            if (typeof fragment === 'string') {
                                const $fragment = $(fragment);
                                $fragment.find('.product-name, .wc-block-cart-item__product-name').each(function() {
                                    const name = $(this).text().trim();
                                    if (name && name.length > 2) {
                                        product_names.push(name);
                                    }
                                });
                            }
                        });
                    }
                }
            } catch (e) {
                console.warn('[WPNTS] ⚠️ Error extracting from cart fragments:', e);
            }
        }

        /**
         * Extract products from WooCommerce REST API
         */
        extractProductsFromRestAPI(product_names) {
            // This would be implemented if we have access to WooCommerce Store API
            // console.log('[WPNTS] 🌐 REST API extraction not implemented yet');
        }

        /**
         * Track cart interactions (quantity changes, removals)
         */
        trackCartInteraction(type, productName, quantity, value) {
            const interaction = {
                type: type, // 'increase', 'decrease', 'remove', 'add'
                product: productName,
                quantity: quantity,
                value: value,
                timestamp: Date.now()
            };
            
            this.cartInteractions.push(interaction);
            // console.log('[WPNTS] 🛒 Cart interaction tracked:', interaction);
            
            // Send interaction data
            this.sendCartInteraction(interaction);
            
            // Limit stored interactions to last 50
            if (this.cartInteractions.length > 50) {
                this.cartInteractions = this.cartInteractions.slice(-50);
            }
        }

        /**
         * Send cart interaction to server
         */
        sendCartInteraction(interaction) {
            const data = {
                action: 'wpnts_track_cart_interaction',
                nonce: wpnts_checkout_ajax.nonce,
                session_key: this.sessionKey,
                interaction: JSON.stringify(interaction)
            };

            $.ajax({
                url: wpnts_checkout_ajax.ajax_url,
                type: 'POST',
                data: data,
                success: (response) => {
                    // console.log('[WPNTS] ✅ Cart interaction sent successfully');
                },
                error: (xhr, status, error) => {
                    console.warn('[WPNTS] ⚠️ Failed to send cart interaction:', error);
                }
            });
        }

        /**
         * Enhanced checkout data collection
         */
        collectCheckoutData() {
            // console.log('[WPNTS] 📊 Collecting enhanced checkout data...');
            const data = {};

            // Get billing information with enhanced selectors
            const emailSelectors = [
                "input[name='billing_email']", 
                "input#billing_email", 
                "input[type='email']",
                ".wc-block-checkout__email input[type='email']",
                "#email"
            ];
            
            let $email = null;
            emailSelectors.forEach(selector => {
                if (!$email || $email.length === 0) {
                    $email = $(selector).first();
                }
            });
            data.email = $email && $email.length ? $email.val().trim() : '';

            // Enhanced name collection with more selectors
            const firstNameSelectors = [
                "input[name='billing_first_name']",
                "input#billing_first_name", 
                ".wc-block-checkout__billing-fields input[placeholder*='First']",
                ".wc-block-checkout__contact-fields input[placeholder*='First']",
                "input[placeholder*='First name']"
            ];
            
            const lastNameSelectors = [
                "input[name='billing_last_name']",
                "input#billing_last_name",
                ".wc-block-checkout__billing-fields input[placeholder*='Last']", 
                ".wc-block-checkout__contact-fields input[placeholder*='Last']",
                "input[placeholder*='Last name']"
            ];
            
            let firstName = '';
            let lastName = '';
            
            firstNameSelectors.forEach(selector => {
                if (!firstName) {
                    const $el = $(selector).first();
                    if ($el.length) firstName = $el.val() || '';
                }
            });
            
            lastNameSelectors.forEach(selector => {
                if (!lastName) {
                    const $el = $(selector).first();
                    if ($el.length) lastName = $el.val() || '';
                }
            });
            
            data.name = (firstName + ' ' + lastName).trim();

            // Fallback for combined name fields
            if (!data.name) {
                const nameSelectors = [
                    "input[name='billing_name']",
                    "input#billing_name",
                    ".wc-block-checkout__billing-fields input[placeholder*='Name']",
                    ".wc-block-checkout__contact-fields input[placeholder*='Name']",
                    "input[placeholder*='Full name']"
                ];
                
                nameSelectors.forEach(selector => {
                    if (!data.name) {
                        const $el = $(selector).first();
                        if ($el.length) data.name = $el.val().trim();
                    }
                });
            }

            // Enhanced phone collection
            const phoneSelectors = [
                "input[name='billing_phone']", 
                "input#billing_phone", 
                "input[type='tel']",
                ".wc-block-checkout__billing-fields input[type='tel']"
            ];
            
            let $phone = null;
            phoneSelectors.forEach(selector => {
                if (!$phone || $phone.length === 0) {
                    $phone = $(selector).first();
                }
            });
            data.phone = $phone && $phone.length ? $phone.val().trim() : '';

            // Enhanced address collection
            const addr1 = $("input[name='billing_address_1'], .wc-block-checkout__billing-fields input[placeholder*='Address']").first().val() || '';
            const city = $("input[name='billing_city'], .wc-block-checkout__billing-fields input[placeholder*='City']").first().val() || '';
            data.address = (addr1 + ' ' + city).trim();

            // Collect product information with enhanced methods
            data.product_names = this.collectProductNames();
            data.product_links = this.collectProductLinks();
            data.product_ids = this.collectProductIds();
            data.cart_data = this.collectCartData();
            data.total_amount = this.calculateTotalAmount();
            
            // Add interaction data
            data.cart_interactions = this.cartInteractions;
            data.user_interactions = this.userInteractions;
            data.checkout_started = this.isCheckoutStarted;
            data.time_on_checkout = this.checkoutStartTime ? Date.now() - this.checkoutStartTime : 0;

            return data;
        }

        /**
         * Smart validation - only track meaningful checkout attempts
         */
        shouldTrackAsIncomplete(data) {
            // Don't track if user just landed on checkout
            if (!this.isCheckoutStarted) {
                return false;
            }
            
            // If user has cart interactions, track regardless of time (shows engagement)
            if (data.cart_interactions && data.cart_interactions.length > 0) {
                // console.log('[WPNTS] ✅ Tracking due to cart interactions:', data.cart_interactions.length);
                return true;
            }
            
            // Don't track if user hasn't spent minimum time (unless they have interactions)
            if (data.time_on_checkout < this.minimumTimeBeforeAbandon) {
                // console.log('[WPNTS] ⏰ Not enough time on checkout:', data.time_on_checkout, 'min required:', this.minimumTimeBeforeAbandon);
                return false;
            }
            
            // Must have either contact info OR products OR interactions
            const hasContact = !!(data.email || data.phone || data.name);
            const hasProducts = !!(data.product_names.length > 0 || data.product_ids.length > 0);
            const hasInteractions = !!(data.cart_interactions && data.cart_interactions.length > 0);
            
            const shouldTrack = hasContact || hasProducts || hasInteractions;

            
            return shouldTrack;
        }

        /**
         * Mark checkout as started (user began filling form)
         */
        markCheckoutStarted() {
            if (!this.isCheckoutStarted) {
                this.isCheckoutStarted = true;
                this.checkoutStartTime = Date.now();
                // console.log('[WPNTS] 🎯 Checkout process started');
                
                // Clear any existing abandonment timer
                if (this.abandonmentTimer) {
                    clearTimeout(this.abandonmentTimer);
                }
                
                // Start the abandonment timer immediately when checkout starts
                this.startAbandonmentTimer();
            }
        }

        /**
         * Start abandonment timer
         */
        startAbandonmentTimer() {
            // Clear existing timer
            if (this.abandonmentTimer) {
                clearTimeout(this.abandonmentTimer);
            }
            
            // Only start timer if checkout has actually started
            if (!this.isCheckoutStarted) {
                return;
            }
            
            // console.log('[WPNTS] ⏰ Starting abandonment timer...');
            
            this.abandonmentTimer = setTimeout(() => {
                // console.log('[WPNTS] 🚨 Abandonment timer triggered - sending data');
                this.sendToServer(true); // Force send as abandonment
            }, this.abandonmentDelay);
        }

        /**
         * Enhanced send to server with abandonment logic
         */
        sendToServer(isAbandonment = false) {
            // console.log('[WPNTS] 📤 Attempting to send data to server...', isAbandonment ? '(ABANDONMENT)' : '');
            
            const data = this.collectCheckoutData();
            
            if (!data) {
                // console.log('[WPNTS] ⏭️ No data collected, skipping...');
                return;
            }
            
            // For abandonment, always send regardless of validation
            // For regular tracking, use enhanced validation
            if (!isAbandonment && !this.shouldTrackAsIncomplete(data)) {
                return;
            }
            
            // Check if data is similar to avoid spam (but allow abandonment updates)
            if (this.lastSentData && this.dataIsSimilar(data, this.lastSentData) && !isAbandonment) {
                // console.log('[WPNTS] ⏭️ Data unchanged, skipping...');
                return;
            }

            // Add metadata
            data.session_key = this.sessionKey;
            data.is_abandonment = isAbandonment;
            data.page_info = this.pageInfo;

            // console.log('[WPNTS] 📡 Sending AJAX request with payload:', data);

            const ajaxData = {
                action: 'wpnts_save_incomplete_order',
                nonce: wpnts_checkout_ajax.nonce,
                session_key: data.session_key,
                email: data.email,
                name: data.name,
                phone: data.phone,
                address: data.address,
                product_ids: JSON.stringify(data.product_ids || []),
                product_names: JSON.stringify(data.product_names || []),
                product_links: JSON.stringify(data.product_links || []),
                cart_data: JSON.stringify(data.cart_data || {}),
                total_amount: data.total_amount || 0,
                cart_interactions: JSON.stringify(data.cart_interactions || []),
                is_abandonment: isAbandonment,
                time_on_checkout: data.time_on_checkout || 0
            };

            $.ajax({
                url: wpnts_checkout_ajax.ajax_url,
                type: 'POST',
                data: ajaxData,
                success: (response) => {
                    // console.log('[WPNTS] ✅ Server response received:', response);
                    if (response.success && response.data && response.data.id) {
                        // console.log('[WPNTS] 💾 Incomplete order saved with ID:', response.data.id);
                        this.lastSentData = data;
                    } else {
                        console.warn('[WPNTS] ⚠️ Server response indicates failure:', response);
                    }
                },
                error: (xhr, status, error) => {
                    console.error('[WPNTS] ❌ AJAX Error:', error);
                    console.error('[WPNTS] 📄 Response:', xhr.responseText);
                }
            });
        }

        /**
         * Enhanced event listeners
         */
        init() {
            // console.log('[WPNTS] 🎯 Initializing enhanced event listeners...');
            
            // If user has items in cart or is on checkout, start engagement tracking
            if (this.pageInfo.hasCartItems || this.pageInfo.isCheckoutPage) {
                // console.log('[WPNTS] 🎯 User has cart items or on checkout - starting engagement tracking');
                // Give user 30 seconds to start interacting, then begin abandonment tracking
                setTimeout(() => {
                    if (!this.isCheckoutStarted) {
                        // console.log('[WPNTS] ⏰ No interaction detected, starting passive abandonment tracking');
                        this.markCheckoutStarted();
                    }
                }, 30000); // 30 seconds
            }
            
            // Listen for form interactions to mark checkout as started
            $(document).on('input focus', 'form.checkout input, form.checkout textarea, form.checkout select, .wc-block-checkout input, .wc-block-checkout textarea, .wc-block-checkout select', () => {
                this.markCheckoutStarted();
                this.throttledSend();
            });

            // Also mark checkout started on cart interactions (shows engagement)
            $(document).on('click', '.quantity .plus, .quantity .minus, .wc-block-components-quantity-selector__button', () => {
                this.markCheckoutStarted();
            });

            // Enhanced cart quantity tracking with better event handling
            $(document).on('click', '.quantity .plus, .quantity .minus, .wc-block-components-quantity-selector__button', (e) => {
                e.preventDefault(); // Prevent any default behavior that might interfere
                
                const $button = $(e.target);
                const $quantityInput = $button.siblings('input').first();
                
                // If no input found, try parent container
                if ($quantityInput.length === 0) {
                    const $container = $button.closest('.wc-block-components-quantity-selector');
                    const $input = $container.find('input[type="number"]');
                    if ($input.length) {
                        $quantityInput = $input;
                    }
                }
                
                const currentQty = parseInt($quantityInput.val()) || 1;
                const isIncrease = $button.hasClass('wc-block-components-quantity-selector__button--plus') || $button.hasClass('plus');
                const isDecrease = $button.hasClass('wc-block-components-quantity-selector__button--minus') || $button.hasClass('minus');
                
                // Enhanced product name detection
                let productName = '';
                const $cartRow = $button.closest('.cart_item, .wc-block-cart-items__row, tr');
                
                // First try aria-label (most reliable)
                const ariaLabel = $button.attr('aria-label') || '';
                const ariaMatch = ariaLabel.match(/(?:Reduce|Increase) quantity of (.+?)$/i);
                if (ariaMatch && ariaMatch[1]) {
                    productName = ariaMatch[1].trim();
                }
                
                // Fallback to DOM selectors
                if (!productName) {
                    const nameSelectors = [
                        '.wc-block-cart-item__product-name',
                        '.product-name a',
                        '.product-name',
                        'td:nth-child(2) a',
                        'td:nth-child(2)',
                        '.wc-block-cart-item__product .wc-block-cart-item__product-name'
                    ];
                    
                    nameSelectors.forEach(selector => {
                        if (!productName) {
                            const $nameEl = $cartRow.find(selector);
                            if ($nameEl.length) {
                                productName = $nameEl.text().trim();
                                // Clean up the name
                                productName = productName.replace(/×\s*\d+/g, '').trim();
                                productName = productName.replace(/Remove.*$/i, '').trim();
                            }
                        }
                    });
                }
                

                
                // Track immediately, then check for actual change
                const interactionType = isIncrease ? 'increase' : (isDecrease ? 'decrease' : 'unknown');
                
                this.trackCartInteraction(
                    interactionType,
                    productName || 'Unknown Product',
                    isIncrease ? currentQty + 1 : Math.max(1, currentQty - 1),
                    0
                );
                
                // Also track after a delay to get the actual new quantity
                setTimeout(() => {
                    const actualNewQty = parseInt($quantityInput.val()) || currentQty;
                    if (actualNewQty !== currentQty) {
                   
                        this.trackCartInteraction(
                            actualNewQty > currentQty ? 'increase' : 'decrease',
                            productName || 'Unknown Product',
                            actualNewQty,
                            0
                        );
                    }
                }, 500);
            });

            // Enhanced cart removal tracking with better selectors
            $(document).on('click', '.remove, .remove-from-cart, .wc-remove-item, .cart_item .remove, .wc-block-cart-item__remove-link', (e) => {
                const $removeButton = $(e.target);
                const $cartRow = $removeButton.closest('.cart_item, .wc-block-cart-items__row, tr');
                
                // Enhanced product name detection for removal
                let productName = '';
                
                // First try aria-label (most reliable for WooCommerce Blocks)
                const ariaLabel = $removeButton.attr('aria-label') || '';
                const ariaMatch = ariaLabel.match(/Remove (.+?) from cart/i);
                if (ariaMatch && ariaMatch[1]) {
                    productName = ariaMatch[1].trim();
                }
                
                // Fallback to DOM selectors
                if (!productName) {
                    const nameSelectors = [
                        '.wc-block-cart-item__product-name',
                        '.product-name a',
                        '.product-name',
                        'td:nth-child(2) a',
                        'td:nth-child(2)',
                        '.wc-block-cart-item__product .wc-block-cart-item__product-name'
                    ];
                    
                    nameSelectors.forEach(selector => {
                        if (!productName) {
                            const $nameEl = $cartRow.find(selector);
                            if ($nameEl.length) {
                                productName = $nameEl.text().trim();
                                // Clean up the name
                                productName = productName.replace(/×\s*\d+/g, '').trim();
                                productName = productName.replace(/Remove.*$/i, '').trim();
                            }
                        }
                    });
                }
                
 
                this.trackCartInteraction('remove', productName || 'Unknown Product', 0, 0);
                
                // Mark checkout as started since user is actively managing cart
                this.markCheckoutStarted();
            });

            // Track when user leaves checkout (potential abandonment)
            $(window).on('beforeunload', () => {
                if (this.isCheckoutStarted) {
                    this.sendToServer(true);
                }
            });

            // Track page visibility changes
            if (typeof document.hidden !== 'undefined') {
                $(document).on('visibilitychange', () => {
                    if (document.hidden && this.isCheckoutStarted) {
                        this.startAbandonmentTimer();
                    } else if (!document.hidden) {
                        if (this.abandonmentTimer) {
                            clearTimeout(this.abandonmentTimer);
                            this.abandonmentTimer = null;
                        }
                    }
                });
            }

            // WooCommerce specific events
            $(document.body).on('updated_checkout', () => {
                this.throttledSend();
            });

            $(document.body).on('updated_wc_div', () => {
                this.throttledSend();
            });

            // WooCommerce Blocks specific events
            $(document.body).on('wc-blocks_added_to_cart', () => {
                this.markCheckoutStarted();
            });

            $(document.body).on('wc-blocks_removed_from_cart', () => {
                this.markCheckoutStarted();
            });

            // Additional event listeners for quantity changes (using event delegation)
            $(document).on('change', 'input[type="number"].wc-block-components-quantity-selector__input', (e) => {
                const $input = $(e.target);
                const $container = $input.closest('.wc-block-cart-items__row');
                
                // Get product name from aria-label of nearby buttons
                let productName = '';
                const $button = $container.find('.wc-block-components-quantity-selector__button').first();
                if ($button.length) {
                    const ariaLabel = $button.attr('aria-label') || '';
                    const match = ariaLabel.match(/(?:Reduce|Increase) quantity of (.+?)$/i);
                    if (match) {
                        productName = match[1].trim();
                    }
                }
                
                const newQty = parseInt($input.val()) || 1;
                // console.log('[WPNTS] 🔢 Quantity input changed:', { productName, newQty });
                
                this.trackCartInteraction('change', productName || 'Unknown Product', newQty, 0);
                this.markCheckoutStarted();
            });

            // Payment method changes
            $(document).on('change', 'input[name="payment_method"], .wc-block-checkout__payment-method input', () => {
                this.markCheckoutStarted();
                this.throttledSend();
            });

            // console.log('[WPNTS] ✅ Enhanced tracking initialized');
        }

        /**
         * Throttled send to avoid too many requests
         */
        throttledSend() {
            if (this.throttleTimer) clearTimeout(this.throttleTimer);
            this.throttleTimer = setTimeout(() => this.sendToServer(), 2000);
        }

        /**
         * Utility methods (keeping existing ones)
         */
        uniqueArray(arr) {
            return Array.from(new Set(arr.filter(Boolean)));
        }

        dataIsSimilar(newData, oldData) {
            return (
                newData.email === oldData.email &&
                newData.name === oldData.name &&
                newData.phone === oldData.phone &&
                JSON.stringify(newData.product_names) === JSON.stringify(oldData.product_names) &&
                Math.abs(newData.total_amount - oldData.total_amount) < 0.01
            );
        }

        // Placeholder methods for compatibility
        collectProductLinks() { return []; }
        collectProductIds() { return []; }
        collectCartData() { return {}; }
        calculateTotalAmount() { return 0; }

        /**
         * Test method to verify cart interactions are working
         */
        testCartInteraction() {
            // console.log('[WPNTS] 🧪 Testing cart interaction...');
            this.trackCartInteraction('test', 'Test Product', 1, 10.00);
            // console.log('[WPNTS] 📊 Current interactions:', this.cartInteractions);
        }

        /**
         * Force save incomplete order for testing
         */
        forceSaveIncompleteOrder() {
            // console.log('[WPNTS] 🧪 Force saving incomplete order...');
            
            // Mark checkout as started to pass validation
            this.markCheckoutStarted();
            
            // Add some test data if needed
            if (this.cartInteractions.length === 0) {
                this.trackCartInteraction('test', 'Test Product for Incomplete Order', 1, 25.00);
            }
            
            // Force send to server
            this.sendToServer(true);
        }

        /**
         * Test remove button detection
         */
        testRemoveButtons() {
            // console.log('[WPNTS] 🧪 Testing remove button detection...');
            
            $('.wc-block-cart-item__remove-link, .remove').each(function(index) {
                const $btn = $(this);
                const ariaLabel = $btn.attr('aria-label') || '';
                const $row = $btn.closest('.wc-block-cart-items__row, .cart_item, tr');
                
            });
            
            return 'Remove button test complete - check console';
        }

        
    }

    // Initialize when DOM is ready
    $(document).ready(function() {
        // console.log('[WPNTS] 🚀 Enhanced DOM Ready - Checking if tracking should initialize...');
        
        const isCheckoutPage = $('body').hasClass('woocommerce-checkout') || $('.woocommerce-checkout').length > 0;
        const isCartPage = $('body').hasClass('woocommerce-cart') || $('.woocommerce-cart').length > 0;
        
        // Enhanced cart item detection for blocks
        const cartItemSelectors = [
            '.cart_item',
            '.wc-block-cart-items__row',
            '.woocommerce-cart-form__cart-item',
            'tr.cart_item',
            '.cart-item',
            'tbody tr'
        ];
        
        let hasCartItems = false;
        cartItemSelectors.forEach(selector => {
            if ($(selector).length > 0) {
                hasCartItems = true;
            }
        });
        

        
        if (isCheckoutPage || (isCartPage && hasCartItems)) {
            // console.log('[WPNTS] ✅ Conditions met - Starting enhanced checkout tracker!');
            const pageInfo = { isCheckoutPage, isCartPage, hasCartItems };
            const tracker = new WPNTSEnhancedCheckoutTracker(pageInfo);
            window.wpntsTracker = tracker;
            
            // Make debug functions globally available
            window.wpntsTestInteraction = () => tracker.testCartInteraction();
            window.wpntsForceAbandon = () => tracker.sendToServer(true);
            window.wpntsForceSave = () => tracker.forceSaveIncompleteOrder();
            window.wpntsTestRemove = () => tracker.testRemoveButtons();
        } else {
            // console.log('[WPNTS] ❌ Conditions not met - Enhanced tracking not initialized');
        }
    });

})(jQuery);