;(function($) {
    'use strict';

    var WPUF_Pricing = {
        init: function() {
            if (this.initialized) {
                return;
            }
            this.initialized = true;
            this.bindEvents();
            this.calculateTotal();
        },

        initialized: false,

        bindEvents: function() {
            var self = this;

            // Price field changes
            $(document).on('change keyup', '[data-price-field="true"]', function() {
                self.calculateTotal();
            });

            // Pricing checkbox changes
            $(document).on('change', '[data-type="pricing-checkbox"]', function() {
                self.calculateTotal();
            });

            // Pricing radio changes
            $(document).on('change', '[data-type="pricing-radio"]', function() {
                var $radio = $(this);
                // Enable quantity input for selected radio
                $radio.closest('.wpuf-fields').find('.wpuf-pricing-quantity').prop('disabled', true);
                if ($radio.is(':checked')) {
                    $radio.closest('.wpuf-pricing-radio-item').find('.wpuf-pricing-quantity').prop('disabled', false);
                }
                self.calculateTotal();
            });

            // Pricing select/dropdown changes
            $(document).on('change', '[data-type="pricing-select"]', function() {
                self.calculateTotal();
            });

            // Pricing multiselect changes
            $(document).on('change', '[data-type="pricing-multiselect"]', function() {
                var $select = $(this);
                var $qtyContainer = $select.closest('.wpuf-fields').find('.wpuf-multiselect-quantities');

                // Show/hide quantity inputs based on selection
                $qtyContainer.find('.wpuf-qty-row').hide();
                $select.find('option:selected').each(function() {
                    var value = $(this).val();
                    $qtyContainer.find('[data-value="' + value + '"]').show();
                });

                self.calculateTotal();
            });

            // Quantity field changes
            $(document).on('change keyup', '.wpuf-pricing-quantity', function() {
                self.calculateTotal();
            });
        },

        calculateTotal: function() {
            var total = 0;
            var items = [];

            // Calculate from price fields
            $('[data-price-field="true"]').each(function() {
                var $field = $(this);
                var price = parseFloat($field.val()) || 0;

                if (price !== 0) {
                    var $label = $field.closest('li').find('.wpuf-label label');
                    var fieldLabel = $label.length ? $label.text().replace('*', '').trim() : 'Price';

                    items.push({
                        label: fieldLabel,
                        quantity: 1,
                        price: price
                    });
                    total += price;
                }
            });

            // Calculate from pricing checkboxes
            $('[data-type="pricing-checkbox"]:checked').each(function() {
                var $checkbox = $(this);
                var price = parseFloat($checkbox.data('price')) || 0;
                var qty = 1;
                var $qtyInput = $checkbox.closest('.wpuf-pricing-checkbox-item').find('.wpuf-pricing-quantity');
                if ($qtyInput.length && $qtyInput.is(':visible')) {
                    qty = parseInt($qtyInput.val()) || 1;
                    if (qty < 1) qty = 1;
                }
                var label = $checkbox.closest('label').text().trim();

                var itemTotal = price * qty;
                items.push({
                    label: label,
                    quantity: qty,
                    price: itemTotal
                });
                total += itemTotal;
            });

            // Calculate from pricing radios
            $('[data-type="pricing-radio"]:checked').each(function() {
                var $radio = $(this);
                var price = parseFloat($radio.data('price')) || 0;
                var qty = 1;
                var $qtyInput = $radio.closest('.wpuf-pricing-radio-item').find('.wpuf-pricing-quantity:not(:disabled)');
                if ($qtyInput.length && $qtyInput.is(':visible')) {
                    qty = parseInt($qtyInput.val()) || 1;
                    if (qty < 1) qty = 1;
                }
                var label = $radio.closest('label').text().trim();

                var itemTotal = price * qty;
                items.push({
                    label: label,
                    quantity: qty,
                    price: itemTotal
                });
                total += itemTotal;
            });

            // Calculate from pricing dropdowns
            $('[data-type="pricing-select"]').each(function() {
                var $select = $(this);
                var $option = $select.find('option:selected');
                var optionVal = $option.val();

                if (!optionVal || optionVal === '-1' || optionVal === '') {
                    return;
                }

                var price = parseFloat($option.data('price')) || 0;
                var qty = 1;
                var $qtyInput = $select.closest('.wpuf-fields').find('.wpuf-pricing-quantity');
                if ($qtyInput.length && $qtyInput.is(':visible')) {
                    qty = parseInt($qtyInput.val()) || 1;
                    if (qty < 1) qty = 1;
                }
                var label = $option.text().trim();

                var itemTotal = price * qty;
                items.push({
                    label: label,
                    quantity: qty,
                    price: itemTotal
                });
                total += itemTotal;
            });

            // Calculate from pricing multiselects
            $('[data-type="pricing-multiselect"]').each(function() {
                var $select = $(this);
                $select.find('option:selected').each(function() {
                    var $option = $(this);
                    var value = $option.val();

                    if (!value || value === '') {
                        return;
                    }

                    var price = parseFloat($option.data('price')) || 0;
                    var qty = 1;
                    var $qtyInput = $select.closest('.wpuf-fields').find('[name*="_qty[' + value + ']"]');
                    if ($qtyInput.length && $qtyInput.is(':visible')) {
                        qty = parseInt($qtyInput.val()) || 1;
                        if (qty < 1) qty = 1;
                    }
                    var label = $option.text().trim();

                    var itemTotal = price * qty;
                    items.push({
                        label: label,
                        quantity: qty,
                        price: itemTotal
                    });
                    total += itemTotal;
                });
            });

            // Update cart total display
            this.updateCartTotal(total, items);
        },

        updateCartTotal: function(total, items) {
            var $amount = $('.wpuf-cart-total-amount');
            var $hidden = $('.wpuf-cart-total-hidden');

            if ($amount.length) {
                $amount.text(total.toFixed(2));
            }
            if ($hidden.length) {
                $hidden.val(total.toFixed(2));
            }

            // Update cart summary table if exists
            var $cartItems = $('.wpuf-cart-items');
            if ($cartItems.length) {
                $cartItems.empty();

                if (items.length === 0) {
                    $cartItems.html('<tr class="wpuf-cart-empty"><td colspan="3" style="text-align: center; padding: 15px; color: #999;">No items selected</td></tr>');
                } else {
                    items.forEach(function(item) {
                        var row = '<tr>' +
                            '<td style="padding: 8px;">' + item.label + '</td>' +
                            '<td style="text-align: center; padding: 8px;">' + item.quantity + '</td>' +
                            '<td style="text-align: right; padding: 8px;">' + item.price.toFixed(2) + '</td>' +
                            '</tr>';
                        $cartItems.append(row);
                    });
                }
            }
        }
    };

    // Initialize on document ready
    $(document).ready(function() {
        WPUF_Pricing.init();
    });

    // Also initialize after WPUF form loads
    $(document).on('wpuf-form-loaded', function() {
        WPUF_Pricing.init();
    });

    // Initialize after a short delay as fallback
    $(window).on('load', function() {
        setTimeout(function() {
            if (!WPUF_Pricing.initialized) {
                WPUF_Pricing.init();
            } else {
                // Recalculate if already initialized
                WPUF_Pricing.calculateTotal();
            }
        }, 500);
    });

})(jQuery);
