(function($) {
    'use strict';

    // WPNTS Checkout Tracker Class
    class WPNTSCheckoutTracker {
        constructor(pageInfo) {
           
            this.sessionKey = this.getSessionKey();
            this.throttleTimer = null;
            this.lastSentData = null;
            this.pageInfo = 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);
                   
                }
                 /* 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);
            }
        }

        /**
         * Remove duplicates from array
         */
        uniqueArray(arr) {
            return Array.from(new Set(arr.filter(Boolean)));
        }

        /**
         * Collect checkout form data
         */
        collectCheckoutData() {
            
            const data = {};

            // Get billing information
            const $email = $("input[name='billing_email'], input#billing_email, input[type='email']").first();
            data.email = $email.length ? $email.val().trim() : '';

            const firstName = $("input[name='billing_first_name'], input#billing_first_name").first().val() || '';
            const lastName = $("input[name='billing_last_name'], input#billing_last_name").first().val() || '';
            data.name = (firstName + ' ' + lastName).trim();

            // Fallback for combined name fields
            if (!data.name) {
                const combined = $("input[name='billing_name'], input#billing_name").first();
                if (combined.length) data.name = combined.val().trim();
            }

            const $phone = $("input[name='billing_phone'], input#billing_phone, input[type='tel']").first();
            data.phone = $phone.length ? $phone.val().trim() : '';

            const addr1 = $("input[name='billing_address_1']").first().val() || '';
            const city = $("input[name='billing_city']").first().val() || '';
            data.address = (addr1 + ' ' + city).trim();

            // Collect product information
            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();

            // More flexible validation - track even with minimal data
            const hasContact = !!(data.email || data.phone || data.name);
            const hasProducts = !!(data.product_names.length > 0 || data.product_ids.length > 0);
            
            // If we have at least an email OR some product info, track it
            if (!data.email && data.product_names.length === 0 && data.product_ids.length === 0) {
               
                return null;
            }
            
        

            // If no products found, try to get from page title or URL
            if (data.product_names.length === 0 && data.product_ids.length === 0) {
               
                // Try to get product info from page context
                const pageTitle = document.title;
                if (pageTitle.includes('Cart') || pageTitle.includes('Checkout')) {
                    // Try to extract from cart/checkout context
                    const cartInfo = this.extractCartInfoFromContext();
                    if (cartInfo.products.length > 0) {
                        data.product_names = cartInfo.products;
                      
                    }
                }
                
                // If still no products and we're on cart page, create a generic entry
                if (data.product_names.length === 0 && this.pageInfo.isCartPage) {
                    // Check if cart appears to have items (even if we can't detect them)
                    const cartNotEmpty = $('.cart-empty, .wc-empty-cart-message').length === 0;
                    if (cartNotEmpty && (data.email || data.name)) {
                        data.product_names = ['Unknown Product (Cart Items)'];
                       
                    }
                }
            }

            data.session_key = this.sessionKey;
          
            return data;
        }

        /**
         * Extract cart info from page context as fallback
         */
        extractCartInfoFromContext() {
            const products = [];
            
            
            // Try to get from any visible product elements
            $('.product, .woocommerce-product').each(function() {
                const productName = $(this).find('h1, h2, h3, .product-title, .entry-title').first().text().trim();
                if (productName) {
                    products.push(productName);
                }
            });
            
            // Try to get from breadcrumbs or navigation
            $('.breadcrumb, .woocommerce-breadcrumb').find('a').each(function() {
                const linkText = $(this).text().trim();
                if (linkText && linkText !== 'Home' && linkText !== 'Shop' && linkText !== 'Cart' && linkText !== 'Checkout') {
                    products.push(linkText);
                }
            });
            
            
            return {
                products: this.uniqueArray(products)
            };
        }

        /**
         * Collect product names from checkout
         */
        collectProductNames() {
            const product_names = [];
            const nameSelectors = [
                '.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',
                '.product-name',
                '.wc-order-review .product-name',
                // Additional selectors for different themes
                '.cart_item td.product-name',
                '.wc-block-cart-items__row .wc-block-cart-item__product .wc-block-cart-item__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 generic 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);
                
                elements.each(function() {
                    const el = $(this).clone();
                    // Remove quantity and other elements
                    el.find('strong, .quantity, .product-quantity, .woocommerce-Price-amount').remove();
                    let txt = el.text().trim();
                    
                    // If no text, try getting from link
                    if (!txt) {
                        txt = $(this).find('a').text().trim();
                    }
                    
                    // Clean up common patterns
                    txt = txt.replace(/×\s*\d+/g, '').trim(); // Remove quantity like "× 2"
                    txt = txt.replace(/\s+/g, ' ').trim(); // Clean up whitespace
                    
                    if (txt && txt.length > 2) {
                        product_names.push(txt);
                    }
                });
            });

            return this.uniqueArray(product_names);
        }

        /**
         * Collect product links from checkout
         */
        collectProductLinks() {
            const links = [];
            const linkSelectors = [
                '.woocommerce-checkout-review-order-table .product-name a',
                '.woocommerce-checkout .product-name a',
                'table.shop_table.cart a.product-name',
                '.cart_item .product-thumbnail a',
                '.cart_item a.product-name',
                '.product-name a',
                '.order_item .product-name a',
                '.wc-order-review .product-name a'
            ];

            linkSelectors.forEach(selector => {
                $(selector).each(function() {
                    const href = $(this).attr('href') || $(this).data('href') || $(this).prop('href');
                    if (href && typeof href === 'string') {
                        const cleanHref = href.trim();
                        // Ignore anchors or JS links
                        if (cleanHref.indexOf('javascript:') === -1 && cleanHref.indexOf('#') !== 0) {
                            links.push(cleanHref);
                        }
                    }
                });
            });

            return this.uniqueArray(links);
        }

        /**
         * Collect product IDs from checkout
         */
        collectProductIds() {
            const product_ids = [];

            // Try to get product IDs from various sources
            const itemSelectors = [
                '.cart_item', 
                '.order_item', 
                'tr.cart_item',
                '.wc-block-cart-items__row',
                '.shop_table tbody tr'
            ];

            itemSelectors.forEach(selector => {
                $(selector).each(function() {
                    // Look for data attributes
                    const productId = $(this).data('product_id') || 
                                    $(this).data('product-id') || 
                                    $(this).attr('data-product_id') ||
                                    $(this).attr('data-product-id');
                    if (productId) {
                        product_ids.push(parseInt(productId));
                    }

                    // Look for hidden inputs
                    const hiddenInput = $(this).find('input[name*="product_id"], input[name*="cart_item_key"], input[type="hidden"]');
                    if (hiddenInput.length) {
                        hiddenInput.each(function() {
                            const value = $(this).val();
                            if (value && !isNaN(value)) {
                                product_ids.push(parseInt(value));
                            }
                        });
                    }

                    // Look for links with product IDs
                    const productLinks = $(this).find('a[href*="product"]');
                    productLinks.each(function() {
                        const href = $(this).attr('href');
                        const match = href.match(/product[\/\-](\d+)/);
                        if (match) {
                            product_ids.push(parseInt(match[1]));
                        }
                    });
                });
            });

            return this.uniqueArray(product_ids);
        }

        /**
         * Collect full cart data
         */
        collectCartData() {
            const cartData = {
                items: [],
                subtotal: 0,
                tax: 0,
                shipping: 0,
                total: 0
            };

            // Collect cart items from multiple possible structures
            const itemSelectors = [
                '.cart_item', 
                '.order_item', 
                'tr.cart_item',
                '.wc-block-cart-items__row',
                '.shop_table tbody tr'
            ];

            itemSelectors.forEach(selector => {
                $(selector).each(function() {
                    const $item = $(this);
                    
                    // Try multiple ways to get product name
                    let product_name = $item.find('.product-name').text().trim() ||
                                     $item.find('td:nth-child(2)').text().trim() ||
                                     $item.find('.wc-block-cart-item__product-name').text().trim() ||
                                     $item.find('a').first().text().trim();
                    
                    // Clean up product name (remove quantity info)
                    product_name = product_name.replace(/\s*×\s*\d+\s*$/, '').trim();
                    
                    // Try multiple ways to get quantity
                    let quantity = parseInt($item.find('.qty').val()) ||
                                 parseInt($item.find('.product-quantity').text()) ||
                                 parseInt($item.find('input[type="number"]').val()) ||
                                 parseInt($item.find('.quantity').text()) ||
                                 1;
                    
                    // Try multiple ways to get price
                    let price = $item.find('.woocommerce-Price-amount').first().text().trim() ||
                              $item.find('.amount').first().text().trim() ||
                              $item.find('.price').first().text().trim();
                    
                    // Get product ID
                    let product_id = $item.data('product_id') || 
                                   $item.data('product-id') || 
                                   $item.attr('data-product_id') ||
                                   0;

                    if (product_name && product_name.length > 0) {
                        cartData.items.push({
                            product_name: product_name,
                            quantity: quantity,
                            price: price,
                            product_id: product_id
                        });
                    }
                });
            });

            // Get totals
            const $orderTotal = $('.order-total .woocommerce-Price-amount');
            if ($orderTotal.length) {
                const totalText = $orderTotal.text().replace(/[^\d.,]/g, '');
                cartData.total = parseFloat(totalText.replace(',', '.')) || 0;
            }

            return cartData;
        }

        /**
         * Calculate total amount
         */
        calculateTotalAmount() {
            // Try multiple selectors for order total
            const totalSelectors = [
                '.order-total .woocommerce-Price-amount',
                '.cart-subtotal .woocommerce-Price-amount',
                '.order_total .amount',
                '#order_total .amount'
            ];

            for (const selector of totalSelectors) {
                const $total = $(selector);
                if ($total.length) {
                    const totalText = $total.text().replace(/[^\d.,]/g, '');
                    const amount = parseFloat(totalText.replace(',', '.'));
                    if (!isNaN(amount) && amount > 0) {
                        return amount;
                    }
                }
            }

            return 0;
        }

        /**
         * Send data to server
         */
        sendToServer() {
            const data = this.collectCheckoutData();
            if (!data) {
                return;
            }

            // Check if data has changed significantly
            if (this.lastSentData && this.dataIsSimilar(data, this.lastSentData)) {
                return;
            }

            const payload = {
                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
            };


            $.ajax({
                url: wpnts_checkout_ajax.ajax_url,
                method: 'POST',
                data: payload,
                dataType: 'json',
                success: (response) => {
                    if (response.success) {
                        this.lastSentData = data;
                        // Store record ID for potential future use
                        try {
                            sessionStorage.setItem('wpnts_record_id', response.data.id);
                        } catch (e) {
                            console.warn('[WPNTS] Could not store record ID in sessionStorage');
                        }
                    } else {
                        console.error('[WPNTS] ❌ Server returned error:', response.data);
                    }
                },
                error: (xhr, status, error) => {
                    console.error('[WPNTS] 🚨 AJAX request failed:', {
                        status: status,
                        error: error,
                        responseText: xhr.responseText,
                        url: wpnts_checkout_ajax.ajax_url
                    });
                }
            });
        }

        /**
         * Check if data is similar to avoid spam
         */
        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
            );
        }

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

        /**
         * Initialize event listeners
         */
        init() {
            // Initial send after page load
            setTimeout(() => {
                this.sendToServer();
            }, 1500);

            // Listen for form changes
            $(document).on('input change', 'form.checkout input, form.checkout textarea, form.checkout select', () => {
                this.throttledSend();
            });

            // WooCommerce checkout updated event
            $(document.body).on('updated_checkout', () => {
                this.throttledSend();
            });

            // Cart quantity changes and removals
            $(document).on('click', '.quantity .plus, .quantity .minus, .remove, .remove-from-cart, .wc-remove-item, .cart_item .remove', () => {
                this.throttledSend();
            });

            // Track cart updates (WooCommerce AJAX)
            $(document.body).on('updated_wc_div', () => {
                this.throttledSend();
            });

            // Track when cart becomes empty
            $(document.body).on('wc_cart_emptied', () => {
                this.sendToServer();
            });

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

            // Shipping method changes
            $(document).on('change', 'input[name^="shipping_method"]', () => {
                this.throttledSend();
            });

            // Track when user leaves the page (potential abandonment)
            $(window).on('beforeunload', () => {
                // Send final data before leaving
                const data = this.collectCheckoutData();
                if (data) {
                    // Use sendBeacon for reliable sending on page unload
                    if (navigator.sendBeacon) {
                        const formData = new FormData();
                        formData.append('action', 'wpnts_save_incomplete_order');
                        formData.append('nonce', wpnts_checkout_ajax.nonce);
                        formData.append('session_key', data.session_key);
                        formData.append('email', data.email);
                        formData.append('name', data.name);
                        formData.append('phone', data.phone);
                        formData.append('address', data.address);
                        formData.append('product_ids', JSON.stringify(data.product_ids || []));
                        formData.append('product_names', JSON.stringify(data.product_names || []));
                        formData.append('product_links', JSON.stringify(data.product_links || []));
                        formData.append('cart_data', JSON.stringify(data.cart_data || {}));
                        formData.append('total_amount', data.total_amount || 0);
                        
                        navigator.sendBeacon(wpnts_checkout_ajax.ajax_url, formData);
                    }
                }
            });

            // Track page visibility changes (tab switching, minimizing)
            if (typeof document.hidden !== 'undefined') {
                $(document).on('visibilitychange', () => {
                    if (document.hidden) {
                        this.sendToServer();
                    }
                });
            }

            // Additional cart-specific events
            if (this.pageInfo.isCartPage) {
                
                // Track "Proceed to Checkout" button clicks
                $(document).on('click', '.checkout-button, .wc-proceed-to-checkout, a[href*="checkout"]', () => {
                    this.sendToServer();
                });
                
                // Track "Continue Shopping" clicks
                $(document).on('click', 'a[href*="shop"], .continue-shopping', () => {
                    this.sendToServer();
                });
            }
        }

       
    }

    // Initialize when DOM is ready
    $(document).ready(function() {
       
        // Initialize on checkout page or cart page with items
        const isCheckoutPage = $('body').hasClass('woocommerce-checkout') || $('.woocommerce-checkout').length;
        const isCartPage = $('body').hasClass('woocommerce-cart') || $('.woocommerce-cart').length;
        
        // More comprehensive cart item detection
        const cartItemSelectors = [
            '.cart_item',
            '.woocommerce-cart-form__cart-item', 
            'tr.cart_item',
            '.wc-block-cart-items__row',
            '.cart-item',
            'tbody tr',
            '.shop_table.cart tbody tr'
        ];
        
        let hasCartItems = false;
        cartItemSelectors.forEach(selector => {
            if ($(selector).length > 0) {
                hasCartItems = true;
            }
        });
        
        // Also check if WooCommerce cart has items via global variables
        if (typeof wc_cart_params !== 'undefined' || typeof woocommerce_params !== 'undefined') {
            hasCartItems = true;
        }
        
        // Check for any product-related elements
        const hasProducts = $('.product, .woocommerce-product, [data-product_id]').length > 0;
        
        
        // More flexible initialization conditions
        if (isCheckoutPage || (isCartPage && (hasCartItems || hasProducts))) {
           
            const pageInfo = {
                isCheckoutPage: isCheckoutPage,
                isCartPage: isCartPage,
                hasCartItems: hasCartItems,
                hasProducts: hasProducts
            };
            const tracker = new WPNTSCheckoutTracker(pageInfo);
            
            // Make tracker globally available for debugging
            window.wpntsTracker = tracker;
        } 
        /* else {
            console.log('[WPNTS] ❌ Conditions not met - Tracking not initialized');
        } */
    });

})(jQuery);