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

    var AdvanceCouponsHandler = function ($scope, $) {
        var $wrapper = $scope.find('.ua-coupon-list-wrapper');
        if ($wrapper.length === 0) {
            return;
        }

        var ajaxUrl = $wrapper.data('ajax-url');
        var nonce = $wrapper.data('nonce');
        var $message = $wrapper.find('.ua-coupon-message');
        
        // Debug logging
        console.log('UNLOCKAFE DEBUG: Handler initialized');
        console.log('UNLOCKAFE DEBUG: AJAX URL:', ajaxUrl);
        console.log('UNLOCKAFE DEBUG: Nonce:', nonce);

        // Apply Coupon - Handle click on apply coupon links
        $wrapper.on('click', '.ua-apply-coupon', function (e) {
            e.preventDefault();
            var $button = $(this);
            var couponCode = $button.data('coupon-code');

            if (!couponCode) {
                showMessage('Invalid coupon code.', 'error');
                return;
            }

            $wrapper.addClass('ua-loading');
            $button.text('Applying...');
            
            console.log('UNLOCKAFE DEBUG: Sending AJAX request');
            console.log('UNLOCKAFE DEBUG: Data:', {
                action: 'unlockafe_apply_coupon',
                coupon_code: couponCode,
                nonce: nonce
            });

            $.ajax({
                url: ajaxUrl,
                type: 'POST',
                data: {
                    action: 'unlockafe_apply_coupon',
                    coupon_code: couponCode,
                    nonce: nonce
                },
                success: function (response) {
                    console.log('UNLOCKAFE DEBUG: AJAX success response:', response);
                    if (response.success) {
                        showMessage(response.data.message, 'success');
                        updateAppliedCoupons();
                    } else {
                        showMessage(response.data.message, 'error');
                    }
                },
                error: function (xhr, status, error) {
                    console.log('UNLOCKAFE DEBUG: AJAX error:', xhr, status, error);
                    console.log('UNLOCKAFE DEBUG: Response text:', xhr.responseText);
                    showMessage('An unexpected error occurred.', 'error');
                },
                complete: function () {
                    $wrapper.removeClass('ua-loading');
                    $button.text('Apply Coupon');
                }
            });
        });

        // Remove Coupon
        $wrapper.on('click', '.ua-remove-coupon', function (e) {
            e.preventDefault();
            var $button = $(this);
            var couponCode = $button.data('coupon');

            $wrapper.addClass('ua-loading');

            $.ajax({
                url: ajaxUrl,
                type: 'POST',
                data: {
                    action: 'unlockafe_remove_coupon',
                    coupon_code: couponCode,
                    nonce: nonce
                },
                success: function (response) {
                    if (response.success) {
                        showMessage(response.data.message, 'success');
                        $button.closest('li').remove();
                    } else {
                        showMessage(response.data.message, 'error');
                    }
                },
                error: function () {
                    showMessage('An unexpected error occurred.', 'error');
                },
                complete: function () {
                    $wrapper.removeClass('ua-loading');
                }
            });
        });

        function showMessage(msg, type) {
            $message.html(msg).removeClass('success error').addClass(type).slideDown();
            setTimeout(function () {
                $message.slideUp();
            }, 5000);
        }

        function updateAppliedCoupons() {
            // Trigger WooCommerce cart and checkout updates instead of page reload
            $(document.body).trigger('update_checkout');
            $(document.body).trigger('wc_update_cart');
            
            // Also trigger cart fragments update for better UX
            if (typeof wc_cart_fragments_params !== 'undefined') {
                $(document.body).trigger('wc_fragment_refresh');
            }
        }
    };

    $(window).on('elementor/frontend/init', function () {
        elementorFrontend.hooks.addAction('frontend/element_ready/unlockafe-advance-coupons.default', AdvanceCouponsHandler);
    });

})(jQuery);