<?php declare(strict_types=1);

// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Provide a public-facing view for the plugin
 *
 * This file is used to markup the public-facing aspects of the plugin.
 *
 * @link       https://webequipe.com
 * @since      1.0.0
 *
 * @package    Webequipe_Spin_Win_Wheel
 * @subpackage Webequipe_Spin_Win_Wheel/public/partials
 */

// If this file is called directly, abort.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
?>

<!-- This file should primarily consist of HTML with a little bit of PHP. -->

<?php
global $webequipe_sww_spin_shortcode_id, $webequipe_sww_spin_default_id, $webequipe_sww_spin_default_min;

$webequipe_sww_spin_default_id = (int) get_option('wsww_setting_options_default');
$webequipe_sww_spin_default_min = (int) get_option('wsww_setting_options_minute');
$webequipe_sww_spin_shortcode_id = ($webequipe_sww_spin_default_id !== 0) ? $webequipe_sww_spin_default_id : (isset($data['id']) ? $data['id'] : 0);

if (empty($webequipe_sww_spin_shortcode_id)) {
    echo esc_html__( 'No shortcode ID found.', 'webequipe-spin-win-wheel' );
} else {
    $webequipe_sww_spin_spin = webequipe_sww_get_spin($webequipe_sww_spin_shortcode_id);
    if (empty($webequipe_sww_spin_spin) || is_wp_error($webequipe_sww_spin_spin)) {
        printf(
            '<div class="wsww-error" style="color:red;">%s</div>',
            wp_kses_post( sprintf(
                /* translators: %d: Spin wheel ID */
                __( '⚠️ Spin wheel not found for shortcode ID %d.', 'webequipe-spin-win-wheel' ),
                absint( $webequipe_sww_spin_shortcode_id )
            ) )
        );
        return;
    }
    // Store shortcode ID for wp_footer hook
    $GLOBALS['webequipe_sww_spin_shortcode_id'] = $webequipe_sww_spin_shortcode_id;
    add_action('wp_footer', function() {
        if (isset($GLOBALS['webequipe_sww_spin_shortcode_id'])) {
            webequipe_sww_spin_circle_markup($GLOBALS['webequipe_sww_spin_shortcode_id']);
        }
    }, 10);
    ?>

    <?php
    //check spin type
    if ('spin_button' === $webequipe_sww_spin_spin->spin_type && $webequipe_sww_spin_default_id === 0) { ?>

        <div>

            <?php
            if ( 'active' === $webequipe_sww_spin_spin->spin_status ) {

                $webequipe_sww_spin_classes = ['btn-try-luck', 'wsww-tyl-btn', 'button-tigger-spin-card'];

                // Decode JSON to array safely
                $webequipe_sww_spin_spin_display_setting = !empty($webequipe_sww_spin_spin->spin_display_setting)
                    ? json_decode($webequipe_sww_spin_spin->spin_display_setting, true)
                    : [];

                // Append classes based on settings
                if (in_array('laptop', $webequipe_sww_spin_spin_display_setting))
                    $webequipe_sww_spin_classes[] = 'show-laptop';
                if (in_array('tablet', $webequipe_sww_spin_spin_display_setting))
                    $webequipe_sww_spin_classes[] = 'show-tablet';
                if (in_array('mobile', $webequipe_sww_spin_spin_display_setting))
                    $webequipe_sww_spin_classes[] = 'show-mobile';

                $webequipe_sww_spin_button_classes = implode(' ', $webequipe_sww_spin_classes);
                ?>

                <button class="<?php echo esc_attr($webequipe_sww_spin_button_classes); ?>" data-spin="<?php echo esc_attr( (string) $webequipe_sww_spin_shortcode_id ); ?>" style="background: <?php echo esc_attr($webequipe_sww_spin_spin->initial_button_background_color); ?> !important;
            color: <?php echo esc_attr($webequipe_sww_spin_spin->initial_button_color); ?> !important;">
                    <span><?php echo esc_html($webequipe_sww_spin_spin->initial_button_text); ?></span>
                </button>
                <?php
            } else {
                printf(
                    '<div class="wsww-error wsww-spin-inactive-msg" style="color:#b91c1c;">%s</div>',
                    esc_html__( 'Spin wheel is not active.', 'webequipe-spin-win-wheel' )
                );
            } ?>

        </div>

    <?php } ?>

    <?php
    //add action call back 
    function webequipe_sww_spin_circle_markup($webequipe_sww_spin_shortcode_id)
    {

        include __DIR__ . '/spin-part/spin-variable.php';

        if ( 'active' === $webequipe_sww_spin_schedule_state ) {
            // Check if popup mode and use Bootstrap modal
            $is_popup_mode = ($webequipe_sww_spin_spin_position_class == "popup");
            $modal_id = 'wsww-spin-modal-' . (int) $webequipe_sww_spin_shortcode_id;
            ?>
            
            <?php if ($is_popup_mode): ?>
            <?php
            /*
             * Intentionally no `fade` on this .modal: Bootstrap’s .modal.fade opacity transition
             * fights theme CSS and our flex-based center layout (center popup looked broken / invisible).
             * Motion is handled in webequipe-spin-win-wheel-public.css (wswwModalDialogIn / wswwModalPanelIn).
             */
            ?>
            <!-- Bootstrap Modal for Popup Mode -->
            <div class="modal" id="<?php echo esc_attr($modal_id); ?>" tabindex="-1" aria-labelledby="<?php echo esc_attr($modal_id); ?>Label" aria-hidden="true" data-bs-backdrop="static" data-bs-keyboard="false">
                <div class="modal-dialog modal-xl modal-dialog-centered">
                    <div class="modal-content wsww-modal-content" style="box-shadow:none !important;border:none !important;">
                        <div class="modal-body p-0">
                            <button type="button" class="wsww-modal-close" data-bs-dismiss="modal" aria-label="Close">
                                &times;
                            </button>
            <?php endif; ?>

            <div class="wsww-shortcode-wrapper 
    <?php if ($webequipe_sww_spin_spin_position_class == "popup" && $webequipe_sww_spin_spin_type == "spin_auto") {
                        echo "wsww-shortcode-wrapper-center-auto";
                    } elseif ($webequipe_sww_spin_spin_position_class == "popup" && $webequipe_sww_spin_spin_type == "spin_button") {
                        echo "wsww-shortcode-wrapper-center-button-click";
                    } ?> " data-spin="<?php echo (int) $webequipe_sww_spin_shortcode_id; ?>" data-modal-id="<?php echo $is_popup_mode ? esc_attr($modal_id) : ''; ?>">

                <div
                    class="spinner-wrapper align-items-center <?php echo esc_attr($webequipe_sww_spin_spin_type_class); ?> <?php echo esc_attr($webequipe_sww_spin_spin_position_class); ?>">
                    <!-- Close button for all modes except popup (popup uses Bootstrap modal close button) -->
                    <?php if (!$is_popup_mode): ?>
                    <div class="spin-close">
                        <div>
                            <svg viewBox="0 0 365.71733 365" xmlns="http://www.w3.org/2000/svg">
                                <g fill="var(--card_color)">
                                    <path
                                        d="m356.339844 296.347656-286.613282-286.613281c-12.5-12.5-32.765624-12.5-45.246093 0l-15.105469 15.082031c-12.5 12.503906-12.5 32.769532 0 45.25l286.613281 286.613282c12.503907 12.5 32.769531 12.5 45.25 0l15.082031-15.082032c12.523438-12.480468 12.523438-32.75.019532-45.25zm0 0" />
                                    <path
                                        d="m295.988281 9.734375-286.613281 286.613281c-12.5 12.5-12.5 32.769532 0 45.25l15.082031 15.082032c12.503907 12.5 32.769531 12.5 45.25 0l286.632813-286.59375c12.503906-12.5 12.503906-32.765626 0-45.246094l-15.082032-15.082032c-12.5-12.523437-32.765624-12.523437-45.269531-.023437zm0 0" />
                                </g>
                            </svg>
                        </div>
                    </div>
                    <?php endif; ?>
                    <?php
                    // Popup/center modal needs flex at all desktop/tablet widths (d-xxl-flex only kicks in at 1400px).
                    $webequipe_sww_w100_flex_class = $is_popup_mode ? 'd-flex' : 'd-xxl-flex';
                    ?>
                    <div
                        class="w-100 <?php echo esc_attr( $webequipe_sww_w100_flex_class ); ?> align-items-center p-2 p-md-0 template-<?php echo esc_attr($webequipe_sww_spin_spin->template_setting); ?>">

                        <?php if (in_array($webequipe_sww_spin_spin_position_class, ['left', 'right'])): ?>
                            <!-- Left/Right mode: Use separate containers with equal side spacing -->
                            <div class="wsww-chart-container">
                                <div id="chart" data-chart="1"></div>
                            </div>
                            <div class="wsww-form-container">
                                <div
                                    class="email-wrapper form-alignment-<?php echo esc_attr($webequipe_sww_spin_from_design_alinment); ?>">
                        <?php else: ?>
                            <!-- Popup/Inline mode: Keep original structure -->
                            <div id="chart" data-chart="1"></div>
                            <div
                                class="email-wrapper form-alignment-<?php echo esc_attr($webequipe_sww_spin_from_design_alinment); ?>">
                        <?php endif; ?>
                            <?php
                            // Global Mailchimp settings for consent checkbox.
                            $wsww_mailchimp_settings = [];
                            if ( class_exists( '\Webequipe\SpinWinWheel\Mailchimp' ) ) {
                                $wsww_mailchimp_settings = \Webequipe\SpinWinWheel\Mailchimp::get_settings();
                            }

                            // Show consent checkbox whenever consent is enabled in settings.
                            $wsww_mailchimp_consent_enabled = ! empty( $wsww_mailchimp_settings['consent_enabled'] );
                            $wsww_mailchimp_consent_text    = isset( $wsww_mailchimp_settings['consent_text'] ) && '' !== $wsww_mailchimp_settings['consent_text']
                                ? $wsww_mailchimp_settings['consent_text']
                                : __( 'I agree to receive promotional emails.', 'webequipe-spin-win-wheel' );
                            ?>

                            <form id="spinForm" method="post" action="">
                                <div class="description">
                                    <h3 class=""><?php echo esc_html($webequipe_sww_spin_spin_title); ?></h3>
                                    <p><?php echo esc_html($webequipe_sww_spin_spin_description); ?></p>
                                </div>

                                <?php if (in_array('name_field', $webequipe_sww_spin_display_fields)) { ?>
                                    <div>
                                        <!-- <div class="ff-label">Name:</div> -->
                                        <input type="text" name="name" class="ff-field" placeholder="Your Name" required>
                                    </div>
                                <?php } ?>

                                <?php if (in_array('email_field', $webequipe_sww_spin_display_fields)) { ?>
                                    <div>
                                        <!-- <div class="ff-label">Email:</div> -->
                                        <input type="email" name="email" class="spin-email ff-field" placeholder="Your Email" required>

                                    </div>
                                <?php } ?>
                                <?php if (in_array('mobile_field', $webequipe_sww_spin_display_fields)) { ?>
                                    <div>
                                        <!-- <div class="ff-label">Phone:</div> -->
                                        <input type="text" name="phone" placeholder="Your Phone" class="ff-field" required>
                                    </div>
                                <?php } ?>

                                <?php if ( $wsww_mailchimp_consent_enabled ) : ?>
                                    <div class="wsww-consent-wrapper">
                                        <label class="wsww-consent-label">
                                            <input type="checkbox"
                                                name="wsww_marketing_consent"
                                                class="wsww-marketing-consent"
                                                value="1"
                                                required
                                            />
                                            <span><?php echo esc_html( $wsww_mailchimp_consent_text ); ?></span>
                                        </label>
                                    </div>
                                <?php endif; ?>

                               

                                <?php wp_nonce_field('wsww-email-enquiry-form'); ?>
                                <input type="hidden" name="action" value="wsww_email_enquiry">
                                <input type="hidden" name="display_after_same_email"
                                    value="<?php echo (int) $webequipe_sww_spin_display_after_same_email; ?>">

                                <input type="hidden" name="send_email"
                                    value="<?php echo esc_attr($webequipe_sww_spin_send_email); ?>">
                                <input type="hidden" name="from_name"
                                    value="<?php echo esc_attr($webequipe_sww_spin_from_name); ?>">
                                <input type="hidden" name="from_address"
                                    value="<?php echo esc_attr($webequipe_sww_spin_from_address); ?>">
                                <input type="hidden" name="from_subject"
                                    value="<?php echo esc_attr($webequipe_sww_spin_from_subject); ?>">
                                <input type="hidden" name="from_message"
                                    value="<?php echo esc_attr($webequipe_sww_spin_from_message); ?>">
                                <input type="hidden" name="admin_geting_email"
                                    value="<?php echo esc_attr($webequipe_sww_spin_admin_geting_email); ?>">

                                <button type="submit"
                                    class="wsww-tyl-btn wsww-from-button"><?php echo esc_html($webequipe_sww_spin_from_button_text); ?></button>
                                <div class="spin-btn hide">Click spin</div>
                                <div class="status-msg"></div>

                                <div class="spin-ajax-loader">
                                    <img src="<?php echo esc_url(trailingslashit(WEBEQUIPE_SPIN_WIN_WHEEL_ASSETS)); ?>img/preloader.gif"
                                        alt="ajax loader">
                                </div>
                            </form>

                            <div id="spin-result-message" class="spin-result-message hide"></div>

                        <?php if (in_array($webequipe_sww_spin_spin_position_class, ['left', 'right'])): ?>
                            </div>
                            </div>
                        <?php endif; ?>

                            <div class="hide">
                                <form id="spinFormSent" method="post" action="">
                                    <input type="number" name="display_after_same_email"
                                        value="<?php echo (int) $webequipe_sww_spin_display_after_same_email; ?>">
                                    <input type="text" name="send_email"
                                        value="<?php echo esc_attr($webequipe_sww_spin_send_email); ?>">
                                    <input type="text" name="from_name"
                                        value="<?php echo esc_attr($webequipe_sww_spin_from_name); ?>">
                                    <input type="text" name="from_address"
                                        value="<?php echo esc_attr($webequipe_sww_spin_from_address); ?>">
                                    <input type="text" name="from_subject"
                                        value="<?php echo esc_attr($webequipe_sww_spin_from_subject); ?>">
                                    <input type="text" name="from_message"
                                        value="<?php echo esc_attr($webequipe_sww_spin_from_message); ?>">
                                    <input type="text" name="admin_geting_email"
                                        value="<?php echo esc_attr($webequipe_sww_spin_admin_geting_email); ?>">


                                    <input type="email" name="email" id="spin-validate-email" value="">
                                    <input type="text" name="phone" id="spin-validate-phone" value="">
                                    <input type="text" name="name" id="spin-validate-name" value="">
                                    <input type="text" name="spin_label" id="spin-label" value="">
                                    <input type="text" name="is_win" id="is-win" value="">
                                    <input type="text" name="spin_value" id="spin-value" value="">
                                    <input type="text" name="page_url" id="page-url" readonly value="<?php
                                    $host = isset($_SERVER['HTTP_HOST']) ? sanitize_text_field(wp_unslash($_SERVER['HTTP_HOST'])) : '';
                                    $uri = isset($_SERVER['REQUEST_URI']) ? sanitize_text_field(wp_unslash($_SERVER['REQUEST_URI'])) : '';
                                    $scheme = is_ssl() ? 'https://' : 'http://';
                                    echo esc_url($scheme . $host . $uri);
                                    ?>">
                                    <input type="text" name="spin_id" id="page-url" readonly
                                        value="<?php echo (int) $webequipe_sww_spin_spin_id; ?>">

                                    <input type="text" name="wsww_marketing_consent" id="wsww-marketing-consent" value="">

                                    <?php wp_nonce_field('wsww-spin-win-form'); ?>
                                    <input type="hidden" name="action" value="wsww_spin_win">

                                    <button type="submit" id="spin-submit-btn"></button>
                                </form>
                            </div>
                        </div>

                    </div>

                </div>


            </div>
            
            <?php if ($is_popup_mode): ?>
                        </div>
                    </div>
                </div>
            </div>
            <!-- End Bootstrap Modal -->
            <?php endif; ?>

            <?php
        }

        ?>



        <?php
        // Build the main spin wheel script via WordPress inline helper instead of raw <script>.
        ob_start();
        ?>

            var winWidth = jQuery(window).width()
            circleWidth = <?php echo wp_json_encode($webequipe_sww_spin_circleWidth_genarel); ?>,
                circleHeight = <?php echo wp_json_encode($webequipe_sww_spin_circleWidth_genarel); ?>,
                textSize = 14,
                arrowMark = {
                    w: 70,
                    h: 70,
                    x: -70,
                    y: -35
                },
                centerLogo = {
                    w: 50,
                    h: 50,
                    x: -25,
                    y: -27
                };

            //based on window width change circle size
            if (winWidth < 400) {
                circleWidth = <?php echo wp_json_encode($webequipe_sww_spin_circleWidth_400); ?>;
                circleHeight = <?php echo wp_json_encode($webequipe_sww_spin_circleWidth_400); ?>;
            } else if (winWidth < 575) {
                circleWidth = <?php echo wp_json_encode($webequipe_sww_spin_circleWidth_575); ?>;
                circleHeight = <?php echo wp_json_encode($webequipe_sww_spin_circleWidth_575); ?>;
                margin = 0 + ' auto';
            } else if (winWidth < 768) {
                circleWidth = <?php echo wp_json_encode($webequipe_sww_spin_circleWidth_768); ?>;
                circleHeight = <?php echo wp_json_encode($webequipe_sww_spin_circleWidth_768); ?>;
            } else if (winWidth < 1200) {
                circleWidth = <?php echo wp_json_encode($webequipe_sww_spin_circleWidth_1200); ?>;
                circleHeight = <?php echo wp_json_encode($webequipe_sww_spin_circleWidth_1200); ?>;
            } else if (winWidth < 1400) {
                circleWidth = <?php echo wp_json_encode($webequipe_sww_spin_circleWidth_1400); ?>;
                circleHeight = <?php echo wp_json_encode($webequipe_sww_spin_circleWidth_1400); ?>;
            } else if (winWidth < 1600) {
                circleWidth = <?php echo wp_json_encode($webequipe_sww_spin_circleWidth_1600); ?>;
                circleHeight = <?php echo wp_json_encode($webequipe_sww_spin_circleWidth_1600); ?>;
            }

            var wswwSpinPosition = <?php echo wp_json_encode( $webequipe_sww_spin_spin_position_class ); ?>;

            function wswwApplyWheelScale(diameter) {
                diameter = parseInt(diameter, 10) || 400;
                var hub = Math.round(Math.max(22, Math.min(58, diameter * 0.11)));
                centerLogo = {
                    w: hub,
                    h: hub,
                    x: -Math.round(hub / 2),
                    y: -Math.round(hub / 2)
                };
                var arrow = Math.round(Math.max(26, Math.min(68, diameter * 0.095)));
                arrowMark = {
                    w: arrow,
                    h: arrow,
                    // Image tip is on the right edge; offset left so tip sits outside the wheel
                    x: -arrow,
                    y: -Math.round(arrow / 2)
                };
            }

            function wswwSyncWheelDimensions() {
                // Reserve space outside the wheel rim for the pointer body
                padding.right = Math.max(14, Math.round(arrowMark.w * 0.55));
                w = circleWidth - padding.left - padding.right;
                h = circleHeight - padding.top - padding.bottom;
                r = Math.min(w, h) / 2;
            }

            function wswwWheelCenterX() {
                return padding.left + (w / 2);
            }

            function wswwWheelCenterY() {
                return padding.top + (h / 2);
            }

            function wswwPointerAnchorX() {
                // Anchor at SVG right: pointer tip (image right edge) sits outside the wheel rim
                return padding.left + w + padding.right;
            }

            function wswwPointerAnchorY() {
                return wswwWheelCenterY();
            }

            function wswwSvgTotalWidth() {
                return w + padding.left + padding.right;
            }

            function wswwSvgTotalHeight() {
                return h + padding.top + padding.bottom;
            }

            function wswwCenterHubRadius() {
                return (centerLogo.w / 2) + Math.max(4, Math.round(centerLogo.w * 0.12));
            }

            function wswwClampCircleToViewport(baseSize) {
                var size = parseInt(baseSize, 10) || 400;
                if (wswwSpinPosition !== 'left' && wswwSpinPosition !== 'right') {
                    return size;
                }

                var vh = Math.max(window.innerHeight || 0, document.documentElement.clientHeight || 0);
                var vw = Math.max(document.documentElement.clientWidth || 0, winWidth || 0);
                var wrapper = document.querySelector('.spinner-wrapper.' + wswwSpinPosition);
                if (!wrapper || vh <= 0) {
                    return size;
                }

                var shellPadding = 40;
                var stacked = false;
                var layoutRow = wrapper.querySelector('.w-100');
                if (layoutRow) {
                    var flexDir = window.getComputedStyle(layoutRow).flexDirection;
                    stacked = (flexDir === 'column' || flexDir === 'column-reverse');
                }
                var formReserve = 0;

                if (stacked) {
                    formReserve = Math.min(360, Math.floor(vh * 0.46));
                }

                var maxDiameter = vh - shellPadding - formReserve;

                if (stacked) {
                    maxDiameter = Math.min(maxDiameter, Math.floor(vh * 0.5));
                    if (vw > 0 && vw < 768) {
                        maxDiameter = Math.min(maxDiameter, Math.floor(vw * 0.9) - 24);
                    }
                } else {
                    maxDiameter = Math.floor(vh * 0.94) - shellPadding;
                    var chartBox = wrapper.querySelector('.wsww-chart-container');
                    if (chartBox && chartBox.clientWidth > 0) {
                        maxDiameter = Math.min(maxDiameter, chartBox.clientWidth);
                    } else if (wrapper.clientWidth > 0) {
                        maxDiameter = Math.min(maxDiameter, Math.floor(wrapper.clientWidth * 0.66));
                    }
                }

                return Math.max(220, Math.min(size, maxDiameter));
            }

            circleWidth = wswwClampCircleToViewport(circleWidth);
            circleHeight = circleWidth;
            wswwApplyWheelScale(circleWidth);
            var wswwInitialCircleWidth = circleWidth;

            //variable
            var padding = {
                top: 20,
                right: 40,
                bottom: 0,
                left: 0
            };
            if (wswwSpinPosition === 'left' || wswwSpinPosition === 'right') {
                padding.top = 16;
                padding.bottom = 28;
                padding.left = 0;
            }

            var w, h, r;
            wswwSyncWheelDimensions();

            var rotation = 0,
                oldrotation = 0,
                picked = 100000,
                spinBtn = jQuery('.spin-btn'),
                showIndex = 0,
                showJackPot = 50,
                oldpick = [],
                newData = [],
                dataWithHide = [];
            spinCount = '';

            <?php
            if (!isset($webequipe_sww_spin_spin_labels) || !is_array($webequipe_sww_spin_spin_labels)) {
                return;
            }

            // Build wheel segments (0-based index) – do NOT include spin_item_unique_id on frontend.
            $wheel_segments = [];
            $probabilities_by_index = [];
            $eligible_by_index = [];
            $index = 0;
            foreach ($webequipe_sww_spin_spin_labels as $label) {
                $prob = isset($label['spin_probability']) && is_numeric($label['spin_probability']) ? floatval($label['spin_probability']) : 0;
                $wheel_segments[] = [
                    'id' => sanitize_text_field($webequipe_sww_spin_spin_id . '-' . $index),
                    'is_win' => (isset($label['is_win']) && 'yes' === $label['is_win']) ? 'yes' : 'no',
                    'label' => webequipe_sww_normalize_spin_text($label['spin_label'] ?? ''),
                    'value' => webequipe_sww_normalize_spin_text($label['spin_value'] ?? ''),
                    'probability' => $prob,
                    'color' => sanitize_hex_color($label['spin_bgcolor'] ?? '') ?: '#ffffff',
                    'txtcolor' => sanitize_hex_color($label['spin_textcolor'] ?? '') ?: '#000000',
                ];
                $probabilities_by_index[$index] = $prob;
                $eligible_by_index[$index] = true;
                $index++;
            }

            // Step 5: Total probability of remaining (eligible) items.
            $totalProbability = 0;
            foreach ($probabilities_by_index as $i => $prob) {
                if (!empty($eligible_by_index[$i])) {
                    $totalProbability += $prob;
                }
            }

            // Step 6–7: If remaining total < 100, distribute remainder equally among items with probability > 0 (normal recalculation).
            if ($totalProbability > 0 && $totalProbability < 100) {
                $remaining = 100 - $totalProbability;
                $with_prob = [];
                foreach ($probabilities_by_index as $i => $prob) {
                    if (!empty($eligible_by_index[$i]) && $prob > 0) {
                        $with_prob[] = $i;
                    }
                }
                $count = count($with_prob);
                if ($count > 0) {
                    $per_item = $remaining / $count;
                    foreach ($with_prob as $i) {
                        $probabilities_by_index[$i] += $per_item;
                    }
                    $totalProbability = 100;
                }
            }

            // Only when remaining_probability = 100 (current total = 0): distribute 100 only among eligible items where is_win = no.
            if ( (int) $totalProbability === 0 ) {
                $indices_is_win_no = [];
                foreach ( $wheel_segments as $i => $seg ) {
                    if ( ! empty( $eligible_by_index[ $i ] ) ) {
                        $is_win = isset( $seg['is_win'] ) && strtolower( (string) $seg['is_win'] ) === 'yes';
                        if ( ! $is_win ) {
                            $indices_is_win_no[] = $i;
                        }
                    }
                }
                $count_no = count( $indices_is_win_no );
                if ( $count_no > 0 ) {
                    $per_item = 100 / $count_no;
                    foreach ( array_keys( $probabilities_by_index ) as $i ) {
                        $probabilities_by_index[ $i ] = 0;
                    }
                    foreach ( $indices_is_win_no as $i ) {
                        $probabilities_by_index[ $i ] = $per_item;
                    }
                    $totalProbability = 100;
                }
            }

            // If no eligible items left, fall back to original probabilities.
            if ($totalProbability <= 0) {
                $index = 0;
                foreach ($webequipe_sww_spin_spin_labels as $pro) {
                    $prob = isset($pro['spin_probability']) && is_numeric($pro['spin_probability']) ? floatval($pro['spin_probability']) : 0;
                    $probabilities_by_index[$index] = $prob;
                    $index++;
                }
                $totalProbability = array_sum($probabilities_by_index);
            }
            if ($totalProbability <= 0) {
                $totalProbability = 1;
            }

            // Step 8: Pick winner (0-based index).
            $randomNumber = wp_rand(1, (int) max(1, $totalProbability));
            $sum = 0;
            $winner_index = 0;
            foreach ($probabilities_by_index as $i => $probability) {
                $sum += $probability;
                if ($randomNumber <= $sum) {
                    $winner_index = $i;
                    break;
                }
            }

            // Apply final probabilities to segments and ensure a plain 0-based array for JSON (D3 expects array, not object).
            $segments_count = count($wheel_segments);
            for ( $i = 0; $i < $segments_count; $i++ ) {
                $wheel_segments[$i]['probability'] = isset($probabilities_by_index[$i]) ? $probabilities_by_index[$i] : 0;
            }
            $wheel_segments = array_values($wheel_segments);
            ?>
            var data = <?php echo wp_json_encode( $wheel_segments ) ?: '[]'; ?>;
            if (typeof data !== 'object' || data === null || !Array.isArray(data)) { data = []; }

            var message_data = {
                "win_message": <?php echo wp_json_encode($webequipe_sww_spin_win_message); ?>,
                "loss_message": <?php echo wp_json_encode($webequipe_sww_spin_loss_message); ?>
            };

            // Keep pointer angle single-sourced so offset + spin logic stay synced with pointer DOM position.
            var pointerAngle = 90;

            function webequipe_sww_formatMessage(template, label, value) {
                return template
                    .replace(/{label}/g, label)
                    .replace(/{value}/g, value);
            }


            var svgTotalW = wswwSvgTotalWidth();
            var svgTotalH = wswwSvgTotalHeight();

            var svg = d3.select('#chart')
                .append("svg")
                .data([data])
                .attr("width", svgTotalW)
                .attr("height", svgTotalH)
                .attr("viewBox", "0 0 " + svgTotalW + " " + svgTotalH)
                .attr("preserveAspectRatio", "xMidYMid meet")
                .style({
                    "width": svgTotalW + "px",
                    "max-width": "100%",
                    "height": "auto"
                });



            var container = svg.append("g")
                .attr("class", "chartholder")
                .attr("transform", "translate(" + wswwWheelCenterX() + "," + wswwWheelCenterY() + ")");
            var vis = container
                .append("g");

            var pie = d3.layout.pie().sort(null).value(function (d) {
                return 1;
            });

            // declare an arc generator function
            var arc = d3.svg.arc().outerRadius(r);
            // select paths, use arc generator to draw (pass data array so D3 gets an array, not object)
            var arcs = vis.selectAll("g.slice")
                .data(pie(data))
                .enter()
                .append("g")
                .attr("class", "slice");


            // // draw slices
            arcs.append("path")
                .attr("fill", function (d, i) {
                    return data[i].color;
                })
                .attr("stroke", "<?php echo esc_js((string) $webequipe_sww_spin_spin->wheel_stroke_border_color); ?>")
                .attr("stroke-width", <?php echo (int) $webequipe_sww_spin_spin->wheel_stroke_border_size; ?>)
                .attr("d", function (d) {
                    return arc(d);
                });

            // ----------------------------------------------
            //  NEW WORKING ROTATION OFFSET FOR SLICES
            // ----------------------------------------------
            var angleOffset = 0;
            if (Array.isArray(data) && data.length > 0) {
                var sliceAngle = 360 / data.length;
                angleOffset = pointerAngle - (sliceAngle / 2);
                // Force into 0-359 range so rotation never jumps backwards unexpectedly.
                angleOffset = ((angleOffset % 360) + 360) % 360;
            }

            // Rotate ONLY slices, NOT arrow, NOT center logo
            vis.attr("transform", "rotate(" + angleOffset + ")");
            // ----------------------------------------------


            // Responsive padding for slice labels (left from inner edge, right before outer edge)
            function getLabelPadding(rad) {
                var vw = Math.max(document.documentElement.clientWidth || 0, window.innerWidth || 0);
                var baseLeft = Math.max(28, Math.round(rad * 0.34));
                var baseRight = Math.max(0, Math.round(rad * 0.08));
                if (vw < 480) {
                    return { left: Math.min(baseLeft, Math.round(rad * 0.42)), right: 0 };
                }
                if (vw < 768) {
                    return { left: Math.min(Math.max(36, baseLeft), Math.round(rad * 0.38)), right: 0 };
                }
                if (vw < 1024) {
                    return { left: Math.max(40, baseLeft), right: Math.max(0, baseRight) };
                }
                // Desktop: scale with radius to maintain proportions
                baseLeft = Math.max(40, Math.round(rad * 0.30));
                baseRight = Math.max(0, Math.round(rad * 0.10));
                return { left: baseLeft, right: baseRight };
            }

            var labelPadding = getLabelPadding(r);

            // add the text with smart positioning and overflow handling
            arcs.append("text")
                .attr("transform", function (d) {
                    // Place text starting near the inner edge with responsive left padding
                    d.innerRadius = 0;
                    d.outerRadius = r;
                    d.angle = (d.startAngle + d.endAngle) / 2;
                    // Rotate text along slice bisector, then translate by left padding from center
                    return "rotate(" + (d.angle * 180 / Math.PI - 90) + ")translate(" + labelPadding.left + ")";
                })
                .attr("text-anchor", "start")
                .attr("dominant-baseline", "central")
                .attr("style",
                    "font-size: <?php echo (int) $webequipe_sww_spin_wheel_stroke_font_size; ?>px; font-style: <?php echo esc_js((string) $webequipe_sww_spin_wheel_stroke_font_style); ?>; font-family: <?php echo esc_js((string) $webequipe_sww_spin_wheel_stroke_font_family); ?>; overflow: hidden;"
                )
                .text(function (d, i) {
                    var label = data[i].label;
                    var fontSize = <?php echo (int) $webequipe_sww_spin_wheel_stroke_font_size; ?>;

                    // Character width approximation
                    var charWidth = fontSize * 0.6;

                    // Available radial width for text between inner and outer paddings
                    var availableWidth = Math.max(0, r - labelPadding.left - labelPadding.right);
                    var maxLength = Math.max(3, Math.floor(availableWidth / charWidth));

                    // --- Set minimum characters based on device width ---
                    var vw = Math.max(document.documentElement.clientWidth || 0, window.innerWidth || 0);
                    var minChars;
                    if (vw < 480) {        // Mobile
                        minChars = 10;
                    } else if (vw < 1024) { // Tablet
                        minChars = 6;
                    } else {                // Desktop
                        minChars = 4;
                    }

                    // --- Apply both min and max rules ---
                    var finalLength = Math.max(minChars, maxLength);

                    if (label.length > finalLength) {
                        return label.substring(0, finalLength - 2) + '..';
                    }
                    return label;
                })
                .attr('fill', function (d, i) {
                    // Use the individual segment's text color if available and valid
                    // Check if txtcolor exists, is not empty, and is a valid hex color
                    if (data[i].txtcolor && 
                        data[i].txtcolor !== '' && 
                        data[i].txtcolor !== null && 
                        typeof data[i].txtcolor === 'string' &&
                        /^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/.test(data[i].txtcolor)) {
                        return data[i].txtcolor;
                    }
                    
                    // Fallback: Calculate based on background luminance (auto black/white)
                    // This provides smart contrast when no custom text color is set
                    var hex = data[i].color.replace('#', '');
                    // Expand shorthand form (e.g. '03F') to full form (e.g. '0033FF')
                    if (hex.length === 3) {
                        hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2];
                    }
                    // Convert to RGB
                    var r = parseInt(hex.substr(0, 2), 16);
                    var g = parseInt(hex.substr(2, 2), 16);
                    var b = parseInt(hex.substr(4, 2), 16);
                    // Calculate luminance
                    var luminance = (0.299 * r + 0.587 * g + 0.114 * b) / 255;
                    // Return black for light backgrounds, white for dark backgrounds
                    return luminance > 0.5 ? '#000' : '#fff';
                });

            // Update paddings and reposition/truncate labels on resize
            window.addEventListener('resize', function () {
                labelPadding = getLabelPadding(r);
                vis.selectAll('g.slice text')
                    .attr('transform', function (d) {
                        d.innerRadius = 0;
                        d.outerRadius = r;
                        d.angle = (d.startAngle + d.endAngle) / 2;
                        return "rotate(" + (d.angle * 180 / Math.PI - 90) + ")translate(" + labelPadding.left + ")";
                    })
                    .text(function (d, i) {
                        var label = data[i].label;
                        var fontSize = <?php echo (int) $webequipe_sww_spin_wheel_stroke_font_size; ?>;
                        var charWidth = fontSize * 0.6;
                        var availableWidth = Math.max(0, r - labelPadding.left - labelPadding.right);
                        var maxLength = Math.max(3, Math.floor(availableWidth / charWidth));
                        if (label.length > maxLength) {
                            return label.substring(0, maxLength - 2) + '..';
                        }
                        return label;
                    });
            });

            var spin = function (spinCount) {

                spinBtn.on("click", null);

                if (oldpick.length == data.length) {
                    //console.log("done");
                    spinBtn.on("click", null);
                    return;
                }

                var ps = 360 / data.length,
                    pieslice = Math.round(9440 / data.length);

                // Probability-based selection
                var totalProbability = 0;
                var probabilities = [];

                // Calculate total probability and prepare array
                for (var i = 0; i < data.length; i++) {
                    var prob = parseFloat(data[i].probability) || 0;
                    probabilities.push(prob);
                    totalProbability += prob;
                }

                // Ensure valid total probability
                if (totalProbability <= 0) {
                    totalProbability = 1;
                }

                // Generate random number based on total probability
                var randomNumber = Math.random() * totalProbability;

                // Select winner based on probability
                var sum = 0;
                var selectedIndex = 0;
                for (var j = 0; j < probabilities.length; j++) {
                    sum += probabilities[j];
                    if (randomNumber <= sum) {
                        selectedIndex = j;
                        break;
                    }
                }

                var dataShowIndex = data.findIndex(data => data.showon == spinCount);

                // If specific showon is requested, use that instead of probability
                if (dataShowIndex !== -1 && (data[dataShowIndex].hide === 'yes' || data[dataShowIndex].hide === 'no')) {
                    selectedIndex = dataShowIndex;
                }

                // Calculate rotation using actual rendered slice angles from D3
                // Goal: align picked slice center to pointer angle (90° in our text transform frame)
                var pickedSliceSelector = ".slice:nth-child(" + (selectedIndex + 1) + ")";
                var pickedDatum = null;
                try {
                    pickedDatum = d3.select(pickedSliceSelector).datum();
                } catch (e) {
                    pickedDatum = null;
                }

                if (pickedDatum && typeof pickedDatum.startAngle === 'number' && typeof pickedDatum.endAngle === 'number') {
                    var centerAngleRad = (pickedDatum.startAngle + pickedDatum.endAngle) / 2;
                    var centerAngleDeg = (centerAngleRad * 180 / Math.PI) % 360;
                    if (centerAngleDeg < 0) centerAngleDeg += 360;
                    var alignDelta = (pointerAngle - centerAngleDeg) % 360;
                    if (alignDelta < 0) alignDelta += 360;
                    rotation = (360 * 1000) + alignDelta;
                } else {
                    // Fallback to index-based estimation
                    var rotationBase = (selectedIndex * ps) + (ps / 2);
                    rotation = (360 * 1000) + (360 - rotationBase);
                }



                picked = selectedIndex;


                if (data[picked].hide === 'no') {
                    oldpick.length = data.length;
                    spinBtn.on("click", null);

                }

                if (data[picked].hide === 'yes' && data[picked].showon == '') {
                    d3.select(this).call(spin);
                    return;
                }

                if (oldpick.indexOf(picked) !== -1) {
                    d3.select(this).call(spin);
                    return;
                } else {
                    oldpick.push(picked);
                }
                // remove arbitrary large offset; rotation already includes full spins and alignment

                var spinAnimationDuration = <?php echo (int) $webequipe_sww_spin_spin_duration; ?>;
                jQuery(document).trigger('wsww_spin_start', { duration: spinAnimationDuration });

                vis.transition()
                    .duration(spinAnimationDuration)
                    // .duration(10000)
                    .attrTween("transform", rotTween)
                    .each("end", function () {

                        // add this line start
                        var selectedColor = data[picked].selectcolor;
                        if (!selectedColor || selectedColor === '' || selectedColor === undefined) {
                            selectedColor = data[picked].color; // Use original color as fallback
                        }

                        d3.select(".slice:nth-child(" + (picked + 1) + ") path")
                            .attr("fill", selectedColor);

                        // Example config object for win/lose
                        const resultConfig = {
                            yes: {
                                messageTemplate: message_data.win_message,
                                cardClass: "win-card",
                                // icon: '<img src="<?php echo esc_url(trailingslashit(WEBEQUIPE_SPIN_WIN_WHEEL_ASSETS)); ?>img/win.png" alt="win icon" class="wsww-msg-icon">', 
                                // staticContent: '<h3 class="wsww-win-static">Congratulations!</h3>'
                            },
                            no: {
                                messageTemplate: message_data.loss_message,
                                cardClass: "loss-card",
                                // icon: '<img src="<?php echo esc_url(trailingslashit(WEBEQUIPE_SPIN_WIN_WHEEL_ASSETS)); ?>img/loss.png" alt="loss icon" class="wsww-msg-icon">', 
                                // staticContent: '<h3 class="wsww-loss-static">Failed!</h3>'
                            }
                        };

                        function showResultMessage(pickedData) {
                            const status = pickedData.is_win === "yes" ? "yes" : "no";
                            const cfg = resultConfig[status];

                            let spin_title = <?php echo wp_json_encode($webequipe_sww_spin_spin_title); ?>;

                            const resultContainer = d3.select('#spin-result-message');
                            // Build the result card structure but keep the actual
                            // message empty for now. The final message (including
                            // coupon code) will be injected after the AJAX call.
                            resultContainer.html(`
                    <div class="description">
                        <h3 class="">${spin_title}</h3>
                    </div>
                    <div class="${cfg.cardClass}">
                        <div class="spin-message"></div>
                    </div>
                `);
                            // Keep hidden until the backend response arrives.
                            resultContainer.classed('hide', true);

                            // Hide form fields and description, keep loader container visible
                            jQuery('#spinForm .description').addClass('hide');
                            jQuery('#spinForm .ff-field').addClass('hide');
                            jQuery('#spinForm .wsww-from-button').addClass('hide');
                            jQuery('#spinForm .status-msg').addClass('hide');
                        }


                        if (data[picked]) {
                            showResultMessage(data[picked]);
                        }



                        jQuery("#is-win").val(data[picked].is_win);
                        jQuery("#spin-value").val(data[picked].value);
                        jQuery("#spin-label").val(data[picked].label);

                        oldrotation = rotation;

                        jQuery('#spin-submit-btn').trigger('click');
                        jQuery(document).trigger('wsww_spin_complete');

                        // After spin finishes and the result message is shown,
                        // reload the page after 30 seconds so the user has time to read it.
                        setTimeout(function () {
                            // Use full page reload to ensure all state is reset
                            window.location.reload(true);
                        }, 15000);
                    });
            } //spin

            //make arrow — anchor at SVG right; image extends left with tip near the wheel rim
            svg.append("g")
                .attr("class", "wheel-pointer")
                .attr("transform", "translate(" + wswwPointerAnchorX() + "," + wswwPointerAnchorY() + ")")
                .append("image")
                .attr('xlink:href', <?php echo wp_json_encode( esc_url( $webequipe_sww_spin_arrow_icon ) ); ?>)
                .attr('width', arrowMark.w)
                .attr('height', arrowMark.h)
                .attr("x", arrowMark.x)
                .attr("y", arrowMark.y)
            //draw spin circle

            // wheel center group
            var centerGroup = container.append("g")
                .attr("class", "wheel-center-logo");





            // add background circle/rect
            centerGroup.append("circle")
                .attr("cx", centerLogo.x + centerLogo.w / 2)
                .attr("cy", centerLogo.y + centerLogo.h / 2)
                .attr("r", wswwCenterHubRadius())
                .attr("fill", "<?php echo esc_js((string) $webequipe_sww_spin_wheel_center_background); ?>")
                .attr("stroke", "<?php echo esc_js((string) $webequipe_sww_spin_wheel_center_boder_color); ?>")
                .attr("stroke-width", <?php echo (int) $webequipe_sww_spin_wheel_center_boder_width; ?>);

            // add image
            centerGroup.append("image")
                .attr('xlink:href', <?php echo wp_json_encode( esc_url( $webequipe_sww_spin_center_icon ) ); ?>)
                .attr('width', centerLogo.w)
                .attr('height', centerLogo.h)
                .attr("x", centerLogo.x)
                .attr("y", centerLogo.y);

            function rotTween(to) {
                var i = d3.interpolate(oldrotation % 360, rotation);
                return function (t) {
                    return "rotate(" + i(t) + ")";
                };
            }

            function getRandomNumbers() {
                var array = new Uint16Array(1000);
                var scale = d3.scale.linear().range([360, 9440]).domain([0, 100000]);
                if (window.hasOwnProperty("crypto") && typeof window.crypto.getRandomValues === "function") {
                    window.crypto.getRandomValues(array);
                } else {
                    //no support for crypto, get crappy random numbers
                    for (var i = 0; i < 1000; i++) {
                        array[i] = Math.floor(Math.random() * 100000) + 1;
                    }
                }
                return array;
            }

            //svg style 
            jQuery('#chart > svg').css({
                "width": wswwSvgTotalWidth() + "px",
                "max-width": "100%",
                "height": "auto"
            });

            function wswwSyncStackedColumnWidth() {
                var wrapper = document.querySelector('.spinner-wrapper.left, .spinner-wrapper.right, .spinner-wrapper.popup');
                if (!wrapper) {
                    return;
                }
                var layoutRow = wrapper.querySelector('.w-100');
                if (!layoutRow) {
                    return;
                }
                var flexDir = window.getComputedStyle(layoutRow).flexDirection;
                if (flexDir !== 'column' && flexDir !== 'column-reverse') {
                    layoutRow.style.width = '';
                    layoutRow.style.maxWidth = '';
                    return;
                }
                var svg = document.querySelector('#chart svg');
                if (!svg) {
                    return;
                }
                var rect = svg.getBoundingClientRect();
                if (!rect.width || rect.width < 1) {
                    return;
                }
                var colWidth = Math.ceil(rect.width) + 'px';
                layoutRow.style.width = colWidth;
                layoutRow.style.maxWidth = '100%';
                layoutRow.style.marginLeft = 'auto';
                layoutRow.style.marginRight = 'auto';
            }

            function wswwUpdateWheelLayoutGraphics() {
                wswwSyncWheelDimensions();
                var totalW = wswwSvgTotalWidth();
                var totalH = wswwSvgTotalHeight();
                var $svg = jQuery('#chart > svg');
                if ($svg.length) {
                    $svg.attr('width', totalW)
                        .attr('height', totalH)
                        .attr('viewBox', '0 0 ' + totalW + ' ' + totalH)
                        .css({
                            width: totalW + 'px',
                            maxWidth: '100%',
                            height: 'auto'
                        });
                }
                d3.select('#chart .chartholder').attr(
                    'transform',
                    'translate(' + wswwWheelCenterX() + ',' + wswwWheelCenterY() + ')'
                );
                var hubR = wswwCenterHubRadius();
                var $center = jQuery('.wheel-center-logo');
                if ($center.length) {
                    $center.find('circle')
                        .attr('cx', centerLogo.x + centerLogo.w / 2)
                        .attr('cy', centerLogo.y + centerLogo.h / 2)
                        .attr('r', hubR);
                    $center.find('image')
                        .attr('width', centerLogo.w)
                        .attr('height', centerLogo.h)
                        .attr('x', centerLogo.x)
                        .attr('y', centerLogo.y);
                }
                jQuery('#chart .wheel-pointer')
                    .attr('transform', 'translate(' + wswwPointerAnchorX() + ',' + wswwPointerAnchorY() + ')');
                jQuery('#chart .wheel-pointer image')
                    .attr('width', arrowMark.w)
                    .attr('height', arrowMark.h)
                    .attr('x', arrowMark.x)
                    .attr('y', arrowMark.y);
            }

            function wswwApplySidebarWheelSize(targetSize) {
                if (wswwSpinPosition !== 'left' && wswwSpinPosition !== 'right') {
                    return;
                }
                var fitted = wswwClampCircleToViewport(targetSize || circleWidth);
                if (Math.abs(fitted - circleWidth) < 4) {
                    wswwSyncStackedColumnWidth();
                    return;
                }
                circleWidth = fitted;
                circleHeight = fitted;
                wswwApplyWheelScale(circleWidth);
                wswwSyncWheelDimensions();
                if (typeof arc !== 'undefined' && typeof vis !== 'undefined' && vis.selectAll) {
                    arc.outerRadius(r);
                    vis.selectAll('path').attr('d', function (d) {
                        return arc(d);
                    });
                    labelPadding = getLabelPadding(r);
                    vis.selectAll('g.slice text').attr('transform', function (d) {
                        d.innerRadius = 0;
                        d.outerRadius = r;
                        d.angle = (d.startAngle + d.endAngle) / 2;
                        return 'rotate(' + (d.angle * 180 / Math.PI - 90) + ')translate(' + labelPadding.left + ')';
                    });
                }
                wswwUpdateWheelLayoutGraphics();
                wswwSyncStackedColumnWidth();
            }

            window.wswwFitSidebarWheel = function () {
                wswwApplySidebarWheelSize(wswwInitialCircleWidth);
            };

            wswwSyncStackedColumnWidth();
            setTimeout(wswwSyncStackedColumnWidth, 100);
            setTimeout(wswwSyncStackedColumnWidth, 500);

            if (wswwSpinPosition === 'left' || wswwSpinPosition === 'right') {
                setTimeout(function () {
                    wswwApplySidebarWheelSize(wswwInitialCircleWidth);
                }, 450);
                jQuery(window).on('resize.wswwSidebar', function () {
                    if (jQuery('.spinner-wrapper.left.appear-from-left, .spinner-wrapper.right.appear-from-right').length) {
                        wswwApplySidebarWheelSize(wswwInitialCircleWidth);
                    } else {
                        wswwSyncStackedColumnWidth();
                    }
                });
            } else {
                jQuery(window).on('resize.wswwStacked', function () {
                    wswwUpdateWheelLayoutGraphics();
                    wswwSyncStackedColumnWidth();
                });
            }


            // cookie function - define at the top for global access
            function readCookie(name) {
                var nameEQ = name + "=";
                var ca = document.cookie.split(';');
                for (var i = 0; i < ca.length; i++) {
                    var c = ca[i];
                    while (c.charAt(0) == ' ') c = c.substring(1, c.length);
                    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
                }
                return null;
            }

            // Always use event delegation for .spin-close (works for dynamic and static)
            jQuery(document).on('click', '.spin-close', function () {
                let spinner_wrapper = jQuery('.spinner-wrapper');
                let wsww_shortcode_wrapper = jQuery('.wsww-shortcode-wrapper');
                
                // Remove animation classes first to trigger close animation
                if (spinner_wrapper.hasClass('left')) {
                    spinner_wrapper.removeClass('appear-from-left');
                    // Ensure it stays on left side during close
                    spinner_wrapper.css({
                        'left': '-100%',
                        'right': 'auto'
                    });
                } else if (spinner_wrapper.hasClass('right')) {
                    spinner_wrapper.removeClass('appear-from-right');
                    // Ensure it stays on right side during close
                    spinner_wrapper.css({
                        'right': '-100%',
                        'left': 'auto'
                    });
                } else {
                    spinner_wrapper.removeClass('appear-on-popup');
                    spinner_wrapper.removeClass('spinner-open');
                }
                
                // Wait for transition to complete before removing overlay
                setTimeout(function() {
                    jQuery(".wsww-overlay").remove();
                    jQuery('body').removeClass('wsww-spinner-open');

                    // Reset any inline styles
                    spinner_wrapper.css({
                        'left': '',
                        'right': ''
                    });
                }, 400); // Match transition duration
            });

            // Button click handler is now in wsww-ajax.js using event delegation
            // This ensures it works even if the button is added dynamically
        <?php
        // Collect the main wheel script and store it for later addition
        $webequipe_sww_spin_inline_js = ob_get_clean();
        if ( ! empty( $webequipe_sww_spin_inline_js ) ) {
            \Webequipe\SpinWinWheel\Frontend\Shortcode::add_inline_script_content( $webequipe_sww_spin_inline_js );
        }
        ?>

        <?php
        //check spin type == spin_auto
        if ('spin_auto' === $webequipe_sww_spin_spin->spin_type || $webequipe_sww_spin_default_id !== 0) {

            $webequipe_sww_spin_auto_minute_seconds = $webequipe_sww_spin_auto_minute;
            $auto_spin_delay = $webequipe_sww_spin_auto_minute_seconds * 1000;

            if ('left' === $webequipe_sww_spin_spin_position) {
                $webequipe_sww_spin_spin_position_class = 'left-auto';
            } elseif ('right' === $webequipe_sww_spin_spin_position) {
                $webequipe_sww_spin_spin_position_class = 'right-auto';
            } else if ('inline' === $webequipe_sww_spin_spin_position) {
                $webequipe_sww_spin_spin_position_class = 'center-auto';
            }
            ?>

            <?php
            ob_start();
            ?>
                // DEBUG: Confirm JS block is running



                function getCookie(name) {
                    let match = document.cookie.match(new RegExp('(^| )' + name + '=([^;]+)'));
                    if (match) return match[2];
                    return null;
                }

                function setCookie(name, value, days) {
                    let expires = "";
                    if (days) {
                        let date = new Date();
                        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
                        expires = "; expires=" + date.toUTCString();
                    }
                    document.cookie = name + "=" + value + expires + "; path=/";
                }

                jQuery(function ($) {
                    var displayAfterMinutes = <?php echo (int) $webequipe_sww_spin_display_after; ?>; // minutes
                    var autoMinuteSeconds = <?php echo (int) $auto_spin_delay; ?>; // fallback in ms

                    var cookieValue = getCookie("spin_auto_data");
                    var now = Date.now(); // current timestamp in ms
                    var autoSpinDelay;

                    if (cookieValue) {
                        var expireTime = parseInt(cookieValue, 10); // timestamp in ms
                        if (now >= expireTime) {
                            // cookie expired → fallback
                            autoSpinDelay = autoMinuteSeconds;
                        } else {
                            // cookie valid → delay = expireTime - now
                            autoSpinDelay = expireTime - now;
                        }
                    } else {
                        // no cookie → fallback
                        autoSpinDelay = autoMinuteSeconds;
                    }

                    setTimeout(function () {
                        var spinner = $('.spinner-type-spin_auto');
                        var spinner_wrapper = $('.spinner-wrapper');
                        
                        if (spinner.length && spinner_wrapper.length) {
                            // Add position class to spinner
                            spinner.addClass('<?php echo esc_js((string) $webequipe_sww_spin_spin_position_class); ?>');
                            
                            // Use the exact same function as button click - ensures identical behavior
                            if (typeof window.wswwOpenSpinner === 'function') {
                                // Call the same function that button click uses
                                window.wswwOpenSpinner(<?php echo (int) $webequipe_sww_spin_shortcode_id; ?>);
                                
                                // Save new expiry time (current time + displayAfterMinutes)
                                var expireAt = now + (displayAfterMinutes * 60 * 1000);
                                setCookie("spin_auto_data", expireAt, 30); // keep cookie for 30 days
                            } else {
                                // Wait a bit for the function to be available (in case scripts load in different order)
                                var retryCount = 0;
                                var maxRetries = 10;
                                var checkInterval = setInterval(function() {
                                    if (typeof window.wswwOpenSpinner === 'function') {
                                        clearInterval(checkInterval);
                                        window.wswwOpenSpinner(<?php echo (int) $webequipe_sww_spin_shortcode_id; ?>);
                                        
                                        // Save new expiry time (current time + displayAfterMinutes)
                                        var expireAt = now + (displayAfterMinutes * 60 * 1000);
                                        setCookie("spin_auto_data", expireAt, 30); // keep cookie for 30 days
                                    } else {
                                        retryCount++;
                                        if (retryCount >= maxRetries) {
                                            clearInterval(checkInterval);
                                            console.warn('wswwOpenSpinner function not available after retries');
                                        }
                                    }
                                }, 100);
                            }
                        }
                    }, autoSpinDelay);
                });
            <?php
            // Collect the auto-trigger script and store it for later addition
            $webequipe_sww_autospin_inline_js = ob_get_clean();
            if ( ! empty( $webequipe_sww_autospin_inline_js ) ) {
                \Webequipe\SpinWinWheel\Frontend\Shortcode::add_inline_script_content( $webequipe_sww_autospin_inline_js );
            }
            } ?>



    <?php } ?>

<?php } ?>
