/**
 * AIEO Complementary Products
 *
 * Click handler on `.aieo-compl-add` collects all checked complementary
 * product IDs and POSTs them in one round-trip. Updates WC fragments on
 * success so any cart counter on the page reflects the new totals.
 */
(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.aieoComplementary === 'undefined') { return; }
    var cfg  = window.aieoComplementary;
    var i18n = cfg.i18n || {};

    $(document).on('click', '.aieo-compl-add', function (e) {
        e.preventDefault();

        var $btn    = $(this);
        var $block  = $btn.closest('.aieo-compl');
        var $status = $block.find('.aieo-compl-status').removeClass('error').text('');

        var ids = [];
        var variations = {};       // { product_id: variation_id, … } for variable products
        var missingVariation = false;

        $block.find('.aieo-compl-check:checked').each(function () {
            var pid = parseInt(this.value, 10);
            if (!pid) { return; }
            ids.push(pid);

            // If the checkbox sits in a row with a variation <select>,
            // collect the customer's pick. Empty / "0" means the
            // customer checked the box but didn't pick a variation —
            // flag it so we can show a clear error instead of silently
            // picking a default for them.
            var $row = $(this).closest('.aieo-compl-item');
            var $varSel = $row.find('.aieo-compl-variation');
            if ($varSel.length) {
                var vid = parseInt($varSel.val(), 10) || 0;
                if (!vid) {
                    missingVariation = true;
                    $varSel.addClass('aieo-compl-variation--error');
                } else {
                    $varSel.removeClass('aieo-compl-variation--error');
                    variations[pid] = vid;
                }
            }
        });

        if (!ids.length) {
            $status.addClass('error').text(i18n.pickOne || __('Pick one first.', 'ai-eshop-optimizer'));
            return;
        }
        if (missingVariation) {
            $status.addClass('error').text(i18n.pickVariation || __('Pick a variation for each variable product.', 'ai-eshop-optimizer'));
            return;
        }

        $btn.prop('disabled', true);
        $status.text(i18n.adding || __('Adding…', 'ai-eshop-optimizer'));

        $.ajax({
            url: cfg.ajaxUrl,
            method: 'POST',
            data: {
                action:        'aieo_dmm_complementary_add',
                nonce:         cfg.nonce,
                product_ids:   ids,
                variations:    variations,
                source_id:     $block.data('source')
            },
            success: function (resp) {
                $btn.prop('disabled', false);
                if (!resp || !resp.success) {
                    $status.addClass('error').text((resp && resp.data && resp.data.message) || i18n.failed || __('Failed.', 'ai-eshop-optimizer'));
                    return;
                }
                $status.text(i18n.added || __('Added.', 'ai-eshop-optimizer'));

                // Trigger WooCommerce's fragment refresh so mini-carts /
                // cart-count badges across the page update without a
                // full page reload.
                if (resp.data.fragments) {
                    $(document.body).trigger('wc_fragment_refresh');
                    $(document.body).trigger('added_to_cart', [resp.data.fragments, '', $btn]);
                }

                // Uncheck after success so the customer doesn't accidentally
                // re-add the same items on a second click.
                $block.find('.aieo-compl-check:checked').prop('checked', false);
            },
            error: function () {
                $btn.prop('disabled', false);
                $status.addClass('error').text(i18n.failed || __('Failed.', 'ai-eshop-optimizer'));
            }
        });
    });
})(jQuery);
