/**
 * GGM Commerce Product Comparison JavaScript
 *
 * Handles product comparison functionality - selecting products to compare,
 * managing the floating comparison bar, and navigating to comparison page.
 *
 * @package GGM_Commerce
 */

jQuery(document).ready(function($) {
    'use strict';

    // Prevent multiple initializations
    if (window.ggmCommerceCompareInitialized) {
        return;
    }
    window.ggmCommerceCompareInitialized = true;

    // Configuration from localized script
    var config = window.ggmCommerceCompare || {};
    var ajaxUrl = config.ajax_url || '';
    var nonce = config.nonce || '';
    var maxProducts = config.max_products || 7;
    var comparePageUrl = config.compare_page_url || '';
    var i18n = config.i18n || {};

    // Floating bar visibility from global settings
    // wp_localize_script passes '1' for enabled, '0' or '' for disabled
    var showFloatingBar = config.show_floating_bar === '1' || config.show_floating_bar === true;

    // Cache for comparison product IDs
    var compareCache = {
        productIds: [],
        count: 0,
        loaded: false
    };

    // Floating bar element
    var $floatingBar = null;

    /**
     * Initialize comparison - load current state and update buttons
     */
    function initComparison() {
        // Load comparison state from cookie for immediate UI
        var cookieCompare = getCompareFromCookie();
        if (cookieCompare.length > 0) {
            compareCache.productIds = cookieCompare;
            compareCache.count = cookieCompare.length;
            updateAllCompareButtons();
            updateFloatingBar();
        }

        // Load from server (will sync cookie if user is logged in)
        loadCompareState();

        // Create floating bar
        createFloatingBar();
    }

    /**
     * Get comparison list from cookie
     */
    function getCompareFromCookie() {
        var cookieValue = getCookie('ggmc_compare');
        if (cookieValue) {
            try {
                // Try parsing directly first (PHP sets raw JSON)
                var parsed = JSON.parse(cookieValue);
                if (Array.isArray(parsed)) {
                    return parsed.map(function(id) { return parseInt(id, 10); });
                }
            } catch (e) {
                // Try with URL decoding as fallback
                try {
                    var decoded = JSON.parse(decodeURIComponent(cookieValue));
                    if (Array.isArray(decoded)) {
                        return decoded.map(function(id) { return parseInt(id, 10); });
                    }
                } catch (e2) {
                    // Invalid cookie data
                }
            }
        }
        return [];
    }

    /**
     * Get cookie value by name
     */
    function getCookie(name) {
        var value = '; ' + document.cookie;
        var parts = value.split('; ' + name + '=');
        if (parts.length === 2) {
            return parts.pop().split(';').shift();
        }
        return null;
    }

    /**
     * Load comparison state from server
     */
    function loadCompareState() {
        $.ajax({
            url: ajaxUrl,
            type: 'POST',
            data: {
                action: 'ggmc_compare_get',
                nonce: nonce
            },
            success: function(response) {
                if (response.success && response.data) {
                    compareCache.productIds = response.data.product_ids || [];
                    compareCache.count = response.data.count || 0;
                    compareCache.loaded = true;
                    updateAllCompareButtons();
                    updateFloatingBar();
                }
            }
        });
    }

    /**
     * Create the floating comparison bar
     */
    function createFloatingBar() {
        // Skip if floating bar is disabled in settings
        if (!showFloatingBar) {
            return;
        }

        // Only create if not already exists
        if ($('#ggmc-compare-bar').length) {
            $floatingBar = $('#ggmc-compare-bar');
            return;
        }

        var html = '<div id="ggmc-compare-bar" class="ggmc-compare-bar">' +
                       '<div class="ggmc-compare-bar-inner">' +
                           '<div class="ggmc-compare-bar-info">' +
                               '<span class="ggmc-compare-icon">' +
                                   '<i class="eicon-exchange" aria-hidden="true"></i>' +
                               '</span>' +
                               '<span class="ggmc-compare-text">' +
                                   '<span class="ggmc-compare-count">0</span> ' +
                                   '<span class="ggmc-compare-of">' + (i18n.of || 'of') + '</span> ' +
                                   '<span class="ggmc-compare-max">' + maxProducts + '</span> ' +
                                   '<span class="ggmc-compare-label">' + (i18n.products_selected || 'products selected') + '</span>' +
                               '</span>' +
                           '</div>' +
                           '<div class="ggmc-compare-bar-actions">' +
                               '<a href="' + comparePageUrl + '" class="ggmc-compare-bar-btn ggmc-compare-now-btn">' +
                                   (i18n.compare_now || 'Compare Now') +
                               '</a>' +
                               '<button type="button" class="ggmc-compare-bar-btn ggmc-compare-clear-btn">' +
                                   (i18n.clear_all || 'Clear All') +
                               '</button>' +
                           '</div>' +
                       '</div>' +
                   '</div>';

        $('body').append(html);
        $floatingBar = $('#ggmc-compare-bar');

        // Note: Clear button handler is bound via document delegation at line 577
        // to avoid duplicate handlers

        // Update visibility
        updateFloatingBar();
    }

    /**
     * Update floating bar visibility and content
     */
    function updateFloatingBar() {
        if ($floatingBar) {
            $floatingBar.find('.ggmc-compare-count').text(compareCache.count);

            if (compareCache.count > 0) {
                $floatingBar.addClass('visible');
            } else {
                $floatingBar.removeClass('visible');
            }

            // Update compare now button state
            var $compareBtn = $floatingBar.find('.ggmc-compare-now-btn');
            if (compareCache.count < 2) {
                $compareBtn.addClass('disabled').attr('title', i18n.need_at_least_two || 'Select at least 2 products to compare');
            } else {
                $compareBtn.removeClass('disabled').attr('title', '');
            }
        }

        // Update any Compare Icon widgets on the page
        updateCompareIconWidgets();
    }

    /**
     * Update all Compare Icon widgets on the page
     */
    function updateCompareIconWidgets() {
        $('.ggmc-compare-icon[data-compare-icon]').each(function() {
            var $icon = $(this);
            var $badge = $icon.find('.ggmc-compare-count-badge');

            if ($badge.length) {
                $badge.text(compareCache.count);

                if (compareCache.count > 0) {
                    $badge.show();
                } else {
                    $badge.hide();
                }
            }
        });
    }

    /**
     * Toggle comparison item (add if not present, remove if present)
     */
    function toggleCompareItem($button, productId) {
        var isInCompare = compareCache.productIds.indexOf(productId) !== -1;

        // Check max limit before adding
        if (!isInCompare && compareCache.count >= maxProducts) {
            showCompareMessage(
                (i18n.max_reached || 'Maximum of {max} products can be compared').replace('{max}', maxProducts),
                'warning'
            );
            return;
        }

        // Optimistic UI update
        $button.addClass('loading');

        $.ajax({
            url: ajaxUrl,
            type: 'POST',
            data: {
                action: 'ggmc_compare_toggle',
                product_id: productId,
                nonce: nonce
            },
            success: function(response) {
                $button.removeClass('loading');

                if (response.success && response.data) {
                    var action = response.data.action;

                    // Update cache
                    if (action === 'added') {
                        if (compareCache.productIds.indexOf(productId) === -1) {
                            compareCache.productIds.push(productId);
                        }
                        showCompareMessage(response.data.message, 'success');
                    } else if (action === 'removed') {
                        var index = compareCache.productIds.indexOf(productId);
                        if (index > -1) {
                            compareCache.productIds.splice(index, 1);
                        }
                        showCompareMessage(response.data.message, 'info');
                    }

                    compareCache.count = response.data.count;

                    // Update all buttons for this product
                    updateCompareButtonsForProduct(productId);
                    updateFloatingBar();

                    // Trigger custom event
                    $(document).trigger('ggmc_compare_updated', {
                        productId: productId,
                        action: action,
                        count: compareCache.count,
                        productIds: compareCache.productIds
                    });
                } else {
                    showCompareMessage(response.data ? response.data.message : 'An error occurred', 'error');
                }
            },
            error: function() {
                $button.removeClass('loading');
                showCompareMessage(i18n.error_occurred || 'An error occurred. Please try again.', 'error');
            }
        });
    }

    /**
     * Add item to comparison
     */
    function addToCompare($button, productId) {
        // Check max limit
        if (compareCache.count >= maxProducts) {
            showCompareMessage(
                (i18n.max_reached || 'Maximum of {max} products can be compared').replace('{max}', maxProducts),
                'warning'
            );
            return;
        }

        $button.addClass('loading');

        $.ajax({
            url: ajaxUrl,
            type: 'POST',
            data: {
                action: 'ggmc_compare_add',
                product_id: productId,
                nonce: nonce
            },
            success: function(response) {
                $button.removeClass('loading');

                if (response.success && response.data) {
                    if (compareCache.productIds.indexOf(productId) === -1) {
                        compareCache.productIds.push(productId);
                    }
                    compareCache.count = response.data.count;

                    updateCompareButtonsForProduct(productId);
                    updateFloatingBar();
                    showCompareMessage(response.data.message, 'success');

                    $(document).trigger('ggmc_compare_updated', {
                        productId: productId,
                        action: 'added',
                        count: compareCache.count,
                        productIds: compareCache.productIds
                    });
                } else {
                    showCompareMessage(response.data ? response.data.message : 'Failed to add to comparison', 'error');
                }
            },
            error: function() {
                $button.removeClass('loading');
                showCompareMessage(i18n.error_occurred || 'An error occurred. Please try again.', 'error');
            }
        });
    }

    /**
     * Remove item from comparison
     */
    function removeFromCompare($button, productId) {
        $button.addClass('loading');

        $.ajax({
            url: ajaxUrl,
            type: 'POST',
            data: {
                action: 'ggmc_compare_remove',
                product_id: productId,
                nonce: nonce
            },
            success: function(response) {
                $button.removeClass('loading');

                if (response.success && response.data) {
                    var index = compareCache.productIds.indexOf(productId);
                    if (index > -1) {
                        compareCache.productIds.splice(index, 1);
                    }
                    compareCache.count = response.data.count;

                    updateCompareButtonsForProduct(productId);
                    updateFloatingBar();
                    showCompareMessage(response.data.message, 'info');

                    $(document).trigger('ggmc_compare_updated', {
                        productId: productId,
                        action: 'removed',
                        count: compareCache.count,
                        productIds: compareCache.productIds
                    });
                } else {
                    showCompareMessage(response.data ? response.data.message : 'Failed to remove from comparison', 'error');
                }
            },
            error: function() {
                $button.removeClass('loading');
                showCompareMessage(i18n.error_occurred || 'An error occurred. Please try again.', 'error');
            }
        });
    }

    /**
     * Clear all comparison items
     */
    function clearAllCompare() {
        $.ajax({
            url: ajaxUrl,
            type: 'POST',
            data: {
                action: 'ggmc_compare_clear',
                nonce: nonce
            },
            success: function(response) {
                if (response.success) {
                    compareCache.productIds = [];
                    compareCache.count = 0;

                    updateAllCompareButtons();
                    updateFloatingBar();
                    showCompareMessage(response.data.message, 'info');

                    $(document).trigger('ggmc_compare_updated', {
                        action: 'cleared',
                        count: 0,
                        productIds: []
                    });

                    // If on comparison page, reload to show empty state
                    if (window.location.href.indexOf(comparePageUrl) !== -1) {
                        setTimeout(function() {
                            location.reload();
                        }, 1000);
                    }
                }
            },
            error: function() {
                showCompareMessage(i18n.error_occurred || 'An error occurred. Please try again.', 'error');
            }
        });
    }

    /**
     * Update all compare buttons on the page
     */
    function updateAllCompareButtons() {
        $('.compare-btn').each(function() {
            var $button = $(this);
            var productId = parseInt($button.data('product-id'), 10);
            updateButtonState($button, productId);
        });
    }

    /**
     * Update compare buttons for a specific product
     */
    function updateCompareButtonsForProduct(productId) {
        $('.compare-btn[data-product-id="' + productId + '"]').each(function() {
            updateButtonState($(this), productId);
        });
    }

    /**
     * Update button state based on comparison status
     */
    function updateButtonState($button, productId) {
        var isInCompare = compareCache.productIds.indexOf(productId) !== -1;

        if (isInCompare) {
            $button.addClass('in-compare');
            $button.attr('title', i18n.remove_from_compare || 'Remove from comparison');
            // Update icon if using exchange icons
            $button.find('.eicon-exchange').addClass('active');
        } else {
            $button.removeClass('in-compare');
            $button.attr('title', i18n.add_to_compare || 'Add to comparison');
            $button.find('.eicon-exchange').removeClass('active');
        }
    }

    /**
     * Show comparison notification message
     */
    function showCompareMessage(message, type) {
        // Get notification settings from localized config
        // Try ggmCommerceCompare.notifications first (product comparison script), then ggmCommerceAjax.notifications (cart script)
        var notifyConfig = (config.notifications)
            ? config.notifications
            : (typeof ggmCommerceAjax !== 'undefined' && ggmCommerceAjax.notifications)
                ? ggmCommerceAjax.notifications
                : { enabled: '1', position: 'top-right', duration: 3000 };

        // Check if notifications are enabled
        if (notifyConfig.enabled === '0') {
            return;
        }

        type = type || 'info';

        // Remove any existing messages
        $('.ggmc-compare-message').remove();

        // Create message element
        var iconClass = 'eicon-info-circle';
        if (type === 'success') iconClass = 'eicon-check-circle';
        if (type === 'warning') iconClass = 'eicon-warning';
        if (type === 'error') iconClass = 'eicon-close-circle';

        // Build position class
        var positionClass = 'position-' + (notifyConfig.position || 'top-right');

        var $message = $('<div class="ggmc-compare-message ggmc-compare-message-' + type + ' ' + positionClass + '">' +
            '<span class="message-icon"><i class="' + iconClass + '"></i></span>' +
            '<span class="message-text">' + message + '</span>' +
            '<button type="button" class="message-close">&times;</button>' +
            '</div>');

        // Add to page
        $('body').append($message);

        // Animate in
        setTimeout(function() {
            $message.addClass('visible');
        }, 10);

        // Auto-remove after configured duration
        var duration = parseInt(notifyConfig.duration, 10) || 3000;
        setTimeout(function() {
            $message.removeClass('visible');
            setTimeout(function() {
                $message.remove();
            }, 300);
        }, duration);

        // Close button handler
        $message.find('.message-close').on('click', function() {
            $message.removeClass('visible');
            setTimeout(function() {
                $message.remove();
            }, 300);
        });
    }

    /**
     * Event handler for compare button clicks
     */
    $(document).on('click', '.compare-btn', function(e) {
        e.preventDefault();
        e.stopPropagation();

        var $button = $(this);
        var productId = parseInt($button.data('product-id'), 10);

        if (!productId) {
            return;
        }

        // Prevent double-clicks
        if ($button.hasClass('loading')) {
            return;
        }

        toggleCompareItem($button, productId);
    });

    /**
     * Event handler for explicit add-to-compare buttons
     */
    $(document).on('click', '.ggmc-add-to-compare', function(e) {
        e.preventDefault();
        e.stopPropagation();

        var $button = $(this);
        var productId = parseInt($button.data('product-id'), 10);

        if (!productId || $button.hasClass('loading')) {
            return;
        }

        addToCompare($button, productId);
    });

    /**
     * Event handler for explicit remove-from-compare buttons
     */
    $(document).on('click', '.ggmc-remove-from-compare', function(e) {
        e.preventDefault();
        e.stopPropagation();

        var $button = $(this);
        var productId = parseInt($button.data('product-id'), 10);

        if (!productId || $button.hasClass('loading')) {
            return;
        }

        // If inside a comparison widget item, animate removal
        var $compareItem = $button.closest('.ggmc-compare-product');
        if ($compareItem.length) {
            $compareItem.css('opacity', '0.5');
        }

        removeFromCompare($button, productId);
    });

    /**
     * Event handler for clear all button (on comparison page)
     */
    $(document).on('click', '.ggmc-compare-clear-btn', function(e) {
        e.preventDefault();
        e.stopPropagation();
        clearAllCompare();
    });

    /**
     * Listen for compare updates and refresh widget display
     */
    $(document).on('ggmc_compare_updated', function(e, data) {
        if (data.action === 'removed') {
            // Remove the item from comparison widget display
            $('.ggmc-compare-product[data-product-id="' + data.productId + '"]').fadeOut(300, function() {
                $(this).remove();

                // Check if comparison is now empty
                if (data.count === 0) {
                    // Reload to show empty state
                    setTimeout(function() {
                        location.reload();
                    }, 500);
                }
            });
        }
    });

    /**
     * Expose comparison functions globally for use by other scripts/widgets
     */
    window.ggmCommerceCompare = {
        isInCompare: function(productId) {
            return compareCache.productIds.indexOf(parseInt(productId, 10)) !== -1;
        },
        getCount: function() {
            return compareCache.count;
        },
        getMaxProducts: function() {
            return maxProducts;
        },
        getProductIds: function() {
            return compareCache.productIds.slice(); // Return a copy
        },
        refresh: function() {
            loadCompareState();
        },
        add: function(productId) {
            var $dummyButton = $('<div>');
            addToCompare($dummyButton, parseInt(productId, 10));
        },
        remove: function(productId) {
            var $dummyButton = $('<div>');
            removeFromCompare($dummyButton, parseInt(productId, 10));
        },
        toggle: function(productId) {
            var $dummyButton = $('<div>');
            toggleCompareItem($dummyButton, parseInt(productId, 10));
        },
        clear: function() {
            clearAllCompare();
        },
        goToComparePage: function() {
            if (comparePageUrl) {
                window.location.href = comparePageUrl;
            }
        }
    };

    // Initialize on page load
    initComparison();
});
