/**
 * aieo/brand-archive-hero — Follow-brand button click handler.
 *
 * Decoupled from the legacy AIEO_Wishlist heart system on purpose:
 *   - That system runs in IAPI mode on this install (loads
 *     aieo-wishlist-iapi.js from the runtime plugin, which only
 *     understands product items).
 *   - We need item_type='brand' end-to-end without modifying the
 *     runtime plugin or the IAPI store.
 *
 * Direct fetch to wp-admin/admin-ajax.php (action=aieo_wishlist_toggle).
 * The endpoint already accepts item_type='brand' and validates via
 * term_exists() against product_brand. Result: a row in wp_aieo_wishlist
 * with item_type='brand', item_id=<product_brand term_id>.
 */
(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; };

    function init(btn) {
        if (btn.__aieoBrandFollowInit) return;
        btn.__aieoBrandFollowInit = true;

        btn.addEventListener('click', function (ev) {
            ev.preventDefault();
            ev.stopPropagation();
            if (btn.classList.contains('is-loading')) return;

            var brandId = parseInt(btn.getAttribute('data-brand-id'), 10) || 0;
            if (brandId <= 0) return;

            var ajaxUrl  = btn.getAttribute('data-ajax-url') || '';
            var nonce    = btn.getAttribute('data-nonce') || '';
            var labelAdd = btn.getAttribute('data-label-add') || __('Follow brand', 'ai-eshop-optimizer');
            var labelIn  = btn.getAttribute('data-label-in')  || __('Following', 'ai-eshop-optimizer');
            var wasIn    = btn.classList.contains('is-in-list');
            var action   = wasIn ? 'remove' : 'add';

            // Optimistic paint.
            btn.classList.add('is-loading');
            btn.classList.toggle('is-in-list');
            btn.setAttribute('aria-pressed', btn.classList.contains('is-in-list') ? 'true' : 'false');
            var label = btn.querySelector('.aieo-brand-follow__label');
            if (label) label.textContent = btn.classList.contains('is-in-list') ? labelIn : labelAdd;

            var fd = new FormData();
            fd.set('action',          'aieo_wishlist_toggle');
            fd.set('nonce',           nonce);
            fd.set('item_id',         String(brandId));
            fd.set('item_type',       'brand');
            fd.set('wishlist_action', action);
            fd.set('source_type',     'brand_archive');

            fetch(ajaxUrl, {
                method: 'POST',
                credentials: 'same-origin',
                body: fd,
            }).then(function (r) {
                return r.json().catch(function () { return { success: false }; });
            }).then(function (resp) {
                btn.classList.remove('is-loading');
                if (!resp || !resp.success) {
                    // Roll back.
                    btn.classList.toggle('is-in-list');
                    btn.setAttribute('aria-pressed', btn.classList.contains('is-in-list') ? 'true' : 'false');
                    if (label) label.textContent = btn.classList.contains('is-in-list') ? labelIn : labelAdd;
                    if (window.console && resp && resp.data && resp.data.message) {
                        console.warn('[aieo/brand-follow]', resp.data.message);
                    }
                    return;
                }
                // Broadcast so the side cart's Favorites tab + any other
                // listeners re-hydrate. Same event name + signature the
                // legacy product wishlist uses, with item_type='brand'.
                broadcast(brandId, action === 'add', 'brand');
            }).catch(function (err) {
                btn.classList.remove('is-loading');
                btn.classList.toggle('is-in-list');
                btn.setAttribute('aria-pressed', btn.classList.contains('is-in-list') ? 'true' : 'false');
                if (label) label.textContent = btn.classList.contains('is-in-list') ? labelIn : labelAdd;
                if (window.console) { console.warn('[aieo/brand-follow]', err); }
            });
        });
    }

    /**
     * Notify the side cart (and any other listener) that the wishlist
     * changed for an item. Uses both the jQuery event bus (where the
     * side cart listens) AND a vanilla CustomEvent on body (for
     * non-jQuery consumers / future Interactivity-API hearts).
     */
    function broadcast(itemId, added, itemType) {
        try {
            if (window.jQuery) {
                window.jQuery(window).trigger('aieo_wishlist_updated', [itemId, !!added, itemType]);
            }
        } catch (e) { /* ignore */ }
        try {
            document.body.dispatchEvent(new CustomEvent('aieo:wishlist:changed', {
                detail: { productId: itemId, itemId: itemId, inList: !!added, itemType: itemType }
            }));
        } catch (e) { /* ignore */ }
    }

    function boot() {
        document.querySelectorAll('.aieo-brand-follow').forEach(init);
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', boot);
    } else {
        boot();
    }
})();
