/**
 * WooCommerce Cart Improvements
 * 
 * Handles custom quantity buttons and cart interactions.
 */
(function($) {
    'use strict';

    /**
     * Add plus/minus buttons to quantity inputs
     */
    function initQuantityButtons() {
        // Find all quantity inputs that don't have our buttons yet
        $('.quantity:not(.paws-qty-added)').each(function() {
            var $container = $(this);
            var $input = $container.find('input.qty');
            
            if ($input.length && $input.attr('type') !== 'hidden') {
                $container.addClass('paws-qty-added');
                
                // Add minus button
                $('<button type="button" class="paws-qty-btn paws-minus shadow-sm"><i class="fa-solid fa-minus"></i></button>')
                    .insertBefore($input);
                
                // Add plus button
                $('<button type="button" class="paws-qty-btn paws-plus shadow-sm"><i class="fa-solid fa-plus"></i></button>')
                    .insertAfter($input);
            }
        });
    }

    /**
     * Handle quantity button clicks
     */
    $(document).on('click', '.paws-qty-btn', function(e) {
        e.preventDefault();
        
        var $btn = $(this);
        var $container = $btn.closest('.quantity');
        var $input = $container.find('input.qty');
        var val = parseFloat($input.val()) || 0;
        var step = parseFloat($input.attr('step')) || 1;
        var min = parseFloat($input.attr('min'));
        var max = parseFloat($input.attr('max'));
        
        if ($btn.hasClass('paws-plus')) {
            if (max && val >= max) {
                $input.val(max);
            } else {
                $input.val(val + step);
            }
        } else {
            if (min && val <= min) {
                $input.val(min);
            } else if (val > 0) {
                $input.val(val - step);
            }
        }
        
        // Trigger change to enable "Update Cart" button
        $input.trigger('change');
    });

    // Initialize on load
    $(document).ready(function() {
        initQuantityButtons();
    });

    // Re-initialize when cart is updated via AJAX
    $(document).on('updated_cart_totals', function() {
        initQuantityButtons();
    });

})(jQuery);
