// Quantity buttons on the single product and cart pages.
jQuery(document).ready(function($) {
    $(document).ajaxComplete(function() {
        shoptimizerWooQuantityButtons();
    });
    $(document.body).on('wc_fragments_refreshed', function() {
        shoptimizerWooQuantityButtons();
    });
});

document.addEventListener('DOMContentLoaded', function() {
    window.addEventListener('load', shoptimizerWooQuantityButtons);
});

/**
 * WooCommerce quantity buttons (AUTM-optimized)
 */
function shoptimizerWooQuantityButtons() {
    var quantityBoxes = document.querySelectorAll(
        '.woocommerce-cart-form div.quantity:not(.buttons_added) .qty, ' +
        '.summary div.quantity:not(.buttons_added) .qty'
    );

    if (quantityBoxes.length > 0) {
        quantityBoxes.forEach(function(input) {
            if (input.type !== 'date' && input.type !== 'hidden') {
                input.parentNode.classList.add('buttons_added');
            }
        });

        // Enforce minimum on initial load
        var quantityInputs = document.querySelectorAll('input.qty');
        quantityInputs.forEach(function(input) {
            var parent = input.closest('.product-quantity');
            if (!parent) {
                var min = parseFloat(input.getAttribute('min'));
                var val = parseFloat(input.value);
                if (!isNaN(min) && min > 0 && val < min) {
                    input.value = min;
                }
            }
        });
    }
}

document.addEventListener('DOMContentLoaded', function() {
    document.addEventListener('click', function(event) {
        var btn = event.target;

        if (!btn.classList.contains('plus') && !btn.classList.contains('minus')) {
            return;
        }

        var quantityWrapper = btn.closest('.quantity');
        if (!quantityWrapper) return;

        var input = quantityWrapper.querySelector('input.qty');
        if (!input) return;

        var current = parseFloat(input.value);
        var max = parseFloat(input.getAttribute('max'));
        var min = parseFloat(input.getAttribute('min'));

        var rawStep = input.getAttribute('step');
        var step = parseFloat(rawStep);

        if (isNaN(current)) current = 0;
        if (isNaN(min)) min = 0;
        if (rawStep === 'any' || isNaN(step)) step = 1;

        // Determine decimal precision for rounding (AUTM-compatible)
        const stepDecimals = (step.toString().split('.')[1] || '').length;
        const precision = Math.pow(10, stepDecimals);

        let newValue = current;

        if (btn.classList.contains('plus')) {
            if (!isNaN(max)) {
                newValue = Math.min(current + step, max);
            } else {
                newValue = current + step;
            }
        } else {
            newValue = Math.max(current - step, min);
        }

        // Fix floating point issues (critical for AUTM decimals)
        newValue = Math.round(newValue * precision) / precision;

        // Prevent weird negative or NaN outputs
        if (isNaN(newValue) || newValue < 0) {
            newValue = min || 0;
        }

        input.value = newValue;

        // Enable WooCommerce cart update button
        var updateCart = document.querySelector('.woocommerce-cart-form [name="update_cart"]');
        if (updateCart) {
            updateCart.removeAttribute('disabled');
            updateCart.setAttribute('aria-disabled', 'false');
        }

        input.dispatchEvent(new Event('change', { bubbles: true }));

        event.stopPropagation();
        event.preventDefault();
    });
});
