/**
 * AIEO Wishlist — heart button click handler.
 *
 * Targets buttons rendered by AIEO_Wishlist::build_heart_html on the
 * single-product page and archive loop. Reads product_id off the
 * button, POSTs to aieo_wishlist_toggle, updates visual state
 * optimistically (rolls back on error). Also keeps the shared wishlist
 * cookie in sync so the side-cart sees the change immediately.
 *
 * Side-cart favorites (RV / Favorites tabs) have their own separate
 * handler in aieo-side-cart.js — this file does NOT touch those.
 */
(function ($) {
    'use strict';

    var __ = ( window.wp && window.wp.i18n && window.wp.i18n.__ ) ? window.wp.i18n.__ : function (s) { return s; };
    var _x = ( window.wp && window.wp.i18n && window.wp.i18n._x ) ? window.wp.i18n._x : function (s) { return s; };
    var _n = ( window.wp && window.wp.i18n && window.wp.i18n._n ) ? window.wp.i18n._n : function (s, p, n) { return n === 1 ? s : p; };
    var _sprintf = ( window.wp && window.wp.i18n && window.wp.i18n.sprintf ) ? window.wp.i18n.sprintf : function (s) { return s; };

    if (typeof window.aieoWishlist === 'undefined') return;
    var CFG = window.aieoWishlistHeart || {};

    var COOKIE_NAME = window.aieoWishlist.cookie || 'woocommerce_items_in_cart_merchant_wishlist';

    function readCookie() {
        var m = document.cookie.match(new RegExp('(?:^|; )' + COOKIE_NAME + '=([^;]*)'));
        if (!m) return [];
        try {
            return decodeURIComponent(m[1]).split(',')
                .map(function (x) { return parseInt(x, 10) || 0; })
                .filter(function (x) { return x > 0; });
        } catch (e) { return []; }
    }
    function writeCookie(ids) {
        var d = new Date();
        d.setTime(d.getTime() + (30 * 24 * 60 * 60 * 1000));
        document.cookie = COOKIE_NAME + '=' + encodeURIComponent(ids.join(',')) +
            ';expires=' + d.toUTCString() + ';path=/;SameSite=Lax';
    }

    /**
     * Try to open the side-cart and switch to the Favorites tab.
     * Returns true if both DOM hooks were found, false otherwise
     * (caller can fall back to a wishlist-page navigation).
     */
    function openSideCartFavorites() {
        var $trigger = $('.aieo-sc-trigger').first();
        var $favTab  = $('.aieo-sc-tab[data-aieo-sc-tab="favorites"]').first();
        if (!$trigger.length || !$favTab.length) return false;
        $trigger.trigger('click');
        // Switch happens synchronously after open — no setTimeout
        // needed; the side-cart's tab handler runs on click.
        $favTab.trigger('click');
        return true;
    }

    /**
     * "See your favourites" label click. Opens side-cart Favorites
     * if the side-cart DOM is present; otherwise falls back to the
     * configured wishlist page URL; otherwise no-op.
     */
    $(document).on('click', '.aieo-wishlist-heart-label', function (e) {
        var $label = $(this);
        var $wrap  = $label.closest('.aieo-wishlist-heart-wrap');
        var inList = $wrap.hasClass('is-in-list');
        if (!inList) {
            // Not yet in list — proxy to the heart click, which adds.
            e.preventDefault();
            $wrap.find('.aieo-wishlist-heart').first().trigger('click');
            return;
        }
        // In list — open side-cart Favorites or fall back to wishlist page.
        e.preventDefault();
        if (openSideCartFavorites()) return;
        if (CFG.wishlistUrl) { window.location = CFG.wishlistUrl; }
    });

    $(document).on('click', '.aieo-wishlist-heart', function (e) {
        e.preventDefault();
        e.stopPropagation();

        var $btn = $(this);
        if ($btn.hasClass('is-loading')) return;

        var pid = parseInt($btn.attr('data-aieo-wishlist-product'), 10) || 0;
        if (!pid) return;

        // PR #4 (brand-shopping): generic item_type plumbing. The button
        // declares its kind via data-aieo-wishlist-item-type (default
        // 'product' for backwards compatibility). Brand hearts pass
        // 'brand' here; the AJAX endpoint validates the allowlist.
        var itemType = $btn.attr('data-aieo-wishlist-item-type') || 'product';

        // If a wishlist-page URL is configured AND the heart is already
        // filled, navigate there instead of removing. Matches PPE's
        // long-standing behavior so shoppers don't accidentally un-
        // wishlist when they mean to "view my wishlist".
        if ($btn.hasClass('is-in-list') && CFG.wishlistUrl) {
            window.location = CFG.wishlistUrl;
            return;
        }

        var source = $btn.attr('data-aieo-wishlist-source') || 'single_product';
        var wasInList = $btn.hasClass('is-in-list');
        var action = wasInList ? 'remove' : 'add';

        // Optimistic paint — flip immediately.
        $btn.addClass('is-loading').toggleClass('is-in-list');
        var nowInList = $btn.hasClass('is-in-list');
        var $tooltip = $btn.find('.aieo-wishlist-heart-tooltip');
        if ($tooltip.length) {
            $tooltip.text(
                nowInList
                    ? ($btn.attr('data-tooltip-remove') || CFG.tooltipRemove || __('Remove from wishlist', 'ai-eshop-optimizer'))
                    : ($btn.attr('data-tooltip-add')    || CFG.tooltipAdd    || __('Add to wishlist', 'ai-eshop-optimizer'))
            );
        }
        $btn.attr('aria-pressed', nowInList ? 'true' : 'false');

        // Sync the wrapper + sibling label (single-product layout).
        var $wrap = $btn.closest('.aieo-wishlist-heart-wrap');
        if ($wrap.length) {
            $wrap.toggleClass('is-in-list', nowInList);
            var $label = $wrap.find('.aieo-wishlist-heart-label');
            if ($label.length) {
                $label.text(
                    nowInList
                        ? ($label.attr('data-label-view') || __('See your favourites', 'ai-eshop-optimizer'))
                        : ($label.attr('data-label-add')  || __('Add to your favourites', 'ai-eshop-optimizer'))
                );
            }
        }

        // Cookie-side mirror — only for products. The shared wishlist
        // cookie carries product IDs; brands and other item types live
        // server-side only so we don't pollute it.
        var cookie = readCookie();
        var rollbackCookie = cookie.slice();
        if (itemType === 'product') {
            if (action === 'add' && cookie.indexOf(pid) === -1) { cookie.unshift(pid); }
            else if (action === 'remove') { cookie = cookie.filter(function (x) { return x !== pid; }); }
            writeCookie(cookie);
        }

        // Sync ALL hearts for this (item_type, id) pair on the page
        // (a product can appear in the archive + related block; a brand
        // heart could be in both the hero and a card grid).
        $('.aieo-wishlist-heart[data-aieo-wishlist-product="' + pid + '"]').each(function () {
            if (this === $btn[0]) return;
            var otherKind = $(this).attr('data-aieo-wishlist-item-type') || 'product';
            if (otherKind !== itemType) return;
            $(this).toggleClass('is-in-list', $btn.hasClass('is-in-list'));
        });

        $.post(window.aieoWishlist.ajaxUrl, {
            action:          'aieo_wishlist_toggle',
            nonce:           window.aieoWishlist.nonce,
            item_id:         pid,
            item_type:       itemType,
            wishlist_action: action,
            source_type:     source,
            source_id:       0,
            source_name:     '',
        }).done(function (resp) {
            $btn.removeClass('is-loading');
            if (!resp || !resp.success) {
                $btn.toggleClass('is-in-list');
                if (itemType === 'product') { writeCookie(rollbackCookie); }
            }
            try {
                $(window).trigger('aieo_wishlist_updated',  [pid, action === 'add', itemType]);
                $(window).trigger('om_ppe_wishlist_updated', [pid, action === 'add', itemType]);
            } catch (err) { /* ignore */ }
        }).fail(function () {
            $btn.removeClass('is-loading').toggleClass('is-in-list');
            if (itemType === 'product') { writeCookie(rollbackCookie); }
        });
    });
})(jQuery);
