(function($) {
    'use strict';

    // Enhanced WPNTS Checkout Tracker Class
    class WPNTSEnhancedCheckoutTracker {
        constructor(pageInfo) {
            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
         
            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;
            }
            
            // Must have actual products in cart to track
            const hasProducts = !!(data.product_names.length > 0 || data.product_ids.length > 0);
            if (!hasProducts) {
                // console.log('[WPNTS] ❌ No products found, not tracking');
                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 meaningful engagement
            const hasContact = !!(data.email || data.phone || data.name);
            const hasInteractions = !!(data.cart_interactions && data.cart_interactions.length > 0);
            
            const shouldTrack = hasContact || 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] 📤 Frontend tracking disabled - Backend handles all cart tracking');
            
            // DISABLED: Backend now handles all cart tracking through WooCommerce hooks
            // The CartAbandonmentTracker handles:
            // - Cart additions/removals
            // - Incomplete order creation/updates
            // - Abandonment detection via cron
            
            return;
        }

        /**
         * Enhanced event listeners
         */
        init() {
            // console.log('[WPNTS] 🎯 Initializing enhanced event listeners...');
            
            // DON'T automatically start tracking just for being on checkout page
            // Only start tracking when user actually interacts with the page
            
            // 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
            );
        }

        /**
         * Collect product links from cart
         */
        collectProductLinks() {
            const product_links = [];
            
            // Enhanced selectors for product links
            const linkSelectors = [
                '.wc-block-cart-items__row .wc-block-cart-item__product-name a',
                '.cart_item .product-name a',
                '.woocommerce-cart-form .product-name a',
                'table.shop_table.cart .product-name a',
                '.order_item .product-name a',
                '.checkout-review-order .product-name a'
            ];
            
            linkSelectors.forEach(selector => {
                $(selector).each(function() {
                    const href = $(this).attr('href');
                    if (href && href.length > 0) {
                        product_links.push(href);
                    }
                });
            });
            
            return this.uniqueArray(product_links);
        }

        /**
         * Collect product IDs from cart
         */
        collectProductIds() {
            const product_ids = [];
            
            // Try to get product IDs from various sources
            const idSelectors = [
                '.cart_item[data-product_id]',
                '.wc-block-cart-items__row[data-product-id]',
                'tr.cart_item',
                '.cart-item[data-product-id]'
            ];
            
            idSelectors.forEach(selector => {
                $(selector).each(function() {
                    const $item = $(this);
                    let productId = $item.attr('data-product_id') || 
                                   $item.attr('data-product-id') || 
                                   $item.data('product_id') || 
                                   $item.data('product-id');
                    
                    // Try to extract from class names if no data attribute
                    if (!productId) {
                        const classes = $item.attr('class') || '';
                        const match = classes.match(/product-(\d+)/);
                        if (match) {
                            productId = match[1];
                        }
                    }
                    
                    // Try to extract from remove button href
                    if (!productId) {
                        const $removeBtn = $item.find('.remove, .wc-block-cart-item__remove-link');
                        if ($removeBtn.length) {
                            const href = $removeBtn.attr('href') || '';
                            const match = href.match(/remove_item=([^&]+)/);
                            if (match) {
                                productId = match[1];
                            }
                        }
                    }
                    
                    if (productId) {
                        product_ids.push(productId.toString());
                    }
                });
            });
            
            return this.uniqueArray(product_ids);
        }

        /**
         * Collect comprehensive cart data
         */
        collectCartData() {
            const cartData = {
                items: [],
                subtotal: 0,
                tax: 0,
                shipping: 0,
                total: 0
            };
            
            // Use a Set to track unique products and avoid duplicates
            const processedProducts = new Set();
            
            // Collect individual cart items
            const itemSelectors = [
                '.cart_item',
                '.wc-block-cart-items__row',
                'tr.cart_item'
            ];
            
            itemSelectors.forEach(selector => {
                $(selector).each(function() {
                    const $item = $(this);
                    
                    // Get product name
                    let productName = '';
                    const nameSelectors = [
                        '.wc-block-cart-item__product-name',
                        '.product-name a',
                        '.product-name',
                        'td:nth-child(2) a',
                        'td:nth-child(2)'
                    ];
                    
                    nameSelectors.forEach(nameSelector => {
                        if (!productName) {
                            const $nameEl = $item.find(nameSelector);
                            if ($nameEl.length) {
                                productName = $nameEl.text().trim();
                                productName = productName.replace(/×\s*\d+/g, '').trim();
                            }
                        }
                    });
                    
                    // Get quantity
                    let quantity = 1;
                    const $qtyInput = $item.find('input[type="number"], .wc-block-components-quantity-selector__input');
                    if ($qtyInput.length) {
                        quantity = parseInt($qtyInput.val()) || 1;
                    } else {
                        // Try to extract from quantity display
                        const qtyText = $item.find('.quantity, .wc-block-cart-item__quantity').text();
                        const qtyMatch = qtyText.match(/(\d+)/);
                        if (qtyMatch) {
                            quantity = parseInt(qtyMatch[1]) || 1;
                        }
                    }
                    
                    // Get price
                    let price = 0;
                    const priceSelectors = [
                        '.wc-block-cart-item__total .woocommerce-Price-amount',
                        '.product-price .woocommerce-Price-amount',
                        '.amount',
                        '.woocommerce-Price-amount'
                    ];
                    
                    priceSelectors.forEach(priceSelector => {
                        if (price === 0) {
                            const $priceEl = $item.find(priceSelector);
                            if ($priceEl.length) {
                                const priceText = $priceEl.text().replace(/[^\d.,]/g, '');
                                price = parseFloat(priceText.replace(',', '.')) || 0;
                            }
                        }
                    });
                    
                    // Get product ID
                    let productId = $item.attr('data-product_id') || 
                                   $item.attr('data-product-id') || 
                                   $item.data('product_id') || 
                                   $item.data('product-id') || '';
                    
                    // Create unique key to avoid duplicates
                    const uniqueKey = `${productName}_${productId}_${quantity}`;
                    
                    if (productName && !processedProducts.has(uniqueKey)) {
                        processedProducts.add(uniqueKey);
                        
                        cartData.items.push({
                            product_id: productId,
                            name: productName,
                            quantity: quantity,
                            price: price,
                            total: price * quantity
                        });
                        
                        cartData.subtotal += (price * quantity);
                    }
                });
            });
            
            // Try to get totals from cart totals section
            const totalSelectors = [
                '.cart-subtotal .woocommerce-Price-amount',
                '.wc-block-cart__totals-subtotal .woocommerce-Price-amount',
                '.order-total .woocommerce-Price-amount',
                '.wc-block-cart__totals-footer .wc-block-cart__totals-footer-item .woocommerce-Price-amount'
            ];
            
            totalSelectors.forEach(selector => {
                const $totalEl = $(selector).last(); // Get the final total
                if ($totalEl.length && cartData.total === 0) {
                    const totalText = $totalEl.text().replace(/[^\d.,]/g, '');
                    cartData.total = parseFloat(totalText.replace(',', '.')) || cartData.subtotal;
                }
            });
            
            // If no total found, use subtotal
            if (cartData.total === 0) {
                cartData.total = cartData.subtotal;
            }
            
            return cartData;
        }

        /**
         * Calculate total amount from cart
         */
        calculateTotalAmount() {
            // Try to get total from various selectors
            const totalSelectors = [
                '.order-total .woocommerce-Price-amount',
                '.wc-block-cart__totals-footer .wc-block-cart__totals-footer-item .woocommerce-Price-amount',
                '.cart-subtotal .woocommerce-Price-amount',
                '.wc-block-cart__totals-subtotal .woocommerce-Price-amount',
                '.woocommerce-checkout-review-order-table .order-total .woocommerce-Price-amount'
            ];
            
            for (const selector of totalSelectors) {
                const $totalEl = $(selector).last();
                if ($totalEl.length) {
                    const totalText = $totalEl.text().replace(/[^\d.,]/g, '');
                    const total = parseFloat(totalText.replace(',', '.'));
                    if (total > 0) {
                        return total;
                    }
                }
            }
            
            // Fallback: calculate from cart data
            const cartData = this.collectCartData();
            return cartData.total || 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);
        }
        
    }

    // Initialize when DOM is ready
    $(document).ready(function() {
        // console.log('[WPNTS] 🚀 Enhanced checkout tracking DISABLED - Backend handles all cart tracking');
        
        // COMPLETELY DISABLED: All cart tracking is now handled by the backend CartAbandonmentTracker
        // through proper WooCommerce hooks. No need for frontend tracking or initialization.
        
        // Don't even create the tracker object to avoid any interference
        return;
    });

})(jQuery);