/**
 * Mini-Cart Quantity Updater (Vanilla JS)
 *
 * Integrates with the theme's global 'js-quantity-increment' logic 
 * to handle quantity changes in the mini-cart via AJAX.
 */
(function () {
    'use strict';

    var isUpdating = false;
    var updateTimer = null;

    /**
     * Update a cart item quantity via WC AJAX.
     */
    function updateCartItemQty(cartItemKey, qty, nonce, item) {
        if (isUpdating) return;
        isUpdating = true;

        var qtyWrap = item.querySelector('.js-mini-cart-update-qty');
        var list = document.querySelector('.rt-mini-cart-list');

        if (qtyWrap) qtyWrap.classList.add('is-loading');
        if (list) list.classList.add('rt-loading');

        var ajaxUrl = (typeof wc_cart_fragments_params !== 'undefined') ? wc_cart_fragments_params.wc_ajax_url.toString().replace('%%endpoint%%', 'update_cart_item') : '/?wc-ajax=update_cart_item';

        var formData = new FormData();
        formData.append('cart_item_key', cartItemKey);
        formData.append('quantity', qty);
        formData.append('nonce', nonce);

        fetch(ajaxUrl, {
            method: 'POST',
            body: formData
        })
            .then(function (response) {
                return response.json();
            })
            .then(function (response) {
                if (!response || !response.success) {
                    // Revert to server value if failed
                    var fallbackQty = (response && response.data && response.data.old_qty) ? response.data.old_qty : 1;
                    var input = item.querySelector('.rt-quantity__input');
                    if (input) input.value = fallbackQty;
                    return;
                }

                // Update fragments directly
                if (response.data.fragments) {
                    Object.entries(response.data.fragments).forEach(function ([selector, html]) {
                        var targets = document.querySelectorAll(selector);
                        targets.forEach(function (target) {
                            target.outerHTML = html;
                        });
                    });
                }

                // Notify WooCommerce (Using jQuery trigger if available for compatibility)
                if (window.jQuery) {
                    window.jQuery(document.body).trigger('wc_fragments_refreshed');
                } else {
                    document.body.dispatchEvent(new CustomEvent('wc_fragments_refreshed'));
                }
            })
            .catch(function () {
                if (window.jQuery) {
                    window.jQuery(document.body).trigger('wc_fragment_refresh');
                } else {
                    document.body.dispatchEvent(new CustomEvent('wc_fragment_refresh'));
                }
            })
            .finally(function () {
                if (qtyWrap) qtyWrap.classList.remove('is-loading');
                if (list) list.classList.remove('rt-loading');
                isUpdating = false;
            });
    }

    /**
     * Listen for 'change' event on quantity inputs via delegation.
     */
    document.addEventListener('DOMContentLoaded', function () {
        document.body.addEventListener('change', function (e) {
            var input = e.target.closest('.js-mini-cart-update-qty .rt-quantity__input');
            if (!input) return;

            var wrap = input.closest('.js-mini-cart-update-qty');
            var item = input.closest('.mini_cart_item');

            var key = wrap.getAttribute('data-cart-item-key');
            var nonce = wrap.getAttribute('data-nonce');
            var val = parseInt(input.value);

            // 0 is allowed through — it tells the server to remove the item from the cart.
            if (isNaN(val) || val < 0) return;

            // Debounce: Wait 800ms
            clearTimeout(updateTimer);
            updateTimer = setTimeout(function () {
                updateCartItemQty(key, val, nonce, item);
            }, 800);
        });
    });

})();
