(function($) {
    'use strict';
    
    class ProductCompareKav {
        constructor() {
            this.init();
        }
        
        init() {
            this.bindEvents();
            this.loadCompareData();
        }
        
        bindEvents() {
            // Compare button click (original)
            $(document).on('click', '.compare-kav-btn', this.handleCompareButton.bind(this));
            
            // Compare button click (new shortcode buttons)
            $(document).on('click', '.compare-button', this.handleNewCompareButton.bind(this));
            
            // Remove from compare
            $(document).on('click', '.compare-kav__compares__item .remove', this.handleRemoveFromCompare.bind(this));
            
            // Add product from modal
            $(document).on('click', '.compare-kav__modal__compares__products .compare-kav__btn', this.handleAddFromModal.bind(this));
            
            // Search products
            $(document).on('input', '#compare-kav-modal input[name="Search"]', this.handleSearch.bind(this));
            
            // Modal events
            $(document).on('click', '[data-compare-kav-open]', this.openModal.bind(this));
            $(document).on('click', '[data-compare-kav-close]', this.closeModal.bind(this));
        }
        
        handleCompareButton(e) {
            e.preventDefault();
            const $button = $(e.currentTarget);
            const productId = $button.data('product-id');
            const isActive = $button.hasClass('active');
            
            if (isActive) {
                this.removeFromCompare(productId, $button);
            } else {
                this.addToCompare(productId, $button);
            }
        }
        
        handleNewCompareButton(e) {
            e.preventDefault();
            const $button = $(e.currentTarget);
            const productId = $button.data('product-id');
            const isRemove = $button.hasClass('remove-from-compare');
            
            if (isRemove) {
                this.removeFromCompare(productId, $button);
            } else {
                // Always redirect to the automatically created compare page
                const comparePageUrl = compareKav.compare_page_url || '';
                this.addToCompareWithRedirect(productId, $button, comparePageUrl);
            }
        }
        
        addToCompare(productId, $button) {
            $.ajax({
                url: compareKav.ajax_url,
                type: 'POST',
                data: {
                    action: 'add_to_compare',
                    product_id: productId,
                    nonce: compareKav.nonce
                },
                success: (response) => {
                    if (response.success) {
                        $button.addClass('active');
                        const buttonText = $button.text().trim();
                        if (!buttonText.includes(compareKav.texts.added_to_compare)) {
                            $button.html($button.find('svg')[0].outerHTML + ' ' + compareKav.texts.added_to_compare);
                        }
                        this.updateCompareDisplay();
                        this.showNotification(response.data.message, 'success');
                    } else {
                        this.showNotification(response.data.message, 'error');
                    }
                },
                error: () => {
                    this.showNotification(compareKav.texts.error, 'error');
                }
            });
        }
        
        addToCompareWithRedirect(productId, $button, redirectUrl) {
            $.ajax({
                url: compareKav.ajax_url,
                type: 'POST',
                data: {
                    action: 'add_to_compare',
                    product_id: productId,
                    nonce: compareKav.nonce
                },
                success: (response) => {
                    if (response.success) {
                        // Update button state
                        $button.removeClass('add-to-compare').addClass('remove-from-compare');
                        
                        // Update button text if it has text
                        const $textSpan = $button.find('span');
                        if ($textSpan.length > 0) {
                            $textSpan.text(compareKav.texts.remove_from_compare || 'Remove from compare');
                        }
                        
                        this.updateCompareDisplay();
                        
                        // Redirect if URL is provided
                        if (redirectUrl && redirectUrl.trim() !== '') {
                            // Small delay to ensure the AJAX request completes
                            setTimeout(() => {
                                window.location.href = redirectUrl;
                            }, 100);
                        } else {
                            this.showNotification(response.data.message, 'success');
                        }
                    } else {
                        this.showNotification(response.data.message, 'error');
                    }
                },
                error: () => {
                    this.showNotification(compareKav.texts.error, 'error');
                }
            });
        }
        
        removeFromCompare(productId, $button) {
            $.ajax({
                url: compareKav.ajax_url,
                type: 'POST',
                data: {
                    action: 'remove_from_compare',
                    product_id: productId,
                    nonce: compareKav.nonce
                },
                success: (response) => {
                    if (response.success) {
                        if ($button) {
                            $button.removeClass('active');
                            $button.html($button.find('svg')[0].outerHTML + ' ' + (compareKav.texts.add_to_compare || 'Add to compare'));
                        }
                        this.updateCompareDisplay();
                        this.showNotification(response.data.message, 'success');
                    }
                },
                error: () => {
                    this.showNotification(compareKav.texts.error, 'error');
                }
            });
        }
        
        handleRemoveFromCompare(e) {
            e.preventDefault();
            const $item = $(e.currentTarget).closest('.compare-kav__compares__item');
            const productId = $item.data('product-id');
            
            // Add loading state
            $item.addClass('removing');
            
            $.ajax({
                url: compareKav.ajax_url,
                type: 'POST',
                data: {
                    action: 'remove_from_compare',
                    product_id: productId,
                    nonce: compareKav.nonce
                },
                success: (response) => {
                    if (response.success) {
                        this.updateCompareDisplay();
                        this.showNotification(response.data.message, 'success');
                    } else {
                        this.showNotification(response.data.message, 'error');
                        $item.removeClass('removing');
                    }
                },
                error: () => {
                    this.showNotification(compareKav.texts.error, 'error');
                    $item.removeClass('removing');
                }
            });
        }
        
        handleAddFromModal(e) {
            e.preventDefault();
            const $button = $(e.currentTarget);
            const productId = $button.data('product-id');
            
            // Add loading state
            $button.prop('disabled', true).text(compareKav.texts.adding_to_compare || 'Adding to compare...');
            
            $.ajax({
                url: compareKav.ajax_url,
                type: 'POST',
                data: {
                    action: 'add_to_compare',
                    product_id: productId,
                    nonce: compareKav.nonce
                },
                success: (response) => {
                    if (response.success) {
                        this.updateCompareDisplay();
                        this.closeModal();
                        this.showNotification(response.data.message, 'success');
                    } else {
                        this.showNotification(response.data.message, 'error');
                    }
                },
                error: () => {
                    this.showNotification(compareKav.texts.error, 'error');
                },
                complete: () => {
                    $button.prop('disabled', false).text(compareKav.texts.add_to_compare || 'Add to compare');
                }
            });
        }
        
        handleSearch(e) {
            const searchTerm = $(e.target).val().trim();
            
            if (searchTerm.length < 2) {
                // Clear results if search term is too short
                $('.compare-kav__modal__compares__products').html('<li class="no-results" style="width: 100%; text-align: center; padding: 40px;">' + (compareKav.texts.search_placeholder || 'Search products...') + '</li>');
                return;
            }
            
            clearTimeout(this.searchTimeout);
            this.searchTimeout = setTimeout(() => {
                this.searchProducts(searchTerm);
            }, 300);
        }
        
        searchProducts(searchTerm) {
            // Show loading state
            $('.compare-kav__modal__compares__products').html('<li class="loading" style="width: 100%; text-align: center; padding: 40px;">' + (compareKav.texts.searching || 'Searching...') + '</li>');
            
            $.ajax({
                url: compareKav.ajax_url,
                type: 'POST',
                data: {
                    action: 'search_products',
                    search_term: searchTerm,
                    nonce: compareKav.nonce
                },
                success: (response) => {
                    if (response.success) {
                        this.renderSearchResults(response.data);
                    } else {
                        $('.compare-kav__modal__compares__products').html('<li class="error" style="width: 100%; text-align: center; padding: 40px;">' + (compareKav.texts.search_error || 'Search error') + '</li>');
                    }
                },
                error: () => {
                    $('.compare-kav__modal__compares__products').html('<li class="error" style="width: 100%; text-align: center; padding: 40px;">' + (compareKav.texts.connection_error || 'Connection error') + '</li>');
                }
            });
        }
        
        renderSearchResults(products) {
            const $container = $('.compare-kav__modal__compares__products');
            $container.empty();
            
            if (!products || products.length === 0) {
                $container.html('<li class="no-results" style="width: 100%; text-align: center; padding: 40px;">' + (compareKav.texts.no_products_found || 'No products found') + '</li>');
                return;
            }
            
            products.forEach(product => {
                const imageUrl = product.image || '';
                const noImageText = compareKav.texts.no_image || 'No Image';
                const selectProductText = compareKav.texts.select_product || 'Select Product';
                const $item = $(`
                    <li class="compare-kav__flex compare-kav__items-center compare-kav__justify-center">
                        ${imageUrl ? `<img src="${imageUrl}" alt="${product.title}" width="140" height="140">` : `<div style="width: 140px; height: 140px; background: #f0f0f0; display: flex; align-items: center; justify-content: center;">${noImageText}</div>`}
                        <div class="content compare-kav__flex compare-kav__items-center compare-kav__justify-center">
                            <div class="title">${product.title}</div>
                            <button type="button" class="compare-kav__btn compare-kav__btn__outline__primary compare-kav__flex compare-kav__items-center compare-kav__justify-center" data-product-id="${product.id}">${selectProductText}</button>
                        </div>
                    </li>
                `);
                $container.append($item);
            });
        }
        
        loadCompareData() {
            $.ajax({
                url: compareKav.ajax_url,
                type: 'POST',
                data: {
                    action: 'get_compare_products',
                    nonce: compareKav.nonce
                },
                success: (response) => {
                    if (response.success) {
                        this.renderCompareTable(response.data);
                    }
                }
            });
        }
        
        updateCompareDisplay() {
            this.loadCompareData();
        }
        
        renderCompareTable(products) {
            const $container = $('#compares');
            $container.find('.compare-kav__compares__item').remove();
            
            if (products.length === 0) {
                // Show empty state message
                return;
            }
            
            // Get all unique attributes
            const allAttributes = new Set();
            products.forEach(product => {
                Object.keys(product.attributes).forEach(attr => {
                    allAttributes.add(attr);
                });
            });
            
            const attributesList = Array.from(allAttributes);
            
            products.forEach((product, index) => {
                const $item = this.createProductCompareItem(product, attributesList, index === 0);
                $container.find('.compare-kav__compares__add__product').before($item);
            });
            
            // Trigger resize to recalculate widths
            setTimeout(() => {
                $(window).trigger('resize');
            }, 100);
        }
        
        createProductCompareItem(product, attributesList, showLabels = false) {
            const rating = parseFloat(product.rating) || 0;
            
            let attributesHtml = '';
            attributesList.forEach(attrName => {
                const value = product.attributes[attrName] || '-';
                attributesHtml += `
                    <div class="label compare-kav__relative">${showLabels ? attrName : '&nbsp;'}</div>
                    <div class="value">${value}</div>
                `;
            });
            
            // Handle image with fallback
            const noImageText = compareKav.texts.no_image || 'No Image';
            const imageHtml = product.image ? 
                `<img src="${product.image}" alt="${product.title}" width="150" height="150">` :
                `<div class="no-image" style="width: 150px; height: 150px; background: #f5f5f5; display: flex; align-items: center; justify-content: center; border-radius: 8px;">${noImageText}</div>`;
            
            // Handle price display - use the formatted price HTML from WooCommerce
            const priceHtml = product.price || '';
            
            return $(`
                <div class="compare-kav__compares__item compare-kav__relative" data-product-id="${product.id}">
                    <div class="compare-kav__compares__item__product">
                        <button type="button" class="remove compare-kav__absolute">
                            <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="none" viewBox="0 0 24 24">
                                <path fill="#E5E8F3" stroke="#E5E8F3" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M12 22c5.5 0 10-4.5 10-10S17.5 2 12 2 2 6.5 2 12s4.5 10 10 10Z"/>
                                <path stroke="#9397AF" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="m9.17 14.83 5.66-5.66m0 5.66L9.17 9.17"/>
                            </svg>
                        </button>
                        ${imageHtml}
                        <h2 class="title">${product.title}</h2>
                        <div class="compare-kav__flex compare-kav__items-center compare-kav__justify-between">
                            <ul class="sizes compare-kav__flex">
                                <li>${compareKav.texts.product || 'Product'}</li>
                            </ul>
                            <div class="rate compare-kav__flex">
                                ${rating.toFixed(1)}
                                <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="none" viewBox="0 0 16 16">
                                    <path fill="currentColor" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" d="m9.153 2.34 1.174 2.347c.16.326.586.64.946.7l2.127.353c1.36.227 1.68 1.213.7 2.187L12.447 9.58c-.28.28-.434.82-.347 1.207l.473 2.046c.374 1.62-.486 2.247-1.92 1.4l-1.993-1.18c-.36-.213-.953-.213-1.32 0l-1.993 1.18c-1.427.847-2.294.214-1.92-1.4l.473-2.046c.087-.387-.067-.927-.347-1.207L1.9 7.927c-.973-.974-.66-1.96.7-2.187l2.127-.353c.353-.06.78-.374.94-.7L6.84 2.34c.64-1.273 1.68-1.273 2.313 0Z"/>
                                </svg>
                            </div>
                        </div>
                        <div class="price-view compare-kav__flex compare-kav__items-center compare-kav__justify-between">
                            <div class="price">
                                ${priceHtml}
                            </div>
                            <a href="${product.url}" class="compare-kav__btn compare-kav__btn__primary compare-kav__flex compare-kav__items-center compare-kav__justify-center">${compareKav.texts.view_and_buy || 'View and Buy'}</a>
                        </div>
                    </div>
                    <div class="total-info compare-kav__flex">
                        ${attributesHtml}
                    </div>
                </div>
            `);
        }
        
        openModal(e) {
            e.preventDefault();
            const target = $(e.currentTarget).data('compare-kav-open');
            const $modal = $(target);
            
            if ($modal.length) {
                $modal.addClass('open');
                $('html').addClass('compare-kav-overflow-hidden');
                
                // Load initial products
                this.searchProducts('');
            }
        }
        
        closeModal(e) {
            if (e) {
                e.preventDefault();
            }
            
            $('.compare-kav__modal').removeClass('open');
            $('html').removeClass('compare-kav-overflow-hidden');
        }
        
        showNotification(message, type = 'success') {
            // Remove any existing notifications
            $('.compare-kav-notification').remove();
            
            // Create notification element
            const $notification = $(`
                <div class="compare-kav-notification compare-kav-notification--${type}">
                    ${message}
                </div>
            `);
            
            // Add to body
            $('body').append($notification);
            
            // Show notification
            setTimeout(() => {
                $notification.addClass('show');
            }, 100);
            
            // Hide notification after 3 seconds
            setTimeout(() => {
                $notification.removeClass('show');
                setTimeout(() => {
                    $notification.remove();
                }, 300);
            }, 3000);
        }
    }
    
    // Initialize when document is ready
    $(document).ready(function() {
        new ProductCompareKav();
    });
    
})(jQuery);