(function ($) {
    'use strict';

    $(document).ready(function () {

        var $depositRadios = $('input[name="deposit-mode"]');
        var $customTextContainer = $('#bdfw-deposit-notice-custom-text');
        var $depositNotice = $('.deposit-notice');
        var $depositsWrapper = $('.deposits-frontend-wrapper');

        // If there are no deposit radios, there's nothing to do.
        if (!$depositRadios.length) {
            return;
        }

        /**
         * Toggle the custom text container in product page
         * @returns {void}
         */
        function toggleCustomText() {
            // Only run if the custom text container exists on the page
            if ($customTextContainer.length) {
                var selectedMode = $('input[name="deposit-mode"]:checked').val();
                if (selectedMode === 'check_deposit') {
                    $customTextContainer.slideDown();
                } else {
                    $customTextContainer.slideUp();
                }
            }
        }

        /**
         * Update the deposit info for a variation
         * @param {number} variationId - The variation ID
         * @returns {void}
         */
        function updateDepositInfo(variationId) {
            if (!variationId) {
                return;
            }

            $.ajax({
                url: bdfw_ajax.ajax_url,
                type: 'POST',
                data: {
                    action: 'bdfwbp_get_variation_deposit_info',
                    nonce: bdfw_ajax.nonce,
                    variation_id: variationId
                },
                beforeSend: function () {
                    $depositsWrapper.addClass('loading');
                },
                success: function (response) {
                    if (response.success && response.data) {
                        // Update deposit notice text
                        if ($depositNotice.length && response.data.deposit_text) {
                            $depositNotice.html(response.data.deposit_text);
                        }

                        // Update custom text if exists
                        if ($customTextContainer.length && response.data.custom_text) {
                            $customTextContainer.html(response.data.custom_text);
                        }

                        // Update deposit value for calculations
                        if (response.data.deposit_amount) {
                            $depositsWrapper.data('deposit-amount', response.data.deposit_amount);
                        }
                    }
                },
                complete: function () {
                    $depositsWrapper.removeClass('loading');
                }
            });
        }

        // Listen for variation changes
        $(document).on('found_variation', function (event, variation) {
            if (variation && variation.variation_id) {
                updateDepositInfo(variation.variation_id);
            }
        });

        // Listen for variation changes on variation select
        $('select.variation_id').on('change', function () {
            var variationId = $(this).val();
            if (variationId) {
                updateDepositInfo(variationId);
            }
        });

        // Escuchar los cambios en los botones de radio
        $depositRadios.on('change', function () {
            // First, toggle the text visibility
            toggleCustomText();

            // Then, do the AJAX call from the original script
            var $this = $(this);
            var selected_value = $this.val();
            var $addToCartButton = $('button.single_add_to_cart_button');
            var product_id = $addToCartButton.val();

            if (!product_id) {
                product_id = $('input[name="product_id"]').val() || $('input[name="variation_id"]').val();
            }

            if (!product_id) {
                console.error('Bright Deposits: No se pudo encontrar el ID del producto.');
                return;
            }

            $.ajax({
                url: bdfw_ajax.ajax_url,
                type: 'POST',
                data: {
                    action: 'bdfwbp_deposit_cart_btn',
                    nonce: bdfw_ajax.nonce,
                    product_id: product_id,
                    deposit_enabled: (selected_value === 'check_deposit') ? 'yes' : 'no'
                },
                beforeSend: function () {
                    $depositRadios.prop('disabled', true);
                },
                success: function (response) {
                    if (!response.success) {
                        console.error('Bright Deposits: La llamada AJAX falló.', response.data);
                    }
                },
                complete: function () {
                    $depositRadios.prop('disabled', false);
                }
            });
        });

        // Disparar el evento al cargar la página para establecer el valor inicial en la sesión
        // y para mostrar/ocultar el texto personalizado.
        $('input[name="deposit-mode"]:checked').trigger('change');

    });
})(jQuery);