/**
 * Cart Page JavaScript
 *
 */

(function($) {
    'use strict';

    // Cart functionality
    const Cart = {
        init: function() {
            this.bindEvents();
            this.initQuantityControls();
            this.initRemoveButtons();
            this.initCouponForm();
            this.initBulkActions();
        },

        bindEvents: function() {
            const self = this;

            // Listen for WooCommerce cart updates
            $(document.body).on('updated_cart_totals', function() {
                self.initQuantityControls();
                self.initRemoveButtons();
                self.initBulkActions();
            });
        },

        // Quantity controls with circular +/- buttons
        initQuantityControls: function() {
            $('.cart-item').each(function() {
                const $item = $(this);
                const $quantityWrap = $item.find('.quantity-control .quantity');

                if (!$quantityWrap.length) return;

                const $input = $quantityWrap.find('input[type="number"]');

                // Remove existing buttons if any
                $quantityWrap.find('.qty-btn').remove();

                // Wrap input if not already wrapped
                if (!$quantityWrap.find('.qty-wrapper').length) {
                    $input.wrap('<div class="qty-wrapper"></div>');
                }

                const $wrapper = $quantityWrap.find('.qty-wrapper');

                // Add minus button
                const $minusBtn = $('<button type="button" class="qty-btn qty-minus">−</button>');
                $minusBtn.insertBefore($input);

                // Add plus button
                const $plusBtn = $('<button type="button" class="qty-btn qty-plus">+</button>');
                $plusBtn.insertAfter($input);

                // Handle minus click
                $minusBtn.on('click', function(e) {
                    e.preventDefault();
                    let val = parseInt($input.val()) || 0;
                    const min = parseInt($input.attr('min')) || 1;
                    if (val > min) {
                        $input.val(val - 1).trigger('change');
                    }
                });

                // Handle plus click
                $plusBtn.on('click', function(e) {
                    e.preventDefault();
                    let val = parseInt($input.val()) || 0;
                    const max = parseInt($input.attr('max')) || 999;
                    if (val < max) {
                        $input.val(val + 1).trigger('change');
                    }
                });
            });
        },

        // Remove item with animation
        initRemoveButtons: function() {
            $('.remove-btn').on('click', function(e) {
                const $btn = $(this);
                const $cartItem = $btn.closest('.cart-item');

                // Add removing animation
                $cartItem.addClass('removing');
            });
        },

        // Coupon form handling
        initCouponForm: function() {
            $('.promo-box').on('submit', function(e) {
                const $form = $(this);
                const $input = $form.find('.promo-input');
                const code = $input.val().trim();

                if (!code) {
                    e.preventDefault();
                    $input.addClass('error');
                    setTimeout(function() {
                        $input.removeClass('error');
                    }, 2000);
                    return false;
                }
            });
        },

        // Select-all checkbox + remove-selected bulk action
        initBulkActions: function() {
            const self = this;
            const $selectAll = $('#cartSelectAll');
            if (!$selectAll.length) {
                return;
            }

            // Keep the "Select All" checkbox in sync with the row checkboxes.
            const syncSelectAll = function() {
                const $checks = $('.cart-item-check');
                if (!$checks.length) {
                    $selectAll.prop('checked', false);
                    return;
                }
                const allChecked = $checks.length === $checks.filter(':checked').length;
                $selectAll.prop('checked', allChecked);
            };

            $selectAll.off('change.cartBulk').on('change.cartBulk', function() {
                $('.cart-item-check').prop('checked', this.checked);
            });

            $(document).off('change.cartBulk', '.cart-item-check')
                .on('change.cartBulk', '.cart-item-check', syncSelectAll);

            // Remove every checked item via the AJAX qty endpoint (qty = 0 removes).
            $('.cart-remove-selected').off('click.cartBulk').on('click.cartBulk', function(e) {
                e.preventDefault();

                const keys = $('.cart-item-check:checked').map(function() {
                    return $(this).closest('.cart-item').attr('data-cart-item-key');
                }).get();

                if (!keys.length) {
                    return;
                }

                const $btn = $(this);
                $btn.prop('disabled', true);

                self.removeItemsAjax(keys, function() {
                    window.location.reload();
                });
            });
        },

        // Sequentially remove cart items through the existing AJAX endpoint.
        removeItemsAjax: function(keys, done) {
            const cfg = (typeof shopbarCartQty !== 'undefined') ? shopbarCartQty : null;
            if (!cfg || !cfg.ajaxUrl || !cfg.nonce) {
                window.location.reload();
                return;
            }

            let i = 0;
            const next = function() {
                if (i >= keys.length) {
                    if (typeof done === 'function') {
                        done();
                    }
                    return;
                }
                const key = keys[i++];
                const body = new URLSearchParams();
                body.append('action', 'shopbar_update_cart_qty');
                body.append('nonce', cfg.nonce);
                body.append('cart_item_key', key);
                body.append('quantity', '0');

                fetch(cfg.ajaxUrl, {
                    method: 'POST',
                    credentials: 'same-origin',
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                    body: body.toString()
                }).then(function() {
                    next();
                }).catch(function() {
                    next();
                });
            };
            next();
        }
    };

    // Initialize cart when DOM is ready
    $(document).ready(function() {
        if ($('body').hasClass('woocommerce-cart')) {
            Cart.init();
        }
    });

})(jQuery);
