/**
 * AIEO Brand Gifts — front-end JS for the single-product picker (B)
 * and reward-card claim flow (A1). Both contexts hit the same
 * `aieo_dmm_brand_gift_pick` AJAX endpoint and share the variation-
 * dropdown rendering.
 *
 * Side-cart picker (the small <select> inside the banner) lives in
 * aieo-side-cart.js — this file does NOT touch it.
 */
(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 (!window.aieoBrandGifts) return;
    var CFG = window.aieoBrandGifts;

    // -------------------------------------------------------------------------
    // Variation dropdown — shared between contexts
    // -------------------------------------------------------------------------
    function renderVariationDropdown($container, offerId, productId, currentVid) {
        $container.empty().html(
            '<div class="aieo-bg-variation-loading" style="font-size:12px;color:#6b7280;">…</div>'
        );
        $.post(CFG.ajaxUrl, {
            action:     'aieo_dmm_brand_gift_variations',
            nonce:      CFG.nonce,
            product_id: productId
        }).done(function (resp) {
            if (!resp || !resp.success) {
                $container.html('<small style="color:#9a3412;">' + (CFG.i18n.error || __('Error', 'ai-eshop-optimizer')) + '</small>');
                return;
            }
            var variations = (resp.data && resp.data.variations) || [];
            if (!variations.length) {
                $container.html('<small style="color:#9a3412;">' + (CFG.i18n.noVariations || __('No variations', 'ai-eshop-optimizer')) + '</small>');
                return;
            }
            var html = '<select class="aieo-bg-variation-select"' +
                ' data-offer-id="' + offerId + '"' +
                ' data-product-id="' + productId + '">';
            html += '<option value="0">' + (CFG.i18n.pickVariation || __('Pick variation', 'ai-eshop-optimizer')) + '</option>';
            variations.forEach(function (v) {
                var sel = (parseInt(currentVid, 10) === v.variation_id) ? ' selected' : '';
                html += '<option value="' + v.variation_id + '"' + sel + '>' + v.label + '</option>';
            });
            html += '</select>';
            $container.html(html);
        }).fail(function () {
            $container.html('<small style="color:#9a3412;">' + (CFG.i18n.error || __('Error', 'ai-eshop-optimizer')) + '</small>');
        });
    }

    // -------------------------------------------------------------------------
    // (B) Single-product page picker
    // -------------------------------------------------------------------------
    $(document).on('change', '.aieo-bg-product-select', function () {
        var $sel    = $(this);
        var offerId = parseInt($sel.attr('data-offer-id'), 10) || 0;
        var pid     = parseInt($sel.val(), 10) || 0;
        var type    = $sel.find('option:selected').attr('data-product-type') || 'simple';
        if (!offerId || !pid) return;
        var $varBox = $sel.closest('.aieo-bg-product-card').find('.aieo-bg-product-variation');

        // Save the parent first so the cart drops any stale gift line.
        $.post(CFG.ajaxUrl, {
            action:     'aieo_dmm_brand_gift_pick',
            nonce:      CFG.nonce,
            offer_id:   offerId,
            product_id: pid
        });

        if (type === 'variable') {
            renderVariationDropdown($varBox, offerId, pid, 0);
        } else {
            $varBox.empty();
        }
    });

    // -------------------------------------------------------------------------
    // (A1) Reward-card claim — only fires when the offer is qualified
    // (locked cards have aria-disabled="true" and we no-op them).
    // -------------------------------------------------------------------------
    $(document).on('click', '[data-aieo-bg-claim]', function (e) {
        e.preventDefault();
        var $card = $(this);
        if ($card.attr('aria-disabled') === 'true') { return; }
        var offerId = parseInt($card.attr('data-offer-id'), 10) || 0;
        var pid     = parseInt($card.attr('data-product-id'), 10) || 0;
        var type    = $card.attr('data-product-type') || 'simple';
        if (!offerId || !pid) return;

        $.post(CFG.ajaxUrl, {
            action:     'aieo_dmm_brand_gift_pick',
            nonce:      CFG.nonce,
            offer_id:   offerId,
            product_id: pid
        }).done(function (resp) {
            if (!resp || !resp.success) { return; }
            // Refresh side-cart panel so the rewards section + cart
            // line both reflect the new pick.
            if (window.jQuery && jQuery('.aieo-sc-root').length) {
                // Trigger the side-cart's existing fetch by clicking
                // the trigger (no-ops if cart already open) and
                // letting the get response refresh both blocks.
                if (typeof window.aieoSideCartFetch === 'function') {
                    window.aieoSideCartFetch();
                } else {
                    // Soft reload of the rewards block via a manual
                    // ajax_get hit. Side-cart JS picks it up.
                    jQuery(document).trigger('aieo_brand_gifts_picked', [offerId, pid]);
                }
            }
            // For variable picks the user still needs to choose a
            // variation — render the dropdown right under the card.
            if (type === 'variable') {
                var $varBox = $card.parent().find('.aieo-bg-reward-variation[data-product-id="' + pid + '"]').first();
                if (!$varBox.length) {
                    // Card list hasn't been re-rendered yet — inject one inline.
                    $varBox = $('<div class="aieo-sc-gift-variation aieo-bg-reward-variation"></div>')
                        .attr('data-offer-id', offerId)
                        .attr('data-product-id', pid);
                    $card.after($varBox);
                }
                renderVariationDropdown($varBox, offerId, pid, 0);
            }
        });
    });

    // Variation dropdown change (in either context) — POST with the
    // chosen variation_id and refresh the side cart.
    $(document).on('change', '.aieo-bg-variation-select', function () {
        var $sel    = $(this);
        var offerId = parseInt($sel.attr('data-offer-id'), 10) || 0;
        var pid     = parseInt($sel.attr('data-product-id'), 10) || 0;
        var vid     = parseInt($sel.val(), 10) || 0;
        if (!offerId || !pid || !vid) return;
        $sel.prop('disabled', true);
        $.post(CFG.ajaxUrl, {
            action:       'aieo_dmm_brand_gift_pick',
            nonce:        CFG.nonce,
            offer_id:     offerId,
            product_id:   pid,
            variation_id: vid
        }).done(function () {
            $sel.prop('disabled', false);
            if (typeof window.aieoSideCartFetch === 'function') { window.aieoSideCartFetch(); }
        }).fail(function () { $sel.prop('disabled', false); });
    });
})(jQuery);
