;(function($) {

    function getActiveWrapperFromElement($element) {
        if (!$element || !$element.length) {
            return jQuery();
        }
        return $element.closest('.wsww-shortcode-wrapper');
    }

    function ensureWrapperPopupVisibility($wrapper) {
        if (!$wrapper || !$wrapper.length) {
            return;
        }
        var $spinnerWrapper = $wrapper.find('.spinner-wrapper').first();
        $wrapper.find('.email-wrapper, .description, #spinForm, #chart').removeClass('hide').css({
            'display': '',
            'visibility': ''
        });
        $wrapper.find('#spin-result-message').addClass('hide').css({
            'display': '',
            'visibility': ''
        });
        $spinnerWrapper.css({
            'display': '',
            'visibility': '',
            'opacity': ''
        });
    }

    function setSpinFormPendingState($form, isPending) {
        if (!$form || !$form.length) {
            return;
        }

        var $fields = $form.find('input, select, textarea, button');
        $fields.prop('disabled', isPending);

        var $submitButton = $form.find('.wsww-from-button');
        if ($submitButton.length) {
            $submitButton.toggleClass('is-loading', isPending);
        }
    }

    function setAwaitingSpinCompletion($form, isAwaiting) {
        if (!$form || !$form.length) {
            return;
        }

        $form.data('wswwAwaitingSpinCompletion', !!isAwaiting);
    }

    function enableSpinFormSubmitButton($scope) {
        if ($scope && $scope.length) {
            $scope.find('#spinForm .wsww-from-button, .wsww-from-button').prop('disabled', false);
            return;
        }
        $('#spinForm .wsww-from-button').prop('disabled', false);
    }

    function handleSpinComplete() {
        var $form = $('.wsww-shortcode-wrapper #spinForm').first();
        if (!$form.length) {
            return;
        }

        if ($form.data('wswwAwaitingSpinCompletion')) {
            setAwaitingSpinCompletion($form, false);
            setSpinFormPendingState($form, false);
            enableSpinFormSubmitButton(getActiveWrapperFromElement($form));
        }
    }

    function attachSpinEmailListener() {
        var $emailField = $('.spin-email');
        $emailField.off('focus.spinStatus').on('focus.spinStatus', function () {
            var $wrapper = getActiveWrapperFromElement(jQuery(this));
            ($wrapper.length ? $wrapper.find('.status-msg') : $('.status-msg')).html('');
        });

        $emailField.off('input.spinStatus').on('input.spinStatus', function () {
            var $wrapper = getActiveWrapperFromElement(jQuery(this));
            ($wrapper.length ? $wrapper.find('.status-msg') : $('.status-msg')).html('');
            enableSpinFormSubmitButton($wrapper);
        });
    }

    attachSpinEmailListener();
    $(document).on('wsww_spin_complete', handleSpinComplete);

    /**
     * Move spin modals to document.body so they are not trapped under theme headers
     * (Avada/Fusion and others use high z-index on .fusion-header inside transformed/stacking parents).
     */
    function relocateSpinModalsToBody() {
        var modals = document.querySelectorAll('.modal[id^="wsww-spin-modal-"]');
        modals.forEach(function (el) {
            if (el.parentNode !== document.body) {
                document.body.appendChild(el);
            }
        });
    }

    /** While open, body gets a class so CSS can pull theme headers below our modal (Avada etc.). */
    function setWswwSpinModalLayerActive(isActive) {
        if (isActive) {
            document.body.classList.add('wsww-spin-modal-active');
        } else {
            document.body.classList.remove('wsww-spin-modal-active');
        }
    }

    jQuery(document).on('show.bs.modal', '.modal[id^="wsww-spin-modal-"]', function () {
        setWswwSpinModalLayerActive(true);
    });
    jQuery(document).on('hidden.bs.modal', '.modal[id^="wsww-spin-modal-"]', function () {
        setWswwSpinModalLayerActive(false);
    });

    function closeManualModal(modalElement) {
        if (!modalElement) {
            return;
        }

        var modalId = modalElement.getAttribute('id');
        var $modal = jQuery(modalElement);
        var $wrapper = $modal.find('.wsww-shortcode-wrapper').first();
        var $spinnerWrapper = $wrapper.find('.spinner-wrapper').first();

        $modal.removeClass('show wsww-manual-modal-open').css('display', '');
        $modal.attr('aria-hidden', 'true').removeAttr('aria-modal');
        jQuery('body').removeClass('modal-open wsww-spinner-open').css('padding-right', '');
        setWswwSpinModalLayerActive(false);

        var $manualBackdrops = modalId
            ? jQuery('.wsww-manual-modal-backdrop[data-modal-id="' + modalId + '"]')
            : jQuery('.wsww-manual-modal-backdrop');
        $manualBackdrops.removeClass('show');
        setTimeout(function () {
            $manualBackdrops.remove();
        }, 220);

        if ($wrapper.length) {
            $wrapper.removeClass('spinner-open');
        }
        if ($spinnerWrapper.length) {
            $spinnerWrapper.removeClass('spinner-open appear-on-popup');
        }
        ensureWrapperPopupVisibility($wrapper);
    }

    function openManualModal(modalElement, $wrapper, $spinnerWrapper) {
        if (!modalElement) {
            return;
        }

        var modalId = modalElement.getAttribute('id');
        var $modal = jQuery(modalElement);

        jQuery('.wsww-manual-modal-backdrop').remove();
        var $backdrop = jQuery('<div class="modal-backdrop fade wsww-manual-modal-backdrop"></div>');
        if (modalId) {
            $backdrop.attr('data-modal-id', modalId);
        }
        jQuery('body').append($backdrop);
        requestAnimationFrame(function () {
            $backdrop.addClass('show');
        });

        jQuery('body').addClass('modal-open wsww-spinner-open');
        setWswwSpinModalLayerActive(true);

        if ($wrapper && $wrapper.length) {
            $wrapper.addClass('spinner-open');
        }
        if ($spinnerWrapper && $spinnerWrapper.length) {
            $spinnerWrapper.addClass('spinner-open appear-on-popup');
        }
        ensureWrapperPopupVisibility($wrapper);

        $modal.css('display', 'block').removeAttr('aria-hidden').attr({
            'aria-modal': 'true',
            'role': 'dialog'
        }).addClass('show wsww-manual-modal-open');
    }

    /**
     * Function to open spinner (reusable for button clicks and auto-trigger)
     */
    function openSpinner(spinId) {
        var hasSpinId = spinId !== undefined && spinId !== null && spinId !== '';
        var wrapper = hasSpinId
            ? jQuery('.wsww-shortcode-wrapper[data-spin="' + spinId + '"]').first()
            : jQuery('.wsww-shortcode-wrapper[data-modal-id]').first();

        if (!wrapper.length && !hasSpinId) {
            wrapper = jQuery('.wsww-shortcode-wrapper').first();
        }

        if (!wrapper.length) {
            console.warn('Spinner wrapper container not found!');
            return;
        }

        // Find the target spinner wrapper inside the resolved shortcode wrapper.
        let spinner_wrapper = wrapper.find('.spinner-wrapper').first();
        if (spinner_wrapper.length === 0) {
            console.warn('Spinner wrapper not found!');
            return;
        }

        let modal_id = wrapper.data('modal-id');
        var isPopupMode = spinner_wrapper.hasClass('popup') || !!modal_id;

        // Avoid unsafe popup fallback only when multiple popup instances exist.
        if (isPopupMode && !hasSpinId) {
            var popupWrappers = jQuery('.wsww-shortcode-wrapper[data-modal-id]');
            if (popupWrappers.length > 1) {
                console.warn('Popup open aborted: missing spin id with multiple popup instances.');
                return;
            }
        }

        // Reset any previous hidden/result state so popup always opens with wheel + form visible.
        ensureWrapperPopupVisibility(wrapper);
        
        // For popup mode, use Bootstrap modal when API is available.
        if (modal_id) {
            relocateSpinModalsToBody();
            let modalElement = document.getElementById(modal_id);
            var hasBootstrapModalApi = !!(window.bootstrap && typeof window.bootstrap.Modal === 'function');
            if (modalElement && hasBootstrapModalApi) {
                // Keep compatibility with CSS that relies on spinner-open class.
                wrapper.addClass('spinner-open');
                spinner_wrapper.addClass('spinner-open appear-on-popup');
                let modal = new window.bootstrap.Modal(modalElement, {
                    backdrop: 'static',
                    keyboard: false
                });
                jQuery(modalElement).off('shown.bs.modal.wsww').on('shown.bs.modal.wsww', function() {
                    ensureWrapperPopupVisibility(wrapper);
                });
                modal.show();
                return;
            }
            if (modalElement) {
                openManualModal(modalElement, wrapper, spinner_wrapper);
                return;
            }
            console.warn('Popup modal element not found for id:', modal_id);
            return;
        }
        
        // Fallback for non-popup modes or if Bootstrap is not available
        // For popup mode without Bootstrap, show the wrapper
        if (wrapper.hasClass('wsww-shortcode-wrapper-center-button-click') || 
            wrapper.hasClass('wsww-shortcode-wrapper-center-auto')) {
            wrapper.addClass('spinner-open');
        }

        // Create overlay if it doesn't exist - insert it BEFORE spinner-wrapper so CSS sibling selector works
        let overlay = jQuery('.wsww-overlay');
        if (overlay.length === 0) {
            overlay = jQuery("<div class='wsww-overlay'></div>");
            spinner_wrapper.before(overlay);
        }
        
        // Activate overlay immediately (this makes it visible regardless of sibling selector)
        overlay.addClass('active');
        overlay.css({
            'position': 'fixed',
            'top': '0',
            'left': '0',
            'width': '100%',
            'height': '100%',
            'background': 'rgba(0, 0, 0, 0.6)',
            'z-index': '9998'
        });
        
        // Prevent body scroll when spinner is open
        jQuery('body').addClass('wsww-spinner-open');
        
        // Add appropriate animation class based on position
        if (spinner_wrapper.hasClass('left')) {
            spinner_wrapper.addClass('appear-from-left');
            setTimeout(function () {
                if (typeof window.wswwFitSidebarWheel === 'function') {
                    window.wswwFitSidebarWheel();
                }
            }, 480);
        } else if (spinner_wrapper.hasClass('right')) {
            spinner_wrapper.addClass('appear-from-right');
            setTimeout(function () {
                if (typeof window.wswwFitSidebarWheel === 'function') {
                    window.wswwFitSidebarWheel();
                }
            }, 480);
        } else if (spinner_wrapper.hasClass('popup')) {
            // For popup mode, add spinner-open class to show it
            spinner_wrapper.addClass('spinner-open');
            spinner_wrapper.addClass('appear-on-popup');
            spinner_wrapper.css('display', 'flex');
        } else {
            spinner_wrapper.addClass('appear-on-popup');
        }
        
        // Also add spinner-open class for compatibility
        spinner_wrapper.addClass('spinner-open');
    }

    // Make openSpinner available globally for auto-trigger
    window.wswwOpenSpinner = openSpinner;

    // Manual modal fallback close handlers.
    jQuery(document).on('click', '.wsww-manual-modal-backdrop', function() {
        var modalId = jQuery(this).attr('data-modal-id');
        if (!modalId) {
            return;
        }
        var modalElement = document.getElementById(modalId);
        if (modalElement) {
            closeManualModal(modalElement);
        }
    });

    jQuery(document).on('click', '.modal[id^="wsww-spin-modal-"] [data-bs-dismiss="modal"]', function(e) {
        var modalElement = this.closest('.modal');
        if (modalElement && modalElement.classList.contains('wsww-manual-modal-open')) {
            e.preventDefault();
            closeManualModal(modalElement);
        }
    });

    jQuery(document).on('keydown', function(e) {
        if (e.key !== 'Escape') {
            return;
        }
        var modalElement = document.querySelector('.modal.wsww-manual-modal-open');
        if (modalElement) {
            closeManualModal(modalElement);
        }
    });

    // Use event delegation for dynamically added forms
    $(document).on('submit', '#spinForm', function(e) {
        e.preventDefault();

        var $form = $(this);
        var $wrapper = getActiveWrapperFromElement($form);
        var $submitButton = $form.find('.wsww-from-button');

        if ($submitButton.hasClass('is-loading')) {
            return;
        }

        var data = $form.serialize();
        // Ensure action is present
        if (data.indexOf('action=') === -1) {
            data += '&action=wsww_email_enquiry';
        }
        // Add AJAX nonce as per WordPress AJAX guide (replaces form _wpnonce)
        if (typeof wswwSpinObj !== 'undefined' && wswwSpinObj.nonce) {
            // Remove _wpnonce if present and add _ajax_nonce
            data = data.replace(/[&?]_wpnonce=[^&]*/g, '');
            data += '&_ajax_nonce=' + encodeURIComponent(wswwSpinObj.nonce);
        }

        setSpinFormPendingState($form, true);

        // Check if wswwSpinObj is defined
        if (typeof wswwSpinObj === 'undefined') {
            console.error('[DEBUG] wswwSpinObj is not defined! Make sure wsww-ajax-script is enqueued and localized.');
            setSpinFormPendingState($form, false);
            return;
        }

        $.post(wswwSpinObj.ajaxurl, data, function(response) {
                if (!response || !response.success || !response.data) {
                    console.error('[DEBUG] Invalid response:', response);
                    setSpinFormPendingState($form, false);
                    setAwaitingSpinCompletion($form, false);
                    return;
                }

                var responseData = response.data;

                // Required wait time
                var set_time = parseInt(responseData.display_after_same_email, 10) || 0;
                var set_sec = set_time * 60;

                // last_entry value from backend
                var last_entry = responseData.last_entry;

                // Convert last_entry properly
                var already_waited = 0;

                already_waited = parseInt(last_entry, 10) || 0;

                // Remaining wait time
                var waitTime = set_sec - already_waited;

                if (waitTime < 0) {
                    waitTime = 0;
                }

                var minutes = Math.floor(waitTime / 60);
                var seconds = waitTime % 60;

                // Condition: user must wait
                if (last_entry != 0 && waitTime > 0) {

                    ($wrapper.length ? $wrapper.find('.status-msg') : $('.status-msg')).html(
                        'You have to wait ' + minutes + ' minute' + (minutes !== 1 ? 's' : '') +
                        ' and ' + seconds + ' second' + (seconds !== 1 ? 's' : '') +
                        ' before trying again.'
                    );

                    // Keep the form interactive: just show the message and
                    // clear any loading/disabled state so the user can edit fields.
                    setAwaitingSpinCompletion($form, false);
                    setSpinFormPendingState($form, false);

                } else {

                // User can spin
                    var spinCount = (parseInt(responseData.email_rows, 10) || 0) + 1;

                    var $sentForm = ($wrapper.length ? $wrapper.find('#spinFormSent') : $('#spinFormSent')).first();
                    $sentForm.find('#spin-validate-email').val(responseData.email || '');
                    $sentForm.find('#spin-validate-phone').val(responseData.phone || '');
                    $sentForm.find('#spin-validate-name').val(responseData.name || '');

                // Propagate marketing consent (if present) into the hidden submission form.
                var consentChecked = $form.find('input[name="wsww_marketing_consent"]').is(':checked') ? '1' : '';
                $sentForm.find('#wsww-marketing-consent').val(consentChecked);

                    setAwaitingSpinCompletion($form, true);
                    
                    // Get spinBtn from the page (defined in the template)
                    var spinBtn = ($wrapper.length ? $wrapper.find('.spin-btn') : jQuery('.spin-btn'));
                    if (spinBtn.length > 0) {
                        spinBtn.off('click').on('click', function() {
                            // Check if spin function is available (defined in template)
                            if (typeof spin === 'function') {
                                spin(spinCount);
                            } else {
                                console.error('[DEBUG] spin function is not defined');
                            }
                        });
                    }

                    // Trigger the spin button click
                    spinBtn.first().trigger('click');
                }

            })
            .fail(function(jqXHR, textStatus, errorThrown) {
                setAwaitingSpinCompletion($form, false);
                setSpinFormPendingState($form, false);
                console.error('[DEBUG] spinForm AJAX error:', textStatus, errorThrown, jqXHR.responseText);
            });

        });

    $(document).on('submit', '#spinFormSent', function(e) {
        e.preventDefault();

        var $formSent = $(this);
        var $wrapper = getActiveWrapperFromElement($formSent);
        var data = $formSent.serialize();
        // Ensure action is present
        if (data.indexOf('action=') === -1) {
            data += '&action=wsww_spin_win';
        }
        
        // Check if wswwSpinObj is defined
        if (typeof wswwSpinObj === 'undefined') {
            console.error('[DEBUG] wswwSpinObj is not defined! Make sure wsww-ajax-script is enqueued and localized.');
            return;
        }
        
        // Add AJAX nonce as per WordPress AJAX guide (replaces form _wpnonce)
        if (wswwSpinObj.spinWinNonce) {
            // Remove _wpnonce if present and add _ajax_nonce
            data = data.replace(/[&?]_wpnonce=[^&]*/g, '');
            data += '&_ajax_nonce=' + encodeURIComponent(wswwSpinObj.spinWinNonce);
        }

        // Show loader while we wait for the win/loss result
        var $loader = ($wrapper.length ? $wrapper.find('.spin-ajax-loader') : $('.spin-ajax-loader')).first();
        $loader.addClass('show').show();

        // Debug: log loader and parent layout info (to compare local vs live)
        try {
            var $emailWrapper = $loader.closest('.email-wrapper');
            var loaderRect = $loader[0] ? $loader[0].getBoundingClientRect() : null;
            var wrapperRect = $emailWrapper[0] ? $emailWrapper[0].getBoundingClientRect() : null;

            console.group('[WSWW DEBUG] spin-ajax-loader layout');
            console.log('window.innerWidth/innerHeight:', window.innerWidth, window.innerHeight);
            console.log('loader exists:', !!$loader.length);
            console.log('email-wrapper exists:', !!$emailWrapper.length);
            console.log('loader CSS position:', $loader.css('position'));
            console.log('email-wrapper CSS position:', $emailWrapper.css('position'));
            console.log('loader classes:', $loader.attr('class'));
            console.log('spinner-wrapper classes:', ($wrapper.length ? $wrapper.find('.spinner-wrapper') : $('.spinner-wrapper')).attr('class'));
            if (loaderRect) {
                console.log('loader rect (top,left,width,height):', loaderRect.top, loaderRect.left, loaderRect.width, loaderRect.height);
            }
            if (wrapperRect) {
                console.log('email-wrapper rect (top,left,width,height):', wrapperRect.top, wrapperRect.left, wrapperRect.width, wrapperRect.height);
            }
            console.groupEnd();
        } catch (e) {
            console.warn('[WSWW DEBUG] error while logging loader layout:', e);
        }

        // Hide the visible form content (fields, button, status), but keep the
        // loader container itself visible in the middle of the form area.
        var $form = ($wrapper.length ? $wrapper.find('#spinForm') : $('#spinForm')).first();
        $form.find('.description').addClass('wsww-form-content-hidden');
        $form.find('.ff-field').addClass('wsww-form-content-hidden');
        $form.find('.wsww-from-button').addClass('wsww-form-content-hidden');
        $form.find('.status-msg').addClass('wsww-form-content-hidden');

        // Hide any existing result message while loading the new one
        var $inlineResult = ($wrapper.length ? $wrapper.find('#spin-result-message') : $('#spin-result-message')).first();
        $inlineResult.addClass('hide');

        function wswwInjectCouponUI(couponCode, applied) {
            couponCode = (couponCode || '').toString().trim();
            if (!couponCode) {
                return;
            }

            var $result = ($wrapper.length ? $wrapper.find('#spin-result-message') : $('#spin-result-message')).first();
            if (!$result.length) {
                return;
            }

            // If the win message contains the {coupon_code} tag, replace it inline.
            var $msg = $result.find('.spin-message');
            if ($msg.length) {
                var msgHtml = $msg.html();
                if (msgHtml && msgHtml.indexOf('{coupon_code}') !== -1) {
                    $msg.html(msgHtml.replace(/{coupon_code}/g, couponCode));
                }
            }

            // Avoid duplicating the coupon UI if AJAX fires twice.
            if ($result.find('.wsww-coupon-reward').length) {
                return;
            }

            var html = `
                <div class="wsww-coupon-reward" style="margin-top: 20px; padding: 20px 10px; background: #80808017; display: flex;flex-direction: column; align-content: center; align-items: center; border-radius: 10px; ">
                    <div style="font-weight: 600; margin-bottom: 6px; font-size: 20px; line-height: 1.2;">Coupon Code</div>
                    <div style="display:flex; gap:10px; align-items:center; flex-wrap:wrap;">
                        <code class="wsww-coupon-code" style="font-size: 16px; padding: 0px 10px; background: #fff; border: 1px solid #c3c4c7; border-radius: 6px;">${couponCode}</code>
                        <button type="button" class="wsww-tyl-btn wsww-from-button wsww-copy-coupon"  style="font-size: 14px; padding: 9.5px 10px;line-height: 16px;border-radius: 6px;" data-code="${couponCode}">Copy Code</button>
                    </div>
                </div>
            `;

            // Append to existing message block if present.
            var $msg = $result.find('.spin-message');
            if ($msg.length) {
                $msg.append(html);
            } else {
                $result.append(html);
            }
        }

        // Copy handler (event delegation).
        $(document).off('click.wswwCopyCoupon').on('click.wswwCopyCoupon', '.wsww-copy-coupon', function() {
            var code = $(this).data('code') || '';
            code = code.toString();
            var $btn = $(this);

            function markCopied() {
                var original = $btn.data('originalText');
                if (!original) {
                    original = $btn.text();
                    $btn.data('originalText', original);
                }
                $btn.text('Copied');
                setTimeout(function(){ $btn.text(original); }, 1200);
            }

            if (navigator.clipboard && window.isSecureContext) {
                navigator.clipboard.writeText(code).then(markCopied).catch(function(){});
            } else {
                // Fallback
                var $tmp = $('<textarea readonly></textarea>').css({ position: 'absolute', left: '-9999px', top: '0' }).val(code);
                $('body').append($tmp);
                $tmp[0].select();
                try { document.execCommand('copy'); markCopied(); } catch (e) {}
                $tmp.remove();
            }
        });

        $.post(wswwSpinObj.ajaxurl, data, function(response) {
            var responseData = response.data;
            function spinCookieGen(){
                var now = new Date();
                var hours = 24;
                now.setTime(now.getTime() + (hours * 60 * 60 * 1000));
                document.cookie = 'spinCookie=1;expires='+now.toUTCString()+';path=/';
            }

            if(response.success) {
                //reset form
                if ($form.length && $form[0]) {
                    $form[0].reset();
                }

                // Hide loader once the result is ready
                $loader.removeClass('show').hide();

                // Hide form after successful submission
                var $formDescription = $form.find('.description');
                
                // Hide the form and description
                $form.addClass('hide');
                if ($formDescription.length) {
                    $formDescription.addClass('hide');
                }
                
                // Always update the inline result using the backend-generated
                // message (which already includes the coupon code). We keep
                // the existing card/title structure created after the spin.
                if ($inlineResult.length) {
                    var messageHtml = (responseData && responseData.message) ? responseData.message : '';
                    var $msg = $inlineResult.find('.spin-message');

                    if ($msg.length && messageHtml) {
                        $msg.html(messageHtml);
                    } else if (messageHtml) {
                        $inlineResult.html(messageHtml);
                    }

                    $inlineResult.removeClass('hide').css({
                        'display': 'block',
                        'visibility': 'visible'
                    });
                }

                // If a coupon code was generated, display coupon code UI.
                try {
                    var couponCode = '';
                    if (responseData && responseData.inserted_data && responseData.inserted_data.coupon_code) {
                        couponCode = responseData.inserted_data.coupon_code;
                    } else if (responseData && responseData.coupon && responseData.coupon.code) {
                        couponCode = responseData.coupon.code;
                    }
                    var applied = false;
                    if (responseData && responseData.inserted_data && responseData.inserted_data.coupon_applied === 'yes') {
                        applied = true;
                    } else if (responseData && responseData.coupon && responseData.coupon.applied) {
                        applied = true;
                    }
                    wswwInjectCouponUI(couponCode, applied);
                } catch (e) {}

                // setTimeout(() => {
                //     location.reload();
                // }, 10000); //display the win card

               
            }
        })
        .fail(function(jqXHR, textStatus, errorThrown) {
            // Debug: log error
            console.error('[DEBUG] spinFormSent AJAX error:', textStatus, errorThrown, jqXHR.responseText);
            // Hide loader on error
            $loader.removeClass('show').hide();
        })
    }); //insert form

    // update winner form admin
    $('#WswwWinnerForm').on('submit', function(e) {
        e.preventDefault();

        var data = $(this).serialize();

        // Check if wswwSpinObj is defined
        if (typeof wswwSpinObj === 'undefined') {
            console.error('[DEBUG] wswwSpinObj is not defined! Make sure wsww-ajax-script is enqueued and localized.');
            return;
        }

        $.post(wswwSpinObj.ajaxurl, data, function(response) {
            //var responseData = response.data;
            if(response.success) {
                location.reload();
            }
        })
        .fail(function() {
            
        })
    }); //update winner form

    // Use event delegation to handle dynamically added buttons
    // Handle multiple selectors to catch all button variations
    // BUT: Don't prevent form submission if button is inside a form
    jQuery(document).on('click', '.btn-try-luck, .wsww-tyl-btn, .button-tigger-spin-card', function(e) {
        // If button is inside a form and is a submit button, let the form handle submission
        var $button = jQuery(this);
        var $form = $button.closest('form');
        
        if ($form.length > 0 && ($button.attr('type') === 'submit' || $button.hasClass('wsww-from-button'))) {
            // This is a form submit button - let the form submit handler take over
            // Don't prevent default, let the form submit naturally
            console.log('Submit button clicked inside form - allowing form submission');
            return true; // Allow default form submission
        }
        
        e.preventDefault();
        e.stopPropagation();
        
        console.log('Button clicked!', this);
        
        // Always show the Try your luck button
        jQuery('.btn-try-luck, .wsww-tyl-btn').removeClass('hide');

        // Use the reusable function to open spinner
        var spinId = $button.data('spin');
        if (!spinId) {
            var $targetWrapper = jQuery('.wsww-shortcode-wrapper').filter(function() {
                var modalId = jQuery(this).data('modal-id');
                return !!modalId;
            }).first();
            if ($targetWrapper.length) {
                spinId = $targetWrapper.data('spin');
            }
        }

        openSpinner(spinId);
    });
    
    // Also handle on document ready for immediate buttons
    jQuery(document).ready(function() {
        relocateSpinModalsToBody();

        // Always show the Try your luck button
        jQuery('.btn-try-luck, .wsww-tyl-btn').removeClass('hide');
        
        // Debug: Log button count
        var btnCount = jQuery('.btn-try-luck').length;
        console.log('Found ' + btnCount + ' .btn-try-luck button(s) on page load');
    });

})(jQuery);
