/**
 * GGM Commerce Wishlist JavaScript
 *
 * Handles wishlist button interactions and UI updates.
 * Supports multiple wishlists for logged-in users.
 *
 * @package GGM_Commerce
 */

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

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

    // Cache for wishlist data
    var wishlistCache = {
        // For backwards compatibility - default wishlist product IDs
        productIds: [],
        count: 0,
        loaded: false,
        // Multi-wishlist data
        wishlists: [],
        currentWishlistId: null,
        maxWishlists: 5,
        canCreateMore: true,
        sharingEnabled: false,
        isGuest: true
    };

    // =========================================================================
    // INITIALIZATION
    // =========================================================================

    /**
     * Initialize wishlist - load current state and update buttons
     */
    function initWishlist() {
        // Load wishlist state from server
        loadWishlistState();

        // Also try to load from cookie for immediate UI (guests)
        var cookieWishlist = getWishlistFromCookie();
        if (cookieWishlist.length > 0) {
            wishlistCache.productIds = cookieWishlist;
            wishlistCache.count = cookieWishlist.length;
            updateAllWishlistButtons();
            updateWishlistCountDisplays();
        }

        // Initialize wishlist widget UI if present
        initWishlistWidgetUI();
    }

    /**
     * Initialize wishlist widget UI components
     */
    function initWishlistWidgetUI() {
        // Initialize tabs if present
        initWishlistTabs();

        // Initialize dropdown selector if present
        initWishlistDropdown();

        // Initialize management controls
        initManagementControls();

        // Initialize item selection for move/copy
        initItemSelection();
    }

    // =========================================================================
    // COOKIE HANDLING (for guests)
    // =========================================================================

    /**
     * Get wishlist from cookie (for guests)
     */
    function getWishlistFromCookie() {
        var cookieValue = getCookie('ggmc_wishlist');
        if (cookieValue) {
            try {
                var parsed = JSON.parse(decodeURIComponent(cookieValue));
                if (Array.isArray(parsed)) {
                    return parsed.map(function(id) { return parseInt(id, 10); });
                }
            } catch (e) {
                // 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;
    }

    // =========================================================================
    // DATA LOADING
    // =========================================================================

    /**
     * Load wishlist state from server
     */
    function loadWishlistState() {
        $.ajax({
            url: ggmCommerceAjax.ajax_url,
            type: 'POST',
            data: {
                action: 'ggmc_wishlist_get',
                nonce: ggmCommerceAjax.nonce
            },
            success: function(response) {
                if (response.success && response.data) {
                    wishlistCache.productIds = response.data.product_ids || [];
                    wishlistCache.count = response.data.count || 0;
                    wishlistCache.loaded = true;
                    updateAllWishlistButtons();
                    updateWishlistCountDisplays();
                }
            }
        });

        // Also load all wishlists for logged-in users
        loadAllWishlists();
    }

    /**
     * Load all wishlists for logged-in users
     */
    function loadAllWishlists() {
        $.ajax({
            url: ggmCommerceAjax.ajax_url,
            type: 'POST',
            data: {
                action: 'ggmc_wishlist_get_all',
                nonce: ggmCommerceAjax.nonce
            },
            success: function(response) {
                if (response.success && response.data) {
                    wishlistCache.wishlists = response.data.wishlists || [];
                    wishlistCache.maxWishlists = response.data.max_wishlists || 5;
                    wishlistCache.canCreateMore = response.data.can_create_more !== false;
                    wishlistCache.sharingEnabled = response.data.sharing_enabled === true;
                    wishlistCache.isGuest = wishlistCache.wishlists.length === 0;

                    // Set current wishlist if not set: prefer URL param, then default.
                    if (!wishlistCache.currentWishlistId && wishlistCache.wishlists.length > 0) {
                        var urlWishlistId = null;
                        try {
                            var urlParams = new URLSearchParams(window.location.search);
                            if (urlParams.has('wishlist')) {
                                urlWishlistId = parseInt(urlParams.get('wishlist'), 10);
                            }
                        } catch (e) { /* URLSearchParams not supported */ }

                        // Verify the URL wishlist ID exists in the user's wishlists.
                        var urlMatch = urlWishlistId ? wishlistCache.wishlists.find(function(w) { return w.id === urlWishlistId; }) : null;
                        if (urlMatch) {
                            wishlistCache.currentWishlistId = urlWishlistId;
                        } else {
                            var defaultList = wishlistCache.wishlists.find(function(w) { return w.is_default; });
                            wishlistCache.currentWishlistId = defaultList ? defaultList.id : wishlistCache.wishlists[0].id;
                        }
                    }

                    // Update UI
                    updateWishlistTabs();
                    updateWishlistDropdown();
                    updateManagementControls();

                    // Trigger event for widgets to update
                    $(document).trigger('ggmc_wishlists_loaded', { wishlists: wishlistCache.wishlists });
                }
            }
        });
    }

    /**
     * Load specific wishlist data with products
     */
    function loadWishlistData(wishlistId, callback) {
        $.ajax({
            url: ggmCommerceAjax.ajax_url,
            type: 'POST',
            data: {
                action: 'ggmc_wishlist_get',
                wishlist_id: wishlistId || 0,
                include_products: true,
                nonce: ggmCommerceAjax.nonce
            },
            success: function(response) {
                if (response.success && response.data) {
                    if (callback) {
                        callback(response.data);
                    }
                }
            }
        });
    }

    // =========================================================================
    // ITEM OPERATIONS (Add, Remove, Toggle)
    // =========================================================================

    /**
     * Toggle wishlist item (add if not in wishlist, remove if in wishlist)
     */
    function toggleWishlistItem($button, productId, wishlistId) {
        $button.addClass('loading');

        $.ajax({
            url: ggmCommerceAjax.ajax_url,
            type: 'POST',
            data: {
                action: 'ggmc_wishlist_toggle',
                product_id: productId,
                wishlist_id: wishlistId || 0,
                nonce: ggmCommerceAjax.nonce
            },
            success: function(response) {
                $button.removeClass('loading');

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

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

                    wishlistCache.count = response.data.count;

                    // Update all buttons for this product
                    updateWishlistButtonsForProduct(productId);
                    updateWishlistCountDisplays();

                    // Refresh wishlists data
                    loadAllWishlists();

                    // Trigger custom event
                    $(document).trigger('ggmc_wishlist_updated', {
                        productId: productId,
                        action: action,
                        count: wishlistCache.count,
                        productIds: wishlistCache.productIds,
                        wishlistId: wishlistId
                    });
                } else {
                    showWishlistMessage(response.data ? response.data.message : 'An error occurred', 'error');
                }
            },
            error: function() {
                $button.removeClass('loading');
                showWishlistMessage('An error occurred. Please try again.', 'error');
            }
        });
    }

    /**
     * Add item to wishlist
     */
    function addToWishlist($button, productId, wishlistId) {
        $button.addClass('loading');

        $.ajax({
            url: ggmCommerceAjax.ajax_url,
            type: 'POST',
            data: {
                action: 'ggmc_wishlist_add',
                product_id: productId,
                wishlist_id: wishlistId || 0,
                nonce: ggmCommerceAjax.nonce
            },
            success: function(response) {
                $button.removeClass('loading');

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

                    updateWishlistButtonsForProduct(productId);
                    updateWishlistCountDisplays();
                    showWishlistMessage(response.data.message, 'success');

                    // Refresh wishlists data
                    loadAllWishlists();

                    $(document).trigger('ggmc_wishlist_updated', {
                        productId: productId,
                        action: 'added',
                        count: wishlistCache.count,
                        productIds: wishlistCache.productIds,
                        wishlistId: wishlistId
                    });
                } else {
                    showWishlistMessage(response.data ? response.data.message : 'Failed to add to wishlist', 'error');
                }
            },
            error: function() {
                $button.removeClass('loading');
                showWishlistMessage('An error occurred. Please try again.', 'error');
            }
        });
    }

    /**
     * Remove item from wishlist
     */
    function removeFromWishlist($button, productId, wishlistId) {
        $button.addClass('loading');

        $.ajax({
            url: ggmCommerceAjax.ajax_url,
            type: 'POST',
            data: {
                action: 'ggmc_wishlist_remove',
                product_id: productId,
                wishlist_id: wishlistId || 0,
                nonce: ggmCommerceAjax.nonce
            },
            success: function(response) {
                $button.removeClass('loading');

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

                    updateWishlistButtonsForProduct(productId);
                    updateWishlistCountDisplays();
                    showWishlistMessage(response.data.message, 'info');

                    // Refresh wishlists data
                    loadAllWishlists();

                    $(document).trigger('ggmc_wishlist_updated', {
                        productId: productId,
                        action: 'removed',
                        count: wishlistCache.count,
                        productIds: wishlistCache.productIds,
                        wishlistId: wishlistId
                    });
                } else {
                    showWishlistMessage(response.data ? response.data.message : 'Failed to remove from wishlist', 'error');
                }
            },
            error: function() {
                $button.removeClass('loading');
                showWishlistMessage('An error occurred. Please try again.', 'error');
            }
        });
    }

    /**
     * Clear entire wishlist
     */
    function clearWishlist(wishlistId, callback) {
        $.ajax({
            url: ggmCommerceAjax.ajax_url,
            type: 'POST',
            data: {
                action: 'ggmc_wishlist_clear',
                wishlist_id: wishlistId || 0,
                nonce: ggmCommerceAjax.nonce
            },
            success: function(response) {
                if (response.success) {
                    if (!wishlistId || wishlistId === wishlistCache.currentWishlistId) {
                        wishlistCache.productIds = [];
                        wishlistCache.count = 0;
                    }

                    updateAllWishlistButtons();
                    updateWishlistCountDisplays();
                    showWishlistMessage(response.data.message, 'info');

                    // Refresh wishlists data
                    loadAllWishlists();

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

                    if (callback) {
                        callback(response.data);
                    }
                }
            },
            error: function() {
                showWishlistMessage('An error occurred. Please try again.', 'error');
            }
        });
    }

    // =========================================================================
    // WISHLIST MANAGEMENT (Create, Update, Delete)
    // =========================================================================

    /**
     * Create a new wishlist
     */
    function createWishlist(name, isDefault, callback) {
        if (wishlistCache.isGuest) {
            showWishlistMessage('Please log in to create wishlists.', 'error');
            return;
        }

        if (!wishlistCache.canCreateMore) {
            showWishlistMessage('Maximum number of wishlists reached.', 'error');
            return;
        }

        $.ajax({
            url: ggmCommerceAjax.ajax_url,
            type: 'POST',
            data: {
                action: 'ggmc_wishlist_create',
                name: name,
                is_default: isDefault ? 1 : 0,
                nonce: ggmCommerceAjax.nonce
            },
            success: function(response) {
                if (response.success && response.data) {
                    showWishlistMessage(response.data.message, 'success');

                    $(document).trigger('ggmc_wishlist_created', { wishlist: response.data.wishlist });

                    if (callback) {
                        callback(response.data);
                    }

                    // Reload page to show the new wishlist in server-rendered UI.
                    var newId = response.data.wishlist ? response.data.wishlist.id : null;
                    var url = new URL(window.location.href);
                    if (newId) {
                        url.searchParams.set('wishlist', newId);
                    }
                    window.location.href = url.toString();
                    return;
                } else {
                    showWishlistMessage(response.data ? response.data.message : 'Failed to create wishlist', 'error');
                }
            },
            error: function() {
                showWishlistMessage('An error occurred. Please try again.', 'error');
            }
        });
    }

    /**
     * Update a wishlist
     */
    function updateWishlist(wishlistId, name, callback) {
        $.ajax({
            url: ggmCommerceAjax.ajax_url,
            type: 'POST',
            data: {
                action: 'ggmc_wishlist_update',
                wishlist_id: wishlistId,
                name: name,
                nonce: ggmCommerceAjax.nonce
            },
            success: function(response) {
                if (response.success && response.data) {
                    showWishlistMessage(response.data.message, 'success');

                    // Refresh wishlists data
                    loadAllWishlists();

                    $(document).trigger('ggmc_wishlist_updated_meta', { wishlist: response.data.wishlist });

                    if (callback) {
                        callback(response.data);
                    }
                } else {
                    showWishlistMessage(response.data ? response.data.message : 'Failed to update wishlist', 'error');
                }
            },
            error: function() {
                showWishlistMessage('An error occurred. Please try again.', 'error');
            }
        });
    }

    /**
     * Delete a wishlist
     */
    function deleteWishlist(wishlistId, moveItems, callback) {
        $.ajax({
            url: ggmCommerceAjax.ajax_url,
            type: 'POST',
            data: {
                action: 'ggmc_wishlist_delete',
                wishlist_id: wishlistId,
                move_items: moveItems ? 1 : 0,
                nonce: ggmCommerceAjax.nonce
            },
            success: function(response) {
                if (response.success && response.data) {
                    showWishlistMessage(response.data.message, 'success');

                    $(document).trigger('ggmc_wishlist_deleted', { wishlistId: wishlistId });

                    if (callback) {
                        callback(response.data);
                    }

                    // Reload page to get fresh server-rendered content.
                    // Remove ?wishlist= param so we land on the new default.
                    var url = new URL(window.location.href);
                    url.searchParams.delete('wishlist');
                    window.location.href = url.toString();
                    return;
                } else {
                    showWishlistMessage(response.data ? response.data.message : 'Failed to delete wishlist', 'error');
                }
            },
            error: function() {
                showWishlistMessage('An error occurred. Please try again.', 'error');
            }
        });
    }

    /**
     * Set default wishlist
     */
    function setDefaultWishlist(wishlistId, callback) {
        $.ajax({
            url: ggmCommerceAjax.ajax_url,
            type: 'POST',
            data: {
                action: 'ggmc_wishlist_set_default',
                wishlist_id: wishlistId,
                nonce: ggmCommerceAjax.nonce
            },
            success: function(response) {
                if (response.success && response.data) {
                    showWishlistMessage(response.data.message, 'success');

                    $(document).trigger('ggmc_wishlist_default_changed', { wishlistId: wishlistId });

                    if (callback) {
                        callback(response.data);
                    }

                    // Reload page to reflect new default in server-rendered UI.
                    window.location.reload();
                    return;
                } else {
                    showWishlistMessage(response.data ? response.data.message : 'Failed to set default wishlist', 'error');
                }
            },
            error: function() {
                showWishlistMessage('An error occurred. Please try again.', 'error');
            }
        });
    }

    // =========================================================================
    // MOVE/COPY ITEMS
    // =========================================================================

    /**
     * Move items to another wishlist
     */
    function moveItems(productIds, fromWishlistId, toWishlistId, callback) {
        $.ajax({
            url: ggmCommerceAjax.ajax_url,
            type: 'POST',
            data: {
                action: 'ggmc_wishlist_move_items',
                product_ids: productIds,
                from_wishlist: fromWishlistId,
                to_wishlist: toWishlistId,
                nonce: ggmCommerceAjax.nonce
            },
            success: function(response) {
                if (response.success && response.data) {
                    showWishlistMessage(response.data.message, 'success');

                    // Refresh wishlists data
                    loadAllWishlists();

                    $(document).trigger('ggmc_wishlist_items_moved', {
                        productIds: productIds,
                        fromWishlistId: fromWishlistId,
                        toWishlistId: toWishlistId
                    });

                    if (callback) {
                        callback(response.data);
                    }
                } else {
                    showWishlistMessage(response.data ? response.data.message : 'Failed to move items', 'error');
                }
            },
            error: function() {
                showWishlistMessage('An error occurred. Please try again.', 'error');
            }
        });
    }

    /**
     * Copy items to another wishlist
     */
    function copyItems(productIds, fromWishlistId, toWishlistId, callback) {
        $.ajax({
            url: ggmCommerceAjax.ajax_url,
            type: 'POST',
            data: {
                action: 'ggmc_wishlist_copy_items',
                product_ids: productIds,
                from_wishlist: fromWishlistId,
                to_wishlist: toWishlistId,
                nonce: ggmCommerceAjax.nonce
            },
            success: function(response) {
                if (response.success && response.data) {
                    showWishlistMessage(response.data.message, 'success');

                    // Refresh wishlists data
                    loadAllWishlists();

                    $(document).trigger('ggmc_wishlist_items_copied', {
                        productIds: productIds,
                        fromWishlistId: fromWishlistId,
                        toWishlistId: toWishlistId
                    });

                    if (callback) {
                        callback(response.data);
                    }
                } else {
                    showWishlistMessage(response.data ? response.data.message : 'Failed to copy items', 'error');
                }
            },
            error: function() {
                showWishlistMessage('An error occurred. Please try again.', 'error');
            }
        });
    }

    // =========================================================================
    // SHARING
    // =========================================================================

    /**
     * Generate share link for a wishlist
     */
    function generateShareLink(wishlistId, callback) {
        if (!wishlistCache.sharingEnabled) {
            showWishlistMessage('Wishlist sharing is not enabled.', 'error');
            return;
        }

        $.ajax({
            url: ggmCommerceAjax.ajax_url,
            type: 'POST',
            data: {
                action: 'ggmc_wishlist_share',
                wishlist_id: wishlistId,
                nonce: ggmCommerceAjax.nonce
            },
            success: function(response) {
                if (response.success && response.data) {
                    showShareLinkModal(response.data.share_url);

                    $(document).trigger('ggmc_wishlist_share_generated', {
                        wishlistId: wishlistId,
                        shareUrl: response.data.share_url
                    });

                    if (callback) {
                        callback(response.data);
                    }
                } else {
                    showWishlistMessage(response.data ? response.data.message : 'Failed to generate share link', 'error');
                }
            },
            error: function() {
                showWishlistMessage('An error occurred. Please try again.', 'error');
            }
        });
    }

    /**
     * View a shared wishlist
     */
    function viewSharedWishlist(token, callback) {
        $.ajax({
            url: ggmCommerceAjax.ajax_url,
            type: 'POST',
            data: {
                action: 'ggmc_wishlist_view_shared',
                token: token,
                nonce: ggmCommerceAjax.nonce
            },
            success: function(response) {
                if (response.success && response.data) {
                    if (callback) {
                        callback(response.data);
                    }
                } else {
                    showWishlistMessage(response.data ? response.data.message : 'Wishlist not found', 'error');
                }
            },
            error: function() {
                showWishlistMessage('An error occurred. Please try again.', 'error');
            }
        });
    }

    /**
     * Show share link modal
     */
    function showShareLinkModal(shareUrl) {
        var $modal = $('<div class="ggmc-wishlist-share-modal">' +
            '<div class="ggmc-wishlist-share-modal-content">' +
            '<h3>' + getI18nString('share_wishlist', 'Share Wishlist') + '</h3>' +
            '<p>' + getI18nString('share_description', 'Copy this link to share your wishlist:') + '</p>' +
            '<div class="ggmc-share-link-wrapper">' +
            '<input type="text" class="ggmc-share-link-input" value="' + shareUrl + '" readonly>' +
            '<button type="button" class="ggmc-copy-share-link">' + getI18nString('copy', 'Copy') + '</button>' +
            '</div>' +
            '<button type="button" class="ggmc-share-modal-close">&times;</button>' +
            '</div>' +
            '</div>');

        $('body').append($modal);

        // Auto-select the URL
        $modal.find('.ggmc-share-link-input').select();

        // Copy button handler
        $modal.find('.ggmc-copy-share-link').on('click', function() {
            var $input = $modal.find('.ggmc-share-link-input');
            $input.select();
            document.execCommand('copy');
            $(this).text(getI18nString('copied', 'Copied!'));
            setTimeout(function() {
                $modal.find('.ggmc-copy-share-link').text(getI18nString('copy', 'Copy'));
            }, 2000);
        });

        // Close button handler
        $modal.find('.ggmc-share-modal-close').on('click', function() {
            $modal.remove();
        });

        // Close on background click
        $modal.on('click', function(e) {
            if ($(e.target).hasClass('ggmc-wishlist-share-modal')) {
                $modal.remove();
            }
        });
    }

    // =========================================================================
    // UI UPDATE FUNCTIONS
    // =========================================================================

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

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

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

        if (isInWishlist) {
            $button.addClass('in-wishlist');
            $button.attr('title', getI18nString('remove_from_wishlist', 'Remove from Wishlist'));
            // Change icon to filled heart if using Elementor icons
            $button.find('.eicon-heart-o').removeClass('eicon-heart-o').addClass('eicon-heart');
            $button.find('.fa-heart-o, .far.fa-heart').removeClass('fa-heart-o far fa-heart').addClass('fas fa-heart');
        } else {
            $button.removeClass('in-wishlist');
            $button.attr('title', getI18nString('add_to_wishlist', 'Add to Wishlist'));
            // Change icon back to outline heart
            $button.find('.eicon-heart').removeClass('eicon-heart').addClass('eicon-heart-o');
            $button.find('.fas.fa-heart').removeClass('fas fa-heart').addClass('far fa-heart');
        }
    }

    /**
     * Update all wishlist count displays
     */
    function updateWishlistCountDisplays() {
        // Update any elements showing wishlist count
        $('.ggmc-wishlist-count').text(wishlistCache.count);

        // Update count badges
        $('.ggmc-wishlist-count-badge').each(function() {
            var $badge = $(this);
            if (wishlistCache.count > 0) {
                $badge.text(wishlistCache.count).show();
            } else {
                $badge.hide();
            }
        });

        // Do NOT toggle empty/has-items states here based on global count.
        // The server renders the correct state for the active wishlist.
        // Only per-item removal (below in the remove handler) should update this.
    }

    // =========================================================================
    // TABS UI
    // =========================================================================

    /**
     * Initialize wishlist tabs
     */
    function initWishlistTabs() {
        $(document).on('click', '.ggmc-wishlist-tab', function(e) {
            e.preventDefault();
            var wishlistId = $(this).data('wishlist-id');
            switchToWishlist(wishlistId);
        });
    }

    /**
     * Update wishlist tabs UI
     */
    function updateWishlistTabs() {
        var $tabsContainer = $('.ggmc-wishlist-tabs-nav');
        if ($tabsContainer.length === 0 || wishlistCache.wishlists.length === 0) {
            return;
        }

        // If server-rendered tabs already exist, just update active states.
        var $existingTabs = $tabsContainer.find('.ggmc-wishlist-tab[data-wishlist-id]');
        if ($existingTabs.length > 0) {
            $existingTabs.each(function() {
                var $tab = $(this);
                var tabId = parseInt($tab.data('wishlist-id'), 10);
                $tab.toggleClass('active', tabId === wishlistCache.currentWishlistId);
            });
            // Also update tab panels and tab actions visibility.
            $('.ggmc-wishlist-tab-panel, .ggmc-wishlist-tab-actions').each(function() {
                var $el = $(this);
                var elId = parseInt($el.data('wishlist-id'), 10);
                $el.toggleClass('active', elId === wishlistCache.currentWishlistId);
            });
            return;
        }

        // Fallback: build tabs from cache (e.g. after creating/deleting a wishlist).
        var tabsHtml = '';
        wishlistCache.wishlists.forEach(function(wishlist) {
            var activeClass = wishlist.id === wishlistCache.currentWishlistId ? ' active' : '';
            var defaultIcon = wishlist.is_default ? ' <i class="eicon-star ggmc-default-star" title="Default"></i>' : '';
            tabsHtml += '<div class="ggmc-wishlist-tab' + activeClass + '" data-wishlist-id="' + wishlist.id + '" role="tab">' +
                '<span class="ggmc-tab-label">' + escapeHtml(wishlist.name) +
                ' <span class="tab-count">(' + wishlist.item_count + ')</span></span>' +
                defaultIcon +
                '</div>';
        });

        // Add "new wishlist" tab if user can create more
        if (wishlistCache.canCreateMore && !wishlistCache.isGuest) {
            tabsHtml += '<div class="ggmc-wishlist-tab ggmc-wishlist-tab-new" role="button" title="' + getI18nString('create_wishlist', 'Create New Wishlist') + '">' +
                '<i class="eicon-plus"></i>' +
                '</div>';
        }

        $tabsContainer.html(tabsHtml);
    }

    /**
     * Switch to a different wishlist
     */
    function switchToWishlist(wishlistId) {
        wishlistCache.currentWishlistId = wishlistId;

        // Update tabs active state
        $('.ggmc-wishlist-tab').removeClass('active');
        $('.ggmc-wishlist-tab[data-wishlist-id="' + wishlistId + '"]').addClass('active');

        // Load wishlist data and update display
        loadWishlistData(wishlistId, function(data) {
            updateWishlistDisplay(wishlistId, data);
        });

        $(document).trigger('ggmc_wishlist_switched', { wishlistId: wishlistId });
    }

    /**
     * Update wishlist display with new data
     */
    function updateWishlistDisplay(wishlistId, data) {
        var $container = $('.ggmc-wishlist-content[data-wishlist-id="' + wishlistId + '"]');
        if ($container.length === 0) {
            $container = $('.ggmc-wishlist-content');
        }

        // Update the container's data attribute
        $container.attr('data-wishlist-id', wishlistId);

        // Trigger event for widgets to re-render
        $(document).trigger('ggmc_wishlist_display_update', {
            wishlistId: wishlistId,
            data: data,
            container: $container
        });
    }

    // =========================================================================
    // DROPDOWN UI
    // =========================================================================

    /**
     * Initialize wishlist dropdown selector
     */
    function initWishlistDropdown() {
        $(document).on('change', '.ggmc-wishlist-dropdown-select', function() {
            var wishlistId = parseInt($(this).val(), 10);
            switchToWishlist(wishlistId);
        });
    }

    /**
     * Update wishlist dropdown UI
     */
    function updateWishlistDropdown() {
        var $dropdown = $('.ggmc-wishlist-dropdown-select');
        if ($dropdown.length === 0 || wishlistCache.wishlists.length === 0) {
            return;
        }

        // If server-rendered options already exist, just update selected state.
        var $existingOptions = $dropdown.find('option');
        if ($existingOptions.length > 0) {
            $dropdown.val(wishlistCache.currentWishlistId);
            return;
        }

        // Fallback: build options from cache (e.g. after creating/deleting a wishlist).
        var optionsHtml = '';
        wishlistCache.wishlists.forEach(function(wishlist) {
            var selected = wishlist.id === wishlistCache.currentWishlistId ? ' selected' : '';
            var defaultLabel = wishlist.is_default ? ' (' + getI18nString('default', 'Default') + ')' : '';
            optionsHtml += '<option value="' + wishlist.id + '"' + selected + '>' +
                escapeHtml(wishlist.name) + ' (' + wishlist.item_count + ')' + defaultLabel +
                '</option>';
        });

        $dropdown.html(optionsHtml);
    }

    // =========================================================================
    // MANAGEMENT CONTROLS UI
    // =========================================================================

    /**
     * Initialize management controls
     */
    function initManagementControls() {
        // Create wishlist button
        $(document).on('click', '.ggmc-wishlist-create-btn, .ggmc-wishlist-tab-new', function(e) {
            e.preventDefault();
            showCreateWishlistModal();
        });

        // Rename wishlist button
        $(document).on('click', '.ggmc-wishlist-rename-btn', function(e) {
            e.preventDefault();
            var wishlistId = $(this).data('wishlist-id') || wishlistCache.currentWishlistId;
            showRenameWishlistModal(wishlistId);
        });

        // Delete wishlist button
        $(document).on('click', '.ggmc-wishlist-delete-btn', function(e) {
            e.preventDefault();
            var wishlistId = $(this).data('wishlist-id') || wishlistCache.currentWishlistId;
            showDeleteWishlistModal(wishlistId);
        });

        // Set default wishlist button
        $(document).on('click', '.ggmc-wishlist-set-default-btn', function(e) {
            e.preventDefault();
            var wishlistId = $(this).data('wishlist-id') || wishlistCache.currentWishlistId;
            setDefaultWishlist(wishlistId);
        });

        // Share wishlist button
        $(document).on('click', '.ggmc-wishlist-share-btn', function(e) {
            e.preventDefault();
            var wishlistId = $(this).data('wishlist-id') || wishlistCache.currentWishlistId;
            generateShareLink(wishlistId);
        });
    }

    /**
     * Update management controls state
     */
    function updateManagementControls() {
        var $controls = $('.ggmc-wishlist-management-controls');
        if ($controls.length === 0) {
            return;
        }

        // Hide management for guests
        if (wishlistCache.isGuest) {
            $controls.hide();
            return;
        }

        $controls.show();

        // Update create button state
        var $createBtn = $controls.find('.ggmc-wishlist-create-btn');
        if (wishlistCache.canCreateMore) {
            $createBtn.prop('disabled', false).removeClass('disabled');
        } else {
            $createBtn.prop('disabled', true).addClass('disabled');
        }

        // Update share button visibility
        var $shareBtn = $controls.find('.ggmc-wishlist-share-btn');
        if (wishlistCache.sharingEnabled) {
            $shareBtn.show();
        } else {
            $shareBtn.hide();
        }
    }

    /**
     * Show create wishlist modal
     */
    function showCreateWishlistModal() {
        var $modal = $('<div class="ggmc-wishlist-modal">' +
            '<div class="ggmc-wishlist-modal-content">' +
            '<h3>' + getI18nString('create_wishlist', 'Create New Wishlist') + '</h3>' +
            '<div class="ggmc-wishlist-form-group">' +
            '<label for="ggmc-new-wishlist-name">' + getI18nString('wishlist_name', 'Wishlist Name') + '</label>' +
            '<input type="text" id="ggmc-new-wishlist-name" placeholder="' + getI18nString('wishlist_name_placeholder', 'My Wishlist') + '">' +
            '</div>' +
            '<div class="ggmc-wishlist-form-group">' +
            '<label><input type="checkbox" id="ggmc-new-wishlist-default"> ' + getI18nString('set_as_default', 'Set as default wishlist') + '</label>' +
            '</div>' +
            '<div class="ggmc-wishlist-modal-actions">' +
            '<button type="button" class="ggmc-wishlist-modal-cancel">' + getI18nString('cancel', 'Cancel') + '</button>' +
            '<button type="button" class="ggmc-wishlist-modal-confirm">' + getI18nString('create', 'Create') + '</button>' +
            '</div>' +
            '<button type="button" class="ggmc-wishlist-modal-close">&times;</button>' +
            '</div>' +
            '</div>');

        $('body').append($modal);

        // Focus the input
        $modal.find('#ggmc-new-wishlist-name').focus();

        // Confirm button handler
        $modal.find('.ggmc-wishlist-modal-confirm').on('click', function() {
            var name = $modal.find('#ggmc-new-wishlist-name').val().trim();
            var isDefault = $modal.find('#ggmc-new-wishlist-default').is(':checked');

            if (!name) {
                showWishlistMessage(getI18nString('name_required', 'Please enter a wishlist name'), 'error');
                return;
            }

            createWishlist(name, isDefault, function() {
                $modal.remove();
            });
        });

        // Cancel/close handlers
        $modal.find('.ggmc-wishlist-modal-cancel, .ggmc-wishlist-modal-close').on('click', function() {
            $modal.remove();
        });

        // Close on background click
        $modal.on('click', function(e) {
            if ($(e.target).hasClass('ggmc-wishlist-modal')) {
                $modal.remove();
            }
        });

        // Enter key handler
        $modal.find('#ggmc-new-wishlist-name').on('keypress', function(e) {
            if (e.which === 13) {
                $modal.find('.ggmc-wishlist-modal-confirm').click();
            }
        });
    }

    /**
     * Show rename wishlist modal
     */
    function showRenameWishlistModal(wishlistId) {
        var wishlist = wishlistCache.wishlists.find(function(w) { return w.id === wishlistId; });
        if (!wishlist) {
            return;
        }

        var $modal = $('<div class="ggmc-wishlist-modal">' +
            '<div class="ggmc-wishlist-modal-content">' +
            '<h3>' + getI18nString('rename_wishlist', 'Rename Wishlist') + '</h3>' +
            '<div class="ggmc-wishlist-form-group">' +
            '<label for="ggmc-rename-wishlist-name">' + getI18nString('wishlist_name', 'Wishlist Name') + '</label>' +
            '<input type="text" id="ggmc-rename-wishlist-name" value="' + escapeHtml(wishlist.name) + '">' +
            '</div>' +
            '<div class="ggmc-wishlist-modal-actions">' +
            '<button type="button" class="ggmc-wishlist-modal-cancel">' + getI18nString('cancel', 'Cancel') + '</button>' +
            '<button type="button" class="ggmc-wishlist-modal-confirm">' + getI18nString('save', 'Save') + '</button>' +
            '</div>' +
            '<button type="button" class="ggmc-wishlist-modal-close">&times;</button>' +
            '</div>' +
            '</div>');

        $('body').append($modal);

        // Focus and select the input
        $modal.find('#ggmc-rename-wishlist-name').focus().select();

        // Confirm button handler
        $modal.find('.ggmc-wishlist-modal-confirm').on('click', function() {
            var name = $modal.find('#ggmc-rename-wishlist-name').val().trim();

            if (!name) {
                showWishlistMessage(getI18nString('name_required', 'Please enter a wishlist name'), 'error');
                return;
            }

            updateWishlist(wishlistId, name, function() {
                $modal.remove();
            });
        });

        // Cancel/close handlers
        $modal.find('.ggmc-wishlist-modal-cancel, .ggmc-wishlist-modal-close').on('click', function() {
            $modal.remove();
        });

        // Close on background click
        $modal.on('click', function(e) {
            if ($(e.target).hasClass('ggmc-wishlist-modal')) {
                $modal.remove();
            }
        });

        // Enter key handler
        $modal.find('#ggmc-rename-wishlist-name').on('keypress', function(e) {
            if (e.which === 13) {
                $modal.find('.ggmc-wishlist-modal-confirm').click();
            }
        });
    }

    /**
     * Show delete wishlist modal
     */
    function showDeleteWishlistModal(wishlistId) {
        var wishlist = wishlistCache.wishlists.find(function(w) { return w.id === wishlistId; });
        if (!wishlist) {
            return;
        }

        // Prevent deleting the only wishlist.
        if (wishlistCache.wishlists.length <= 1) {
            showWishlistMessage(getI18nString('cannot_delete_only', 'You cannot delete your only wishlist.'), 'error');
            return;
        }

        var hasItems = wishlist.item_count > 0;
        var isDefault = wishlist.is_default;

        // Build informational notices.
        var notices = '';
        if (isDefault) {
            notices += '<p class="ggmc-wishlist-warning">' +
                getI18nString('delete_default_warning', 'This is your default wishlist. Another wishlist will automatically become the new default.') +
                '</p>';
        }
        if (hasItems) {
            notices += '<p class="ggmc-wishlist-warning">' +
                getI18nString('has_items_warning', 'This wishlist contains ' + wishlist.item_count + ' item' + (wishlist.item_count !== 1 ? 's' : '') + '.') +
                '</p>';
        }

        // Move items option — available when there are items and other wishlists exist.
        var moveItemsOption = hasItems && wishlistCache.wishlists.length > 1 ?
            '<div class="ggmc-wishlist-form-group">' +
            '<label><input type="checkbox" id="ggmc-delete-move-items" checked> ' +
            getI18nString('move_items_to_default', 'Move items to default wishlist before deleting') +
            '</label>' +
            '</div>' : '';

        var $modal = $('<div class="ggmc-wishlist-modal">' +
            '<div class="ggmc-wishlist-modal-content">' +
            '<h3>' + getI18nString('delete_wishlist', 'Delete Wishlist') + '</h3>' +
            '<p>' + getI18nString('delete_confirm', 'Are you sure you want to delete') + ' "' + escapeHtml(wishlist.name) + '"?</p>' +
            notices +
            moveItemsOption +
            '<div class="ggmc-wishlist-modal-actions">' +
            '<button type="button" class="ggmc-wishlist-modal-cancel">' + getI18nString('cancel', 'Cancel') + '</button>' +
            '<button type="button" class="ggmc-wishlist-modal-confirm ggmc-btn-danger">' + getI18nString('delete', 'Delete') + '</button>' +
            '</div>' +
            '<button type="button" class="ggmc-wishlist-modal-close">&times;</button>' +
            '</div>' +
            '</div>');

        $('body').append($modal);

        // Confirm button handler
        $modal.find('.ggmc-wishlist-modal-confirm').on('click', function() {
            var moveItems = $modal.find('#ggmc-delete-move-items').is(':checked');
            deleteWishlist(wishlistId, moveItems, function() {
                $modal.remove();
            });
        });

        // Cancel/close handlers
        $modal.find('.ggmc-wishlist-modal-cancel, .ggmc-wishlist-modal-close').on('click', function() {
            $modal.remove();
        });

        // Close on background click
        $modal.on('click', function(e) {
            if ($(e.target).hasClass('ggmc-wishlist-modal')) {
                $modal.remove();
            }
        });
    }

    // =========================================================================
    // ITEM SELECTION (for move/copy)
    // =========================================================================

    /**
     * Initialize item selection for move/copy operations
     */
    function initItemSelection() {
        // Toggle item selection
        $(document).on('click', '.ggmc-wishlist-item-select', function(e) {
            e.preventDefault();
            e.stopPropagation();
            $(this).closest('.ggmc-wishlist-item').toggleClass('selected');
            updateBulkActionVisibility();
        });

        // Select all items
        $(document).on('click', '.ggmc-wishlist-select-all', function(e) {
            e.preventDefault();
            var $container = $(this).closest('.ggmc-wishlist-content');
            $container.find('.ggmc-wishlist-item').addClass('selected');
            updateBulkActionVisibility();
        });

        // Deselect all items
        $(document).on('click', '.ggmc-wishlist-deselect-all', function(e) {
            e.preventDefault();
            var $container = $(this).closest('.ggmc-wishlist-content');
            $container.find('.ggmc-wishlist-item').removeClass('selected');
            updateBulkActionVisibility();
        });

        // Move selected items
        $(document).on('click', '.ggmc-wishlist-move-selected', function(e) {
            e.preventDefault();
            var $container = $(this).closest('.ggmc-wishlist-widget');
            var selectedIds = getSelectedProductIds($container);
            if (selectedIds.length > 0) {
                showMoveItemsModal(selectedIds);
            }
        });

        // Copy selected items
        $(document).on('click', '.ggmc-wishlist-copy-selected', function(e) {
            e.preventDefault();
            var $container = $(this).closest('.ggmc-wishlist-widget');
            var selectedIds = getSelectedProductIds($container);
            if (selectedIds.length > 0) {
                showCopyItemsModal(selectedIds);
            }
        });
    }

    /**
     * Get selected product IDs
     */
    function getSelectedProductIds($container) {
        var ids = [];
        $container.find('.ggmc-wishlist-item.selected').each(function() {
            ids.push(parseInt($(this).data('product-id'), 10));
        });
        return ids;
    }

    /**
     * Update bulk action visibility
     */
    function updateBulkActionVisibility() {
        var hasSelected = $('.ggmc-wishlist-item.selected').length > 0;
        if (hasSelected) {
            $('.ggmc-wishlist-bulk-actions').show();
        } else {
            $('.ggmc-wishlist-bulk-actions').hide();
        }
    }

    /**
     * Show move items modal
     */
    function showMoveItemsModal(productIds) {
        showTransferItemsModal(productIds, 'move');
    }

    /**
     * Show copy items modal
     */
    function showCopyItemsModal(productIds) {
        showTransferItemsModal(productIds, 'copy');
    }

    /**
     * Show transfer items modal (move or copy)
     */
    function showTransferItemsModal(productIds, mode) {
        var title = mode === 'move' ?
            getI18nString('move_items', 'Move Items') :
            getI18nString('copy_items', 'Copy Items');

        var buttonText = mode === 'move' ?
            getI18nString('move', 'Move') :
            getI18nString('copy', 'Copy');

        var optionsHtml = '';
        wishlistCache.wishlists.forEach(function(wishlist) {
            if (wishlist.id !== wishlistCache.currentWishlistId) {
                optionsHtml += '<option value="' + wishlist.id + '">' + escapeHtml(wishlist.name) + '</option>';
            }
        });

        var $modal = $('<div class="ggmc-wishlist-modal">' +
            '<div class="ggmc-wishlist-modal-content">' +
            '<h3>' + title + '</h3>' +
            '<p>' + productIds.length + ' ' + getI18nString('items_selected', 'item(s) selected') + '</p>' +
            '<div class="ggmc-wishlist-form-group">' +
            '<label for="ggmc-transfer-wishlist">' + getI18nString('select_wishlist', 'Select Wishlist') + '</label>' +
            '<select id="ggmc-transfer-wishlist">' + optionsHtml + '</select>' +
            '</div>' +
            '<div class="ggmc-wishlist-modal-actions">' +
            '<button type="button" class="ggmc-wishlist-modal-cancel">' + getI18nString('cancel', 'Cancel') + '</button>' +
            '<button type="button" class="ggmc-wishlist-modal-confirm">' + buttonText + '</button>' +
            '</div>' +
            '<button type="button" class="ggmc-wishlist-modal-close">&times;</button>' +
            '</div>' +
            '</div>');

        $('body').append($modal);

        // Confirm button handler
        $modal.find('.ggmc-wishlist-modal-confirm').on('click', function() {
            var toWishlistId = parseInt($modal.find('#ggmc-transfer-wishlist').val(), 10);

            if (mode === 'move') {
                moveItems(productIds, wishlistCache.currentWishlistId, toWishlistId, function() {
                    $modal.remove();
                    $('.ggmc-wishlist-item.selected').removeClass('selected');
                    updateBulkActionVisibility();
                });
            } else {
                copyItems(productIds, wishlistCache.currentWishlistId, toWishlistId, function() {
                    $modal.remove();
                    $('.ggmc-wishlist-item.selected').removeClass('selected');
                    updateBulkActionVisibility();
                });
            }
        });

        // Cancel/close handlers
        $modal.find('.ggmc-wishlist-modal-cancel, .ggmc-wishlist-modal-close').on('click', function() {
            $modal.remove();
        });

        // Close on background click
        $modal.on('click', function(e) {
            if ($(e.target).hasClass('ggmc-wishlist-modal')) {
                $modal.remove();
            }
        });
    }

    // =========================================================================
    // NOTIFICATION MESSAGES
    // =========================================================================

    /**
     * Show wishlist notification message
     */
    function showWishlistMessage(message, type) {
        type = type || 'info';

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

        // Create message element
        var $message = $('<div class="ggmc-wishlist-message ggmc-wishlist-message-' + type + '">' +
            '<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 delay
        setTimeout(function() {
            $message.removeClass('visible');
            setTimeout(function() {
                $message.remove();
            }, 300);
        }, 3000);

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

    // =========================================================================
    // UTILITY FUNCTIONS
    // =========================================================================

    /**
     * Get i18n string with fallback
     */
    function getI18nString(key, fallback) {
        if (typeof ggmCommerceAjax !== 'undefined' && ggmCommerceAjax.i18n && ggmCommerceAjax.i18n[key]) {
            return ggmCommerceAjax.i18n[key];
        }
        return fallback;
    }

    /**
     * Escape HTML entities
     */
    function escapeHtml(text) {
        var div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }

    // =========================================================================
    // WISHLIST SELECTOR POPOVER
    // =========================================================================

    var popoverState = {
        isOpen: false,
        productId: null,
        $triggerButton: null,
        selectedWishlistId: null
    };

    /**
     * Check if popover should be shown (logged-in user with multiple wishlists capability)
     */
    function shouldShowPopover() {
        // Don't show popover for guests
        if (wishlistCache.isGuest) {
            return false;
        }

        // Show popover if user has wishlists loaded and can have multiple
        return wishlistCache.wishlists.length > 0 || wishlistCache.canCreateMore;
    }

    /**
     * Show the wishlist selector popover
     */
    function showWishlistPopover($button, productId) {
        var $popover = $('#ggmc-wishlist-selector-popover');
        if ($popover.length === 0) {
            // Popover not in DOM, fall back to simple toggle
            return false;
        }

        // Update popover state
        popoverState.isOpen = true;
        popoverState.productId = productId;
        popoverState.$triggerButton = $button;

        // Check if product is already in any wishlist
        var isInWishlist = wishlistCache.productIds.indexOf(productId) !== -1;

        // Update popover title based on whether item is in wishlist
        var titleText = isInWishlist ?
            getI18nString('move_to_wishlist', 'Move to Wishlist') :
            getI18nString('add_to_wishlist', 'Add to Wishlist');
        $popover.find('.ggmc-wishlist-popover-title').text(titleText);

        // Update button text
        var buttonText = isInWishlist ?
            getI18nString('move', 'Move') :
            getI18nString('add_to_wishlist', 'Add to Wishlist');
        $popover.find('.ggmc-wishlist-popover-add-btn').text(buttonText);

        // Refresh the wishlist list in popover
        refreshPopoverWishlistList();

        // Pre-select the default wishlist
        var defaultWishlist = wishlistCache.wishlists.find(function(w) { return w.is_default; });
        if (defaultWishlist) {
            popoverState.selectedWishlistId = defaultWishlist.id;
            $popover.find('input[value="' + defaultWishlist.id + '"]').prop('checked', true);
            $popover.find('.ggmc-wishlist-popover-add-btn').prop('disabled', false);
        }

        // Position and show popover
        positionPopover($popover, $button);
        $popover.fadeIn(150);

        // Reset create form
        $popover.find('.ggmc-wishlist-popover-create-form').hide();
        $popover.find('.ggmc-wishlist-popover-create-btn').show();
        $popover.find('.ggmc-wishlist-popover-new-name').val('');

        return true;
    }

    /**
     * Refresh the wishlist list in the popover
     */
    function refreshPopoverWishlistList() {
        var $popover = $('#ggmc-wishlist-selector-popover');
        var $list = $popover.find('.ggmc-wishlist-popover-list');

        if (wishlistCache.wishlists.length === 0) {
            $list.html('<p class="ggmc-wishlist-popover-empty">' +
                getI18nString('no_wishlists', 'No wishlists yet. Create one below.') + '</p>');
            return;
        }

        var html = '';
        wishlistCache.wishlists.forEach(function(wishlist) {
            var defaultIndicator = wishlist.is_default ?
                ' <span class="ggmc-default-indicator">(' + getI18nString('default', 'Default') + ')</span>' : '';
            var checked = wishlist.is_default ? ' checked' : '';

            html += '<label class="ggmc-wishlist-popover-item" data-wishlist-id="' + wishlist.id + '">' +
                '<input type="radio" name="ggmc_wishlist_select" value="' + wishlist.id + '"' + checked + ' />' +
                '<span class="ggmc-wishlist-popover-item-name">' +
                escapeHtml(wishlist.name) + defaultIndicator +
                '</span>' +
                '<span class="ggmc-wishlist-popover-item-count">' + wishlist.item_count + '</span>' +
                '</label>';
        });

        $list.html(html);

        // Update create button visibility
        var $createSection = $popover.find('.ggmc-wishlist-popover-create');
        if (wishlistCache.canCreateMore) {
            $createSection.show();
        } else {
            $createSection.hide();
        }
    }

    /**
     * Position the popover relative to the trigger button
     */
    function positionPopover($popover, $button) {
        var buttonOffset = $button.offset();
        var buttonWidth = $button.outerWidth();
        var buttonHeight = $button.outerHeight();
        var popoverWidth = 280; // Fixed width for the popover
        var popoverHeight = $popover.outerHeight() || 300;
        var windowWidth = $(window).width();
        var windowHeight = $(window).height();
        var scrollTop = $(window).scrollTop();

        // Try to position below the button, centered
        var left = buttonOffset.left + (buttonWidth / 2) - (popoverWidth / 2);
        var top = buttonOffset.top + buttonHeight + 10;

        // Adjust if off-screen horizontally
        if (left < 10) {
            left = 10;
        } else if (left + popoverWidth > windowWidth - 10) {
            left = windowWidth - popoverWidth - 10;
        }

        // If not enough space below, position above
        if (top + popoverHeight > scrollTop + windowHeight - 10) {
            top = buttonOffset.top - popoverHeight - 10;
            $popover.addClass('above');
        } else {
            $popover.removeClass('above');
        }

        // Update arrow position
        var arrowLeft = buttonOffset.left + (buttonWidth / 2) - left;
        $popover.find('.ggmc-wishlist-popover-arrow').css('left', arrowLeft + 'px');

        $popover.css({
            position: 'absolute',
            top: top + 'px',
            left: left + 'px',
            width: popoverWidth + 'px'
        });
    }

    /**
     * Hide the wishlist selector popover
     */
    function hideWishlistPopover() {
        var $popover = $('#ggmc-wishlist-selector-popover');
        $popover.fadeOut(100);
        popoverState.isOpen = false;
        popoverState.productId = null;
        popoverState.$triggerButton = null;
        popoverState.selectedWishlistId = null;
    }

    /**
     * Add product to selected wishlist from popover
     */
    function addFromPopover() {
        if (!popoverState.productId || !popoverState.selectedWishlistId) {
            return;
        }

        var $addBtn = $('#ggmc-wishlist-selector-popover').find('.ggmc-wishlist-popover-add-btn');
        $addBtn.prop('disabled', true).text(getI18nString('adding', 'Adding...'));

        addToWishlist(
            popoverState.$triggerButton || $('<div>'),
            popoverState.productId,
            popoverState.selectedWishlistId
        );

        // Close popover after a brief delay
        setTimeout(function() {
            hideWishlistPopover();
            $addBtn.prop('disabled', false).text(getI18nString('add_to_wishlist', 'Add to Wishlist'));
        }, 500);
    }

    /**
     * Create new wishlist and add product from popover
     */
    function createAndAddFromPopover(wishlistName) {
        if (!popoverState.productId || !wishlistName.trim()) {
            return;
        }

        var $confirmBtn = $('#ggmc-wishlist-selector-popover').find('.ggmc-wishlist-popover-create-confirm');
        $confirmBtn.prop('disabled', true).text(getI18nString('creating', 'Creating...'));

        createWishlist(wishlistName.trim(), false, function(data) {
            if (data.wishlist && data.wishlist.id) {
                // Add product to the newly created wishlist
                addToWishlist(
                    popoverState.$triggerButton || $('<div>'),
                    popoverState.productId,
                    data.wishlist.id
                );

                // Close popover
                setTimeout(function() {
                    hideWishlistPopover();
                    $confirmBtn.prop('disabled', false).text(getI18nString('create_and_add', 'Create & Add'));
                }, 500);
            } else {
                $confirmBtn.prop('disabled', false).text(getI18nString('create_and_add', 'Create & Add'));
            }
        });
    }

    // =========================================================================
    // EVENT HANDLERS
    // =========================================================================

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

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

        if (!productId) {
            return;
        }

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

        // Check if we should show the popover
        if (shouldShowPopover() && !wishlistId) {
            // Show popover for wishlist selection
            if (showWishlistPopover($button, productId)) {
                return;
            }
        }

        // Fall back to simple toggle
        toggleWishlistItem($button, productId, wishlistId);
    });

    /**
     * Event handler for popover close button
     */
    $(document).on('click', '.ggmc-wishlist-popover-close', function(e) {
        e.preventDefault();
        e.stopPropagation();
        hideWishlistPopover();
    });

    /**
     * Event handler for clicking outside popover
     */
    $(document).on('click', function(e) {
        if (!popoverState.isOpen) {
            return;
        }

        var $target = $(e.target);
        var $popover = $('#ggmc-wishlist-selector-popover');

        // Don't close if clicking inside popover or on wishlist button
        if ($target.closest('#ggmc-wishlist-selector-popover').length > 0 ||
            $target.closest('.wishlist-btn').length > 0) {
            return;
        }

        hideWishlistPopover();
    });

    /**
     * Event handler for selecting a wishlist in popover
     */
    $(document).on('change', '#ggmc-wishlist-selector-popover input[name="ggmc_wishlist_select"]', function() {
        popoverState.selectedWishlistId = parseInt($(this).val(), 10);
        $('#ggmc-wishlist-selector-popover').find('.ggmc-wishlist-popover-add-btn').prop('disabled', false);
    });

    /**
     * Event handler for add button in popover
     */
    $(document).on('click', '.ggmc-wishlist-popover-add-btn', function(e) {
        e.preventDefault();
        e.stopPropagation();
        addFromPopover();
    });

    /**
     * Event handler for create new wishlist button in popover
     */
    $(document).on('click', '.ggmc-wishlist-popover-create-btn', function(e) {
        e.preventDefault();
        e.stopPropagation();
        $(this).hide();
        $('#ggmc-wishlist-selector-popover').find('.ggmc-wishlist-popover-create-form').show();
        $('#ggmc-wishlist-selector-popover').find('.ggmc-wishlist-popover-new-name').focus();
    });

    /**
     * Event handler for cancel create in popover
     */
    $(document).on('click', '.ggmc-wishlist-popover-create-cancel', function(e) {
        e.preventDefault();
        e.stopPropagation();
        $('#ggmc-wishlist-selector-popover').find('.ggmc-wishlist-popover-create-form').hide();
        $('#ggmc-wishlist-selector-popover').find('.ggmc-wishlist-popover-create-btn').show();
        $('#ggmc-wishlist-selector-popover').find('.ggmc-wishlist-popover-new-name').val('');
    });

    /**
     * Event handler for confirm create in popover
     */
    $(document).on('click', '.ggmc-wishlist-popover-create-confirm', function(e) {
        e.preventDefault();
        e.stopPropagation();
        var wishlistName = $('#ggmc-wishlist-selector-popover').find('.ggmc-wishlist-popover-new-name').val();
        if (wishlistName.trim()) {
            createAndAddFromPopover(wishlistName);
        }
    });

    /**
     * Event handler for enter key in create form
     */
    $(document).on('keypress', '.ggmc-wishlist-popover-new-name', function(e) {
        if (e.which === 13) {
            e.preventDefault();
            $('.ggmc-wishlist-popover-create-confirm').click();
        }
    });

    /**
     * Event handler for escape key to close popover
     */
    $(document).on('keydown', function(e) {
        if (e.which === 27 && popoverState.isOpen) {
            hideWishlistPopover();
        }
    });

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

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

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

        addToWishlist($button, productId, wishlistId);
    });

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

        var $button = $(this);
        var productId = parseInt($button.data('product-id'), 10);
        var wishlistId = $button.data('wishlist-id') || wishlistCache.currentWishlistId;

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

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

        removeFromWishlist($button, productId, wishlistId);
    });

    /**
     * Event handler for clear all wishlist
     */
    $(document).on('click', '.ggmc-wishlist-clear-all', function(e) {
        e.preventDefault();

        var $button = $(this);
        var wishlistId = $button.data('wishlist-id') || wishlistCache.currentWishlistId;

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

        var confirmMsg = getI18nString('confirm_clear_wishlist', 'Are you sure you want to clear your entire wishlist?');
        if (!confirm(confirmMsg)) {
            return;
        }

        $button.addClass('loading');

        clearWishlist(wishlistId, function() {
            $button.removeClass('loading');
            // Refresh the page to show empty state
            setTimeout(function() {
                location.reload();
            }, 1000);
        });
    });

    /**
     * Listen for wishlist updates and refresh widget display
     */
    $(document).on('ggmc_wishlist_updated', function(e, data) {
        if (data.action === 'removed') {
            // Remove the item from wishlist widget display
            var selector = '.ggmc-wishlist-item[data-product-id="' + data.productId + '"]';
            if (data.wishlistId) {
                selector = '.ggmc-wishlist-content[data-wishlist-id="' + data.wishlistId + '"] ' + selector;
            }

            $(selector).fadeOut(300, function() {
                $(this).remove();

                // Check if wishlist is now empty
                var $container = $(this).closest('.ggmc-wishlist-content');
                if ($container.find('.ggmc-wishlist-item').length === 0) {
                    $container.find('.ggmc-wishlist-empty').show();
                    $container.find('.ggmc-wishlist-has-items').hide();
                }
            });
        }
    });

    /**
     * Listen for items moved/copied and refresh display
     */
    $(document).on('ggmc_wishlist_items_moved ggmc_wishlist_items_copied', function(e, data) {
        // Reload current wishlist display
        if (wishlistCache.currentWishlistId) {
            loadWishlistData(wishlistCache.currentWishlistId, function(responseData) {
                updateWishlistDisplay(wishlistCache.currentWishlistId, responseData);
            });
        }
    });

    // =========================================================================
    // PUBLIC API
    // =========================================================================

    /**
     * Expose wishlist functions globally for use by other scripts/widgets
     */
    window.ggmCommerceWishlist = {
        // Item operations
        isInWishlist: function(productId, wishlistId) {
            return wishlistCache.productIds.indexOf(parseInt(productId, 10)) !== -1;
        },
        getCount: function(wishlistId) {
            if (wishlistId) {
                var wishlist = wishlistCache.wishlists.find(function(w) { return w.id === wishlistId; });
                return wishlist ? wishlist.item_count : 0;
            }
            return wishlistCache.count;
        },
        getProductIds: function() {
            return wishlistCache.productIds.slice(); // Return a copy
        },
        add: function(productId, wishlistId) {
            var $dummyButton = $('<div>');
            addToWishlist($dummyButton, parseInt(productId, 10), wishlistId);
        },
        remove: function(productId, wishlistId) {
            var $dummyButton = $('<div>');
            removeFromWishlist($dummyButton, parseInt(productId, 10), wishlistId);
        },
        toggle: function(productId, wishlistId) {
            var $dummyButton = $('<div>');
            toggleWishlistItem($dummyButton, parseInt(productId, 10), wishlistId);
        },
        clear: function(wishlistId) {
            clearWishlist(wishlistId);
        },

        // Wishlist management
        getWishlists: function() {
            return wishlistCache.wishlists.slice(); // Return a copy
        },
        getCurrentWishlistId: function() {
            return wishlistCache.currentWishlistId;
        },
        switchWishlist: function(wishlistId) {
            switchToWishlist(wishlistId);
        },
        createWishlist: createWishlist,
        updateWishlist: updateWishlist,
        deleteWishlist: deleteWishlist,
        setDefaultWishlist: setDefaultWishlist,

        // Move/Copy
        moveItems: moveItems,
        copyItems: copyItems,

        // Sharing
        generateShareLink: generateShareLink,
        viewSharedWishlist: viewSharedWishlist,

        // Utility
        refresh: function() {
            loadWishlistState();
        },
        loadWishlistData: loadWishlistData,

        // State
        isGuest: function() {
            return wishlistCache.isGuest;
        },
        canCreateMore: function() {
            return wishlistCache.canCreateMore;
        },
        isSharingEnabled: function() {
            return wishlistCache.sharingEnabled;
        },
        getMaxWishlists: function() {
            return wishlistCache.maxWishlists;
        }
    };

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