jQuery(document).ready(function ($) {
    // Capture the "Continue & Save" (recurrence warning) modal content markup for later restoration.
    // This is the content we may need to bring back if the modal DOM gets replaced.
    window.evgeInitialContinueSaveModalMarkup = window.evgeInitialContinueSaveModalMarkup || null;
    const $initialContinueSaveModalContent = $('.evge-recurrence-modal-content').first();
    if ($initialContinueSaveModalContent.length) {
        window.evgeInitialContinueSaveModalMarkup = $initialContinueSaveModalContent.prop('outerHTML');
    }

    /**
     * Checks if there are any recurrence changes that need special handling
     * @param {Object} options - The save options
     * @returns {boolean} - Returns true if special handling is needed, false otherwise
     */
    window.evgeCheckRecurrenceChanges = function () {
        // Check for recurrence changes
        const originalRecurrenceType = $('.evge-original-recurrence-type').text();
        const originalRecurrenceEndDate = $('.evge-original-recurrence-end-date').text();

        const currentRecurrenceType = $('#evge_recurrence_type').val();
        const currentRecurrenceEndDate = $('#evge_recurrence_end_date').val();

        if (originalRecurrenceType === 'none') {
            return false;
        }

        if (currentRecurrenceType === 'none' && originalRecurrenceType === 'none') {
            return false;
        }

        // if either value is empty, as in empty string or null, continue with save
        if (currentRecurrenceType === '' || originalRecurrenceType === '') {
            return false;
        }

        const isFreeTier = window.evgeCPTAdmin && window.evgeCPTAdmin.isFreeTier;
        if (isFreeTier && (currentRecurrenceType === 'custom' || currentRecurrenceType === 'custom_pro')) {
            return false;
        }

        if (currentRecurrenceType !== originalRecurrenceType
            || currentRecurrenceEndDate !== originalRecurrenceEndDate) {
                            // Ensure the "Continue & Save" modal content exists; if it was removed, restore it.
            if (
                !$('.evge-recurrence-modal-content').length &&
                window.evgeInitialContinueSaveModalMarkup &&
                $('.evge-modal-content').length
            ) {
                $('.evge-modal-content').prepend(window.evgeInitialContinueSaveModalMarkup);
                $('.evge-dynamic.evge-modal-settings').remove();
            }
            $('.evge-recurring-warning-registration-text').show();
            return true;
        } else {
            $('.evge-recurring-warning-registration-text').hide();
            return false;
        }
    };

    /**
     * Tracks whether this queue run ever reported a non-zero total or processed event count.
     * Used to avoid showing the "empty queue" success state after real batch work was shown.
     */
    window.evgeQueueHadNonZeroEventCounts = false;
    window.evgeNoteSeriesQueueEventCounts = function (total, processed) {
        const t = parseInt(total, 10) || 0;
        const p = parseInt(processed, 10) || 0;
        if (t > 0 || p > 0) {
            window.evgeQueueHadNonZeroEventCounts = true;
        }
    };

    /**
     * Shows the queue processing modal and handles its functionality
     * @param {Object} response - The AJAX response containing queue processing data
     */
    window.evgeShowQueueProcessingModal = function(response) {
        if (response.data.pending_tasks > 0) {
            window.evgeQueueHadNonZeroEventCounts = false;
            window.evgeNoteSeriesQueueEventCounts(response.data.total_events, response.data.processed_events);

            // If any dynamic settings content exists in the modal, remove it before revealing new content.
            $('.evge-modal').find('.evge-dynamic.evge-modal-settings').remove();

            // Append the modal HTML to the body if it doesn't exist yet
            if ($('.evge-modal-content').length) {
                $('.evge-recurrence-modal-content').hide();
                // Always replace existing queue content (avoid duplicates / stale HTML).
                $('.evge-modal-evge-queue-processing-modal-content').remove();
                var $modalDiv = $('<div class="evge-modal-evge-queue-processing-modal-content"></div>');
                $modalDiv.html(response.data.modal_html);
                $('.evge-modal-content').prepend($modalDiv);
            } else {
                console.error('Modal not found');
            }
            // Show the modal
            $('.evge-modal')
                .addClass('evge-narrow-max-width-modal evge-centered-modal evge-recurrence-modal')
                .removeClass('evge-medium-max-width-modal');
            $('body').addClass('evge-modal-is-open');

            // Set up close button handlers
            $('.evge-modal-backdrop, .evge-action-modal-close, .evge-modal-close').on('click', function () {
                $('body').removeClass('evge-modal-is-open');
            });
            $('.evge-total-count')
                .text(response.data.total_events)
                .attr('data-total-events', response.data.total_events);
            $('.evge-processed-count').text(response.data.processed_events || 0);

            const progress = response.data.total_events > 0
                ? ((response.data.processed_events || 0) / response.data.total_events) * 100
                : 0;
            $('.evge-progress-bar').css('width', progress + '%');

            if (typeof window.evgeProcessQueueBatch === 'function') {
                if (response.data.is_creation) {
                    $('.evge-undo-recurrence-create').show();
                } else {
                    $('.evge-undo-recurrence-create').hide();
                }
                window.evgeProcessQueueBatch(1, response.data.estimated_batches || 30, response.data.is_creation, response.data.series_id);
            }
        } else {
            // Nothing to process; ensure any queue modal leftovers are removed.
            $('.evge-modal').find('.evge-dynamic.evge-modal-settings').remove();
            $('.evge-modal-evge-queue-processing-modal-content').remove();
            $('body').removeClass('evge-modal-is-open');
        }
    };

    // Initialize venue and organizer tools
    window.evgeInitVenueOrganizerTools = function () {
        // Handle quick create buttons
        $('.evge-create-new:not(.evge-initialized)').on('click', function (event) {
            event.preventDefault();
            $('.evge-' + $(this).attr('data-post-type') + '-quick-create')
                .slideDown()
                .append('<input type="hidden" name="evge_quick_create_' + $(this).attr('data-post-type') + '" value="1">');
        }).addClass('evge-initialized');

        $('.evge-undo-create:not(.evge-initialized)').on('click', function (event) {
            event.preventDefault();
            $('.evge-' + $(this).attr('data-post-type') + '-quick-create')
                .slideUp()
                .find('input[name="evge_quick_create_' + $(this).attr('data-post-type') + '"]')
                .remove();
        }).addClass('evge-initialized');

        // Handle add item functionality
        $('.evge-add-item-link:not(.evge-initialized)').on('click', function (e) {
            e.preventDefault();
            let $context = $(this).siblings('.evge-multi-select-list');
            let $newItem = $context.find('.evge-item-list .evge-single-wrap').first().clone();

            // Remove primary item class and create new button, add remove button
            $newItem.removeClass('evge-primary-item')
                .find('.evge-create-new, .evge-undo-create').remove()
                .end()
                .append('<a href="#" class="evge-item-remove">' + evgeIcon.close + '</a>');

            $newItem.appendTo($context.find('.evge-item-list'));
            evgeInitRemove($newItem);
        }).addClass('evge-initialized');

        // Initialize remove buttons
        $('.evge-item-remove:not(.evge-initialized)').each(function () {
            evgeInitRemove($(this).closest('.evge-single-wrap'));
            $(this).addClass('evge-initialized');
        });
    };
    // Initial initialization
    window.evgeInitVenueOrganizerTools();


    if ($('.evge-modal-placeholder').length && $('.evge-recurrence-modal-content').length) {
        $('body').append($('.evge-modal-backdrop'));
        $('body').append($('#evge-modal'));
        // Replace existing modal content
        $('.evge-modal-placeholder').replaceWith($('.evge-recurrence-modal-content'));
    }

    function evgeApplyMinMaxEndDate() {
        let startTimeVal = $('#evge_start_date').val();
        let endTimeVal = $('#evge_end_date').val();
        let startTime = new Date(startTimeVal).getTime();
        let endTime = new Date(endTimeVal).getTime();
        if (startTime > endTime) {
            $('#evge_end_date').val(startTimeVal);
        }
        $('#evge_end_date').attr('min', startTimeVal);
    } evgeApplyMinMaxEndDate();
    $('#evge_start_date').on('change', function () {
        evgeApplyMinMaxEndDate();
    });

    /**
     * Format a Date as YYYY-MM-DD in the environment local calendar (not UTC).
     * type="date" values are calendar days in local time; toISOString() would use UTC and can drift a day.
     */
    function evgeFormatLocalYmd(date) {
        const y = date.getFullYear();
        const m = String(date.getMonth() + 1).padStart(2, '0');
        const d = String(date.getDate()).padStart(2, '0');
        return y + '-' + m + '-' + d;
    }

    // Function to limit recurrence end date to max 1 year from start date
    function evgeLimitRecurrenceEndDate() {
        // Get the start date value
        let startDateVal = $('#evge_start_date').val();
        if (!startDateVal) return;

        // Handle both datetime-local and date input types
        let startDate;
        if (startDateVal.includes('T')) {
            startDate = new Date(startDateVal);
        } else {
            const timeComponent = $('#evge_start_date').attr('data-time') || '00:00';
            startDate = new Date(startDateVal + 'T' + timeComponent);
        }

        // Calculate max date (1 year from start date)
        let maxDate = new Date(startDate);
        maxDate.setFullYear(maxDate.getFullYear() + 1);

        let startDateStr = evgeFormatLocalYmd(startDate);
        let maxDateStr = evgeFormatLocalYmd(maxDate);

        // Set the min and max attributes on the recurrence end date input
        $('#evge_recurrence_end_date').attr('min', startDateStr);
        $('#evge_recurrence_end_date').attr('max', maxDateStr);

        // Compare YYYY-MM-DD as strings so we do not rely on Date parsing of date-only strings (UTC vs local).
        let currentEndDateVal = $('#evge_recurrence_end_date').val();
        if (currentEndDateVal) {
            if (currentEndDateVal < startDateStr) {
                $('#evge_recurrence_end_date').val(startDateStr);
            } else if (currentEndDateVal > maxDateStr) {
                $('#evge_recurrence_end_date').val(maxDateStr);
            }
        } else {
            $('#evge_recurrence_end_date').val(startDateStr);
        }
    }

    // Run on page load
    evgeLimitRecurrenceEndDate();

    // Run whenever start date changes
    $('#evge_start_date').on('change', function () {
        evgeLimitRecurrenceEndDate();
    });

    $('.evge-selected-timezone-wrap a').on('click', function (event) {
        event.preventDefault();
        $('.evge-event-timezone-wrap').slideToggle();
        $(this).hide();
    });

    // Make function globally available so it can be called from evge-settings.js
    window.evgeUpdateStartEndDateTimeInputs = function(allDay) {
        if (!$('#evge_start_date').length) {
            return;
        }
        let startDateTimeVal = $('#evge_start_date').val();
        let endDateTimeVal = $('#evge_end_date').val();
        let startDateVal = startDateTimeVal.indexOf('T') > -1 ? startDateTimeVal.split('T')[0] : startDateTimeVal;
        let endDateVal = endDateTimeVal.indexOf('T') > -1 ? endDateTimeVal.split('T')[0] : endDateTimeVal;
        let startTimeVal = startDateTimeVal.indexOf('T') > -1 ? startDateTimeVal.split('T')[1] : '00:00';
        let endTimeVal = endDateTimeVal.indexOf('T') > -1 ? endDateTimeVal.split('T')[1] : '00:00';
        if ($('#evge_start_date').val().indexOf('T') === -1) {
            if (typeof $('#evge_start_date').attr('data-time') !== 'undefined') {
                startDateTimeVal = $('#evge_start_date').val() + 'T' + $('#evge_start_date').attr('data-time');
                startTimeVal = $('#evge_start_date').attr('data-time');
            } else {
                startDateTimeVal = $('#evge_start_date').val() + 'T00:00';
            }
        }
        if ($('#evge_end_date').val().indexOf('T') === -1) {
            if (typeof $('#evge_end_date').attr('data-time') !== 'undefined') {
                endDateTimeVal = $('#evge_end_date').val() + 'T' + $('#evge_end_date').attr('data-time');
                endTimeVal = $('#evge_end_date').attr('data-time');
            } else {
                endDateTimeVal = $('#evge_end_date').val() + 'T00:00';
            }
        }
        if (allDay) {
            $('#evge_start_date').attr('type', 'date').val(startDateVal).attr('data-time', startTimeVal);
            $('#evge_end_date').attr('type', 'date').val(endDateVal).attr('data-time', endTimeVal);
        } else {
            $('#evge_start_date').attr('type', 'datetime-local').val(startDateTimeVal);
            $('#evge_end_date').attr('type', 'datetime-local').val(endDateTimeVal);
        }
    };
    
    // Initialize on page load
    if (typeof window.evgeUpdateStartEndDateTimeInputs === 'function') {
        window.evgeUpdateStartEndDateTimeInputs($('#evge-single-setting-all-day .evge-settings-toggle').hasClass('evge-input-toggle--enabled'));
    }

    $('#evge_unlimited_capacity').on('change', function () {
        if ($(this).is(':checked')) {
            $('#evge-capacity').prop('disabled', true);
        } else {
            $('#evge-capacity').prop('disabled', false);
        }
    });

    function evgeProcessTimelineSelection() {
        let openType = $('#evge_open_type').val();
        let closeType = $('#evge_close_type').val();

        $('.evge-open-type-sub').each(function () {
            if ($(this).attr('data-type') === openType) {
                $(this).show();
            } else {
                $(this).hide();
            }
        });

        $('.evge-close-type-sub').each(function () {
            if ($(this).attr('data-type') === closeType) {
                $(this).show();
            } else {
                $(this).hide();
            }
        });

    } evgeProcessTimelineSelection();

    $('#evge_open_type, #evge_close_type').on('change', function () {
        evgeProcessTimelineSelection();
    });

    function evgeInitRegistrationTypes($context) {

        $context.find('.evge-registration-type-price-type select').on('change', function () {
            if ($(this).val() === 'custom') {
                $context.find('.evge-registration-type-price').slideDown();
            } else {
                $context.find('.evge-registration-type-price').slideUp();
            }
        });
        $context.find('.evge-registration-type-capacity-type select').on('change', function () {
            if ($(this).val() === 'custom') {
                $context.find('.evge-registration-type-capacity').slideDown();
            } else {
                $context.find('.evge-registration-type-capacity').slideUp();
            }
        });
    }
    $('.evge-registration-type').each(function () {
        evgeInitRegistrationTypes($(this));
    });


    // Initialize remove functionality
    function evgeInitRemove($item) {
        $item.find('.evge-item-remove:not(.evge-initialized)').on('click', function (e) {
            e.preventDefault();
            $(this).closest('.evge-single-wrap').remove();
            evgeToggleAvailableOptions();
        }).addClass('evge-initialized');
    }

    // Toggle available options
    function evgeToggleAvailableOptions() {
        $('.evge-multi-select-list').each(function () {
            let $context = $(this);
            let $items = $context.find('.evge-single-wrap').not('.evge-primary-item');

            if ($items.length === 0) {
                $items.find('.evge-item-remove').hide();
            } else {
                $items.find('.evge-item-remove').show();
            }
        });
    }

    $('input[name="evge_set_registration_default"]').on('change', function () {
        if ($(this).is(':checked')) {
            console.log('Global setting should be updated to disable registration by default');
        }
    });

    $('.evge-capacity-toggle .evge-settings-toggle').on('click', function () {
        const $toggle = $(this);
        const $input = $('#evge_capacity');

        // Wait for the toggle to update its state
        setTimeout(function () {
            if ($toggle.hasClass('evge-input-toggle--enabled')) {
                $input.prop('disabled', true);
            } else {
                $input.prop('disabled', false);
            }
        }, 50);
    });

    // Function to toggle registration sections visibility
    function toggleRegistrationSections() {
        const $toggle = $('.evge-registration-toggle .evge-settings-toggle');
        if ($toggle.hasClass('evge-input-toggle--enabled')) {
            // Show all registration sections
            $('.evge-registration-section').show();
        } else {
            // Hide all registration sections except the general one
            $('.evge-registration-section').hide();
            $('#evge-registration-general').show();
        }
    } toggleRegistrationSections();

    // Handle registration toggle to show/hide registration sections
    $('.evge-registration-toggle .evge-settings-toggle').on('click', function () {
        // Wait for the toggle to update its state
        setTimeout(toggleRegistrationSections, 50);
    });

    /**
     * Handle payment toggle state changes
     * This function is called after the toggle state has been updated by evge-settings.js
     */
    function evgeHandlePaymentToggle($toggle) {
        var $wrap = $toggle.closest('.evge-payment-enabled-wrap');
        var $toggleContainer = $toggle.closest('.evge-toggle-setting');
        var $message = $wrap.find('.evge-payment-gateway-message');
        var hasConfiguredGateway = $wrap.attr('data-has-configured-gateway') === 'true';
        
        // Wait for toggle state to update (after the class change in the main handler from evge-settings.js)
        setTimeout(function() {
            // Check the current state after update
            var isEnabled = $toggle.hasClass('evge-input-toggle--enabled');
            
            if (isEnabled && !hasConfiguredGateway) {
                // Add yellow warning class
                $toggleContainer.addClass('evge-gateway-needs-configuration');
                // Show message
                if ($message.length) {
                    $message.show();
                }
            } else {
                // Remove yellow warning class
                $toggleContainer.removeClass('evge-gateway-needs-configuration');
                // Hide message
                if ($message.length) {
                    $message.hide();
                }
            }
        }, 50);
    }

    // Handle payment toggle changes - listen after evge-settings.js handles the toggle
    $('body').on('click', '.evge-payment-enabled-wrap .evge-settings-toggle', function() {
        var $toggle = $(this);
        // Let evge-settings.js handle the toggle state change, then handle payment-specific logic
        evgeHandlePaymentToggle($toggle);
    });

    // Image upload handling
    $('.evge-upload-image').on('click', function (e) {
        e.preventDefault();

        const $button = $(this);
        const $wrap = $button.closest('.evge-image-upload-wrap');
        const $preview = $wrap.find('.evge-image-preview');
        const $input = $wrap.find('input[type="hidden"]');
        const $removeButton = $wrap.find('.evge-remove-image');

        // Create a new media frame
        const frame = wp.media({
            title: 'Select or Upload Image',
            button: {
                text: 'Use this image'
            },
            multiple: false
        });

        // When an image is selected in the media frame...
        frame.on('select', function () {
            // Get media attachment details from the frame state
            const attachment = frame.state().get('selection').first().toJSON();

            // Get the image URL, falling back to full size if thumbnail isn't available
            const imageUrl = attachment.sizes.thumbnail ? attachment.sizes.thumbnail.url : attachment.url;

            // Set the image preview
            $preview.html(`<img src="${imageUrl}" alt="">`);

            // Update the form value
            $input.val(attachment.id);

            // Show remove button
            $removeButton.show();
        });

        // Finally, open the modal
        frame.open();
    });

    // Remove image
    $('.evge-remove-image').on('click', function (e) {
        e.preventDefault();

        const $button = $(this);
        const $wrap = $button.closest('.evge-image-upload-wrap');
        const $preview = $wrap.find('.evge-image-preview');
        const $input = $wrap.find('input[type="hidden"]');

        // Clear the preview and input
        $preview.empty();
        $input.val('');

        // Hide remove button
        $button.hide();
    });

    const recurrenceSelect = $('#evge_recurrence_type');
    const scheduleRoot = $('#evge-single-recurrence-schedule');
    const endDateDiv = $('#evge-recurrence-end-date');
    const customRuleUpsellPanel = $('#evge-recurrence-custom-rule-upsell');
    const customRuleProPanel = $('#evge-recurrence-custom-rule-pro');
    const afterRecurrencePanel = $('#evge-event-editor-after-recurrence-panel');
    const hasProCustomSchedules = !!(window.evgeCPTAdmin && window.evgeCPTAdmin.hasCustomSchedules);
    const startDateInput = $('#evge_start_date');
    const evgeDateLocale =
        window.evgeCPTAdmin && window.evgeCPTAdmin.locale ? window.evgeCPTAdmin.locale : undefined;

    function evgeFormatYmdForDisplay(ymd) {
        if (!ymd || !/^\d{4}-\d{2}-\d{2}$/.test(ymd)) {
            return ymd;
        }
        const p = ymd.split('-').map((x) => parseInt(x, 10));
        const dt = new Date(p[0], p[1] - 1, p[2], 12, 0, 0);
        return dt.toLocaleDateString(evgeDateLocale, { year: 'numeric', month: 'long', day: 'numeric' });
    }

    function evgeFormatYmdForCustomPreview(ymd) {
        if (!ymd || !/^\d{4}-\d{2}-\d{2}$/.test(ymd)) {
            return ymd;
        }
        const p = ymd.split('-').map((x) => parseInt(x, 10));
        const dt = new Date(p[0], p[1] - 1, p[2], 12, 0, 0);
        return dt.toLocaleDateString(evgeDateLocale, {
            weekday: 'long',
            year: 'numeric',
            month: 'long',
            day: 'numeric',
        });
    }

    function evgeIsoDow(d) {
        const day = d.getDay();
        return day === 0 ? 7 : day;
    }

    function evgeYmdFromDate(d) {
        const y = d.getFullYear();
        const m = String(d.getMonth() + 1).padStart(2, '0');
        const day = String(d.getDate()).padStart(2, '0');
        return `${y}-${m}-${day}`;
    }

    function evgeParseYmdLocal(s) {
        if (!s || !/^\d{4}-\d{2}-\d{2}$/.test(s)) {
            return null;
        }
        const p = s.split('-').map((x) => parseInt(x, 10));
        return new Date(p[0], p[1] - 1, p[2], 12, 0, 0);
    }

    function evgeMondayOf(d) {
        const x = new Date(d.getFullYear(), d.getMonth(), d.getDate(), 12, 0, 0);
        const iso = evgeIsoDow(x);
        x.setDate(x.getDate() - (iso - 1));
        return x;
    }

    function evgeDaysInMonth(y, m0) {
        return new Date(y, m0 + 1, 0).getDate();
    }

    function evgeWeekdayOrdinalInMonth(d) {
        const y = d.getFullYear();
        const m = d.getMonth();
        const iso = evgeIsoDow(d);
        let ord = 0;
        for (let day = 1; day <= d.getDate(); day++) {
            const t = new Date(y, m, day, 12, 0, 0);
            if (evgeIsoDow(t) === iso) {
                ord++;
            }
        }
        return ord;
    }

    function evgeGetEditorStartAsDate() {
        const startDateValue = startDateInput.val();
        if (!startDateValue) {
            return null;
        }
        if (startDateValue.includes('T')) {
            return new Date(startDateValue);
        }
        const timeComponent = startDateInput.attr('data-time') || '12:00';
        return new Date(startDateValue + 'T' + timeComponent);
    }

    function evgeGetRecurrenceEndYmdForPreview() {
        const v = $('#evge_recurrence_end_date').val();
        if (v && /^\d{4}-\d{2}-\d{2}$/.test(v)) {
            return v;
        }
        const s = evgeGetEditorStartAsDate();
        if (!s) {
            return null;
        }
        const end = new Date(s.getFullYear(), s.getMonth(), s.getDate(), 12, 0, 0);
        end.setFullYear(end.getFullYear() + 2);
        return evgeYmdFromDate(end);
    }

    function evgeGetSkipYmdSet() {
        const o = Object.create(null);
        $('.evge-recurrence-skip-dates--pro .evge-recurrence-skip-dates-pill').each(function () {
            const y = $(this).attr('data-date');
            if (y) {
                o[y] = true;
            }
        });
        return o;
    }

    function evgeReadCustomRuleFromPro() {
        return {
            interval: Math.min(99, Math.max(1, parseInt($('#evge_custom_rec_interval').val(), 10) || 1)),
            frequency: String($('#evge_custom_rec_frequency').val() || 'week'),
            weekdays: customRuleProPanel
                .find('.evge-recurrence-custom-weekday-pill input:checked')
                .map(function () {
                    return parseInt($(this).val(), 10);
                })
                .get()
                .sort((a, b) => a - b),
            monthlyMode:
                customRuleProPanel.find('input[name="evge_custom_rec_monthly_mode"]:checked').val() ||
                'day_of_month',
        };
    }

    function evgeReadCustomRuleFromUpsell() {
        const $p = customRuleUpsellPanel;
        return {
            interval: Math.min(
                99,
                Math.max(1, parseInt($p.find('#evge_custom_rec_interval_upsell').val(), 10) || 1)
            ),
            frequency: String($p.find('#evge_custom_rec_frequency_upsell').val() || 'week'),
            weekdays: $p
                .find('.evge-recurrence-custom-weekday-pill input:checked')
                .map(function () {
                    return parseInt($(this).val(), 10);
                })
                .get()
                .sort((a, b) => a - b),
            monthlyMode: String(
                $p.find('input[name="evge_recurrence_custom_monthly_demo"]:checked').val() || 'day_of_month'
            ),
        };
    }

    function evgeNormalizeCustomRuleFrequency(f) {
        const s = String(f || '')
            .trim()
            .toLowerCase();
        if (s === 'day' || s === 'days' || s === 'daily') {
            return 'day';
        }
        if (s === 'month' || s === 'months' || s === 'monthly') {
            return 'month';
        }
        if (s === 'week' || s === 'weeks' || s === 'weekly') {
            return 'week';
        }
        return 'week';
    }

    /**
     * Weekday toggles only apply when frequency is week; day/month ignore them for preview and storage.
     */
    function evgeRuleForCustomPreview(rule) {
        const frequency = evgeNormalizeCustomRuleFrequency(rule.frequency);
        const weekdays =
            frequency === 'week' && Array.isArray(rule.weekdays) ? rule.weekdays : [];
        return {
            interval: Math.min(99, Math.max(1, parseInt(rule.interval, 10) || 1)),
            frequency: frequency,
            weekdays: weekdays,
            monthlyMode: rule.monthlyMode || 'day_of_month',
        };
    }

    function evgeFormatRecurrenceUnitPhrase(locale, count, frequency) {
        const n = Math.min(99, Math.max(1, parseInt(count, 10) || 1));
        const unit = frequency === 'day' ? 'day' : frequency === 'month' ? 'month' : 'week';
        if (typeof Intl !== 'undefined' && typeof Intl.NumberFormat === 'function') {
            try {
                return new Intl.NumberFormat(locale, {
                    style: 'unit',
                    unit: unit,
                    unitDisplay: 'long',
                }).format(n);
            } catch (ignore) {
                /* Safari / older engines may reject unit style */
            }
        }
        const i18n = window.evgeCPTAdmin && window.evgeCPTAdmin.i18n ? window.evgeCPTAdmin.i18n : {};
        if (frequency === 'day') {
            return n === 1
                ? `1 ${i18n.customRecDay || 'day'}`
                : `${n} ${i18n.customRecDays || 'days'}`;
        }
        if (frequency === 'week') {
            return n === 1
                ? `1 ${i18n.customRecWeek || 'week'}`
                : `${n} ${i18n.customRecWeeks || 'weeks'}`;
        }
        return n === 1
            ? `1 ${i18n.customRecMonth || 'month'}`
            : `${n} ${i18n.customRecMonths || 'months'}`;
    }

    function evgeBuildCustomRecurrenceIntroLine(rule) {
        const i18n = window.evgeCPTAdmin && window.evgeCPTAdmin.i18n ? window.evgeCPTAdmin.i18n : {};
        const abbrev = (window.evgeCPTAdmin && window.evgeCPTAdmin.customRecWeekdayAbbrev) || {};
        const on = i18n.customRecSummaryOn || 'on';
        const iv = rule.interval;
        const freq = evgeNormalizeCustomRuleFrequency(rule.frequency);
        const unitPhrase = evgeFormatRecurrenceUnitPhrase(evgeDateLocale, iv, freq);
        const everyPat = i18n.customRecSummaryEveryPattern || 'Every %s';
        let line = everyPat.replace('%s', unitPhrase);
        if (freq === 'week') {
            const labels = [];
            (rule.weekdays || []).forEach(function (iso) {
                const a = abbrev[String(iso)] !== undefined ? abbrev[String(iso)] : abbrev[iso];
                if (a) {
                    labels.push(a);
                }
            });
            if (labels.length) {
                line += ` ${on} ${labels.join(', ')}`;
            }
        } else if (freq === 'month') {
            const m = rule.monthlyMode;
            const mlabel =
                m === 'nth_weekday'
                    ? i18n.customRecMonthlyNthWeekday || 'nth weekday of month'
                    : i18n.customRecMonthlySameDay || 'same day of month';
            line += ` (${mlabel})`;
        }
        line += '.';
        const start = evgeGetEditorStartAsDate();
        if (start) {
            const ymd = evgeYmdFromDate(
                new Date(start.getFullYear(), start.getMonth(), start.getDate(), 12, 0, 0)
            );
            const startFmt = evgeFormatYmdForCustomPreview(ymd);
            const frag = (i18n.customRecPreviewStartsOn || 'Starts on %s.').replace('%s', startFmt);
            line += ' ' + frag;
        }
        return line;
    }

    function evgeRunCustomOccurrenceCollection(start, endYmd, rule, skipSet) {
        const display = [];
        let extrasRemain = false;
        const startCal = new Date(start.getFullYear(), start.getMonth(), start.getDate(), 12, 0, 0);

        function considerOccurrence(ymd) {
            if (ymd > endYmd) {
                return 'end';
            }
            const p = evgeParseYmdLocal(ymd);
            if (!p || p < startCal) {
                return 'continue';
            }
            if (skipSet && skipSet[ymd]) {
                return 'continue';
            }
            if (display.length < 10) {
                display.push(ymd);
                return 'continue';
            }
            extrasRemain = true;
            return 'stop';
        }

        const freq = evgeNormalizeCustomRuleFrequency(rule.frequency);
        const interval = rule.interval;
        const MAX_STEPS = 10000;

        if (freq === 'day') {
            let cur = new Date(startCal);
            let steps = 0;
            while (steps < MAX_STEPS) {
                const ymd = evgeYmdFromDate(cur);
                if (ymd > endYmd) {
                    break;
                }
                const st = considerOccurrence(ymd);
                if (st === 'stop') {
                    break;
                }
                cur.setDate(cur.getDate() + interval);
                steps++;
            }
        } else if (freq === 'week') {
            if (!rule.weekdays.length) {
                return { ymds: display, hasMore: false };
            }
            const refMon = evgeMondayOf(startCal);
            let d = new Date(startCal);
            let steps = 0;
            while (steps < MAX_STEPS && evgeYmdFromDate(d) <= endYmd) {
                const iso = evgeIsoDow(d);
                if (rule.weekdays.indexOf(iso) !== -1) {
                    const wMon = evgeMondayOf(d);
                    const weekIx = Math.round((wMon - refMon) / (86400000 * 7));
                    if (weekIx >= 0 && weekIx % interval === 0) {
                        const st = considerOccurrence(evgeYmdFromDate(d));
                        if (st === 'stop') {
                            break;
                        }
                    }
                }
                d.setDate(d.getDate() + 1);
                steps++;
            }
        } else if (freq === 'month') {
            const mode = rule.monthlyMode || 'day_of_month';
            if (mode === 'day_of_month') {
                const dom0 = startCal.getDate();
                for (let k = 0; k < 600; k++) {
                    const t = new Date(
                        startCal.getFullYear(),
                        startCal.getMonth() + k * interval,
                        1,
                        12,
                        0,
                        0
                    );
                    const y = t.getFullYear();
                    const m = t.getMonth();
                    const dim = evgeDaysInMonth(y, m);
                    const day = Math.min(dom0, dim);
                    const cand = new Date(y, m, day, 12, 0, 0);
                    if (cand < startCal) {
                        continue;
                    }
                    const ymd = evgeYmdFromDate(cand);
                    if (ymd > endYmd) {
                        break;
                    }
                    const st = considerOccurrence(ymd);
                    if (st === 'stop') {
                        break;
                    }
                }
            } else {
                const targetIso = evgeIsoDow(startCal);
                const ord = evgeWeekdayOrdinalInMonth(startCal);
                if (ord < 1) {
                    return { ymds: display, hasMore: false };
                }
                for (let k = 0; k < 600; k++) {
                    const bm = new Date(
                        startCal.getFullYear(),
                        startCal.getMonth() + k * interval,
                        1,
                        12,
                        0,
                        0
                    );
                    const y = bm.getFullYear();
                    const m = bm.getMonth();
                    let foundYmd = null;
                    let c = 0;
                    for (let day = 1; day <= 31; day++) {
                        const t = new Date(y, m, day, 12, 0, 0);
                        if (t.getMonth() !== m) {
                            break;
                        }
                        if (evgeIsoDow(t) === targetIso) {
                            c++;
                            if (c === ord) {
                                foundYmd = evgeYmdFromDate(t);
                                break;
                            }
                        }
                    }
                    if (!foundYmd) {
                        continue;
                    }
                    if (evgeParseYmdLocal(foundYmd) < startCal) {
                        continue;
                    }
                    if (foundYmd > endYmd) {
                        break;
                    }
                    const st = considerOccurrence(foundYmd);
                    if (st === 'stop') {
                        break;
                    }
                }
            }
        }

        return { ymds: display, hasMore: extrasRemain };
    }

    function evgeFillCustomRecurrencePreview($wrap, rule) {
        const $intro = $wrap.find('.evge-recurrence-custom-preview-intro');
        const $ul = $wrap.find('.evge-recurrence-custom-preview-dates');
        const $more = $wrap.find('.evge-recurrence-custom-preview-more');
        const start = evgeGetEditorStartAsDate();
        const endYmd = evgeGetRecurrenceEndYmdForPreview();
        if (!start || !endYmd) {
            $intro.text('');
            $ul.empty();
            $more.addClass('evge-hidden').text('');
            return;
        }
        const rulePreview = evgeRuleForCustomPreview(rule);
        $intro.text(evgeBuildCustomRecurrenceIntroLine(rulePreview));
        const i18n = window.evgeCPTAdmin && window.evgeCPTAdmin.i18n ? window.evgeCPTAdmin.i18n : {};
        const skipSet = evgeGetSkipYmdSet();
        const { ymds, hasMore } = evgeRunCustomOccurrenceCollection(start, endYmd, rulePreview, skipSet);
        $ul.empty();
        ymds.forEach(function (ymd) {
            $ul.append($('<li/>').text(evgeFormatYmdForCustomPreview(ymd)));
        });
        if (hasMore) {
            $more.removeClass('evge-hidden').text(i18n.customRecPreviewAndMore || '(and more)');
        } else {
            $more.addClass('evge-hidden').text('');
        }
    }

    function evgeSyncCustomRecurrenceProRows() {
        if (!customRuleProPanel.length || !hasProCustomSchedules) {
            return;
        }
        const freq = String($('#evge_custom_rec_frequency').val() || 'week');
        customRuleProPanel.find('.evge-recurrence-custom-row-week').toggleClass('evge-hidden', freq !== 'week');
        customRuleProPanel.find('.evge-recurrence-custom-row-month').toggleClass('evge-hidden', freq !== 'month');
    }

    function evgeUpdateCustomRecurrencePreviews() {
        if (recurrenceSelect.val() !== 'custom') {
            $('.evge-recurrence-custom-preview-intro').text('');
            $('.evge-recurrence-custom-preview-dates').empty();
            $('.evge-recurrence-custom-preview-more').addClass('evge-hidden').text('');
            return;
        }
        if (customRuleProPanel.length && hasProCustomSchedules && !customRuleProPanel.hasClass('evge-hidden')) {
            const rulePro = evgeReadCustomRuleFromPro();
            evgeFillCustomRecurrencePreview(
                customRuleProPanel.find('.evge-recurrence-custom-preview'),
                rulePro
            );
        }
        if (customRuleUpsellPanel.length && !customRuleUpsellPanel.hasClass('evge-hidden')) {
            const ruleUp = evgeReadCustomRuleFromUpsell();
            evgeFillCustomRecurrencePreview(
                customRuleUpsellPanel.find('.evge-recurrence-custom-preview'),
                ruleUp
            );
        }
    }

    function updateRecurrenceText() {
        // Get the start date value and handle both datetime-local and date input types
        const startDateValue = startDateInput.val();
        if (!startDateValue) {
            return;
        }
        let startDate;

        if (startDateValue.includes('T')) {
            // For datetime-local input
            startDate = new Date(startDateValue);
        } else {
            // For date input, use the data-time attribute if available
            const timeComponent = startDateInput.attr('data-time') || '00:00';
            startDate = new Date(startDateValue + 'T' + timeComponent);
        }

        const dayName = startDate.toLocaleDateString(evgeDateLocale, { weekday: 'long' });
        const weekNum = Math.ceil(startDate.getDate() / 7);
        const ordinals =
            window.evgeCPTAdmin && window.evgeCPTAdmin.monthOrdinals && window.evgeCPTAdmin.monthOrdinals.length
                ? window.evgeCPTAdmin.monthOrdinals
                : ['first', 'second', 'third', 'fourth', 'fifth'];
        const weekNumText = ordinals[weekNum - 1] || String(weekNum);

        // Update all options that have a format
        recurrenceSelect.find('option').each(function () {
            const $option = $(this);
            const format = $option.data('format');

            if (format) {
                if ($option.val() === 'weekly') {
                    $option.text(format.replace('%s', dayName));
                } else if ($option.val() === 'monthly') {
                    $option.text(format.replace('%s', `${weekNumText} ${dayName}`));
                }
            }
        });
    }

    function syncRecurrenceTypeDependentUi() {
        const v = recurrenceSelect.val();
        if (v === 'none') {
            endDateDiv.addClass('evge-hidden');
            afterRecurrencePanel.addClass('evge-hidden');
            if (customRuleUpsellPanel.length) {
                customRuleUpsellPanel.addClass('evge-hidden');
            }
            if (customRuleProPanel.length) {
                customRuleProPanel.addClass('evge-hidden');
            }
        } else if (v === 'custom' && customRuleUpsellPanel.length) {
            endDateDiv.addClass('evge-hidden');
            afterRecurrencePanel.removeClass('evge-hidden');
            customRuleUpsellPanel.removeClass('evge-hidden');
            if (customRuleProPanel.length) {
                customRuleProPanel.addClass('evge-hidden');
            }
        } else if (v === 'custom' && customRuleProPanel.length) {
            endDateDiv.removeClass('evge-hidden');
            afterRecurrencePanel.removeClass('evge-hidden');
            customRuleProPanel.removeClass('evge-hidden');
            if (customRuleUpsellPanel.length) {
                customRuleUpsellPanel.addClass('evge-hidden');
            }
        } else {
            endDateDiv.removeClass('evge-hidden');
            afterRecurrencePanel.removeClass('evge-hidden');
            if (customRuleUpsellPanel.length) {
                customRuleUpsellPanel.addClass('evge-hidden');
            }
            if (customRuleProPanel.length) {
                customRuleProPanel.addClass('evge-hidden');
            }
        }
        if (scheduleRoot.length) {
            scheduleRoot.toggleClass('evge-recurrence-layout-custom', v === 'custom');
        }
    }

    if (customRuleProPanel.length && hasProCustomSchedules) {
        customRuleProPanel.on('change', 'input, select', function () {
            evgeSyncCustomRecurrenceProRows();
            evgeUpdateCustomRecurrencePreviews();
        });
        customRuleProPanel.on('input', '#evge_custom_rec_interval', function () {
            evgeSyncCustomRecurrenceProRows();
            evgeUpdateCustomRecurrencePreviews();
        });
    }

    // Show/hide end date, custom rule preview, skip dates; update labels when recurrence type changes
    recurrenceSelect.on('change', function () {
        syncRecurrenceTypeDependentUi();
        updateRecurrenceText();
        evgeSyncCustomRecurrenceProRows();
        evgeUpdateCustomRecurrencePreviews();
    });

    // Update text when start date changes
    startDateInput.on('change', function () {
        updateRecurrenceText();
        evgeUpdateCustomRecurrencePreviews();
    });

    // Also update when all-day toggle changes since it modifies the input type
    // Use event delegation to work with global toggle handler
    $('body').on('click', '#evge-single-setting-all-day .evge-settings-toggle', function () {
        // Wait for the input type to be updated
        setTimeout(function () {
            updateRecurrenceText();
            evgeUpdateCustomRecurrencePreviews();
        }, 100);
    });

    $('#evge_recurrence_end_date').on('change', function () {
        evgeUpdateCustomRecurrencePreviews();
    });

    // Initial text update
    syncRecurrenceTypeDependentUi();
    updateRecurrenceText();
    evgeSyncCustomRecurrenceProRows();
    evgeUpdateCustomRecurrencePreviews();

    const $skipPro = $('.evge-recurrence-skip-dates--pro');
    if ($skipPro.length) {
        const $skipList = $skipPro.find('.evge-recurrence-skip-dates-list');
        const $skipInput = $skipPro.find('.evge-recurrence-skip-date-input');
        const $skipHidden = $skipPro.find('#evge_recurrence_skip_dates');
        const skipI18n =
            window.evgeCPTAdmin && window.evgeCPTAdmin.i18n ? window.evgeCPTAdmin.i18n : {};

        function evgeGetSkipDates() {
            return $skipList
                .find('.evge-recurrence-skip-dates-pill')
                .map(function () {
                    return $(this).attr('data-date');
                })
                .get()
                .filter(Boolean);
        }

        function evgeSyncSkipHidden() {
            const dates = evgeGetSkipDates().sort();
            $skipHidden.val(JSON.stringify(dates));
        }

        function evgeAddSkipDate(raw, options) {
            const silent = options && options.silent;
            const v = (raw || '').trim();
            if (!v) {
                if (!silent) {
                    window.alert(skipI18n.skipDateInvalid || 'Choose a valid date to add.');
                }
                return;
            }
            if ($skipList.find('[data-date="' + v + '"]').length) {
                if (!silent) {
                    window.alert(skipI18n.skipDateDuplicate || 'That date is already in the skip list.');
                }
                return;
            }
            const removeLabel = skipI18n.skipDateRemoveLabel || 'Remove skip date';
            const $pill = $('<li class="evge-recurrence-skip-dates-pill"></li>').attr('data-date', v);
            const $pillLabel = $('<span class="evge-recurrence-skip-dates-pill-label"></span>').text(
                evgeFormatYmdForDisplay(v)
            );
            const $remove = $('<button type="button" class="evge-recurrence-skip-dates-remove"></button>')
                .attr('aria-label', removeLabel)
                .html(typeof evgeIcon !== 'undefined' ? evgeIcon.close : '&times;');
            $pill.append($pillLabel, $remove);
            $skipList.append($pill);
            $skipInput.val('');
            evgeSyncSkipHidden();
            evgeUpdateCustomRecurrencePreviews();
        }

        $skipInput.on('keydown', function (e) {
            if (e.key === 'Enter') {
                e.preventDefault();
                evgeAddSkipDate($skipInput.val());
            }
        });

        $skipInput.on('change', function () {
            const v = $skipInput.val();
            if (v) {
                evgeAddSkipDate(v);
            }
        });

        $skipList.on('click', '.evge-recurrence-skip-dates-remove', function (e) {
            e.preventDefault();
            $(this).closest('.evge-recurrence-skip-dates-pill').remove();
            evgeSyncSkipHidden();
            evgeUpdateCustomRecurrencePreviews();
        });

        (function evgeBootstrapSkipDatesFromHidden() {
            const raw = ($skipHidden.val() || '').trim();
            if (!raw || raw === '[]') {
                return;
            }
            try {
                const arr = JSON.parse(raw);
                if (!Array.isArray(arr)) {
                    return;
                }
                arr.sort().forEach(function (ymd) {
                    if (ymd && typeof ymd === 'string') {
                        evgeAddSkipDate(ymd, { silent: true });
                    }
                });
            } catch (ignore) {
                /* ignore */
            }
        })();
    }

    if ($('.evge-queue-processing-modal-trigger').length) {
        evgeCheckSeriesQueue();
    }

    // Queue processing functionality
    function evgeCheckSeriesQueue() {
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'evge_check_series_queue',
                nonce: evgeCPTAdmin.nonce
            },
            success: function (response) {
                if (response.success && response.data.pending_tasks > 0) {
                    if (response.data.modal_html) {
                        window.evgeShowQueueProcessingModal(response);
                    }
                } else {
                    $('.evge-modal-close').trigger('click');
                    $('.evge-queue-processing-modal-content').remove();
                }
            }
        });
    }

    window.evgeProcessQueueBatch = function (currentBatch, maxBatches, isCreation, seriesId) {
        if (seriesId) {
            $('.evge-undo-recurrence-create').data('series-id', seriesId);
        }
        // Safety check to prevent infinite loops
        if (currentBatch > maxBatches && maxBatches > 0) {
            console.log('Reached maximum number of batch processing attempts', currentBatch, maxBatches);
            return;
        }

        // Also limit to a reasonable number regardless of estimated batches
        if (currentBatch > 30) {
            console.log('Reached hard limit of batch processing attempts');
            return;
        }

        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'evge_process_series_queue_batch',
                nonce: evgeCPTAdmin.nonce
            },
            success: function (response) {
                if (response.success) {

                    if (response.data.is_completed) {
                        const totalEv = parseInt(response.data.total_events, 10) || 0;
                        const processedEv = parseInt(response.data.processed_events, 10) || 0;

                        // Empty counts at completion only: never showed real totals/processed during this run (spurious queue).
                        if (totalEv === 0 && processedEv === 0 && !window.evgeQueueHadNonZeroEventCounts) {
                            const i18n = (window.evgeCPTAdmin && window.evgeCPTAdmin.i18n) ? window.evgeCPTAdmin.i18n : {};
                            const titleText = i18n.recurrenceProcessingCompleteTitle || 'Success!';
                            const bodyText = i18n.recurrenceProcessingCompleteMessage || 'Your recurring events are saved.';
                            const closeText = i18n.close || 'Close';
                            const $wrapper = $('.evge-modal-evge-queue-processing-modal-content');
                            if ($wrapper.length) {
                                $wrapper.html(`
									<div class="evge-narrow-modal-inner evge-recurrence-modal-content-inner">
										<div class="evge-modal-section">
											<div class="evge-standard-dialog">
												<p><strong>${titleText}</strong></p>
												<p>${bodyText}</p>
											</div>
											<div class="evge-modal-actions">
												<button type="button" class="button evge-modal-close">${closeText}</button>
											</div>
										</div>
									</div>
								`);
                                $wrapper.find('.evge-modal-close').on('click', function () {
                                    $('body').removeClass('evge-modal-is-open');
                                    $(document).trigger('evge_admin_modal_closed');
                                });
                            }
                        } else {
                            // All done — normal progress UI
                            $('.evge-progress-bar').css('width', '100%');
                            $('.evge-processed-count').text($('.evge-total-count').attr('data-total-events'));

                            // Show undo button if we're creating new events
                            if (isCreation && seriesId) {
                                $('.evge-undo-recurrence-create')
                                    .prop('disabled', false)
                                    .off('click')
                                    .on('click', function () {
                                        const $button = $(this);
                                        const seriesId = $('.evge-undo-recurrence-create').data('series-id');
                                        $button.prop('disabled', true);

                                        $.ajax({
                                            url: ajaxurl,
                                            type: 'POST',
                                            data: {
                                                action: 'evge_trash_all_recurrences',
                                                nonce: evgeCPTAdmin.nonce,
                                                series_id: seriesId,
                                                include_template_event: false
                                            },
                                            success: function (response) {
                                                if (response.success) {
                                                    const undoMsg = response.data.message || 'Recurrence creation has been undone successfully.';
                                                    const i18nClose = (window.evgeCPTAdmin && window.evgeCPTAdmin.i18n && window.evgeCPTAdmin.i18n.close) ? window.evgeCPTAdmin.i18n.close : 'Close';
                                                    // Match AdminCustomPostTypeService trash/success modal markup (padding + dialog spacing)
                                                    $('.evge-modal-content').html(`
														<div class="evge-narrow-modal-inner evge-recurrence-modal-content-inner">
															<div class="evge-modal-section">
																<div class="evge-standard-dialog">
																	<p>${undoMsg}</p>
																</div>
																<div class="evge-modal-actions">
																	<button type="button" class="button evge-modal-close">${i18nClose}</button>
																</div>
															</div>
														</div>
													`);
                                                } else {
                                                    $button.prop('disabled', false);
                                                    alert(response.data.message || 'Failed to undo recurrence creation.');
                                                }
                                            },
                                            error: function () {
                                                $button.prop('disabled', false);
                                                alert('Failed to undo recurrence creation.');
                                            }
                                        });
                                    });
                            }
                        }
                    } else {
                        // Update progress
                        window.evgeNoteSeriesQueueEventCounts(response.data.total_events, response.data.processed_events);
                        const progress = (response.data.processed_events / response.data.total_events) * 100;
                        $('.evge-progress-bar').css('width', progress + '%');
                        $('.evge-total-count').text(response.data.total_events).attr('data-total-events', response.data.total_events);
                        $('.evge-processed-count').text(response.data.processed_events);
                        // Process next batch
                        setTimeout(function () {
                            window.evgeProcessQueueBatch(currentBatch + 1, maxBatches, isCreation, seriesId);
                        }, 1000); // 1 second delay to prevent overwhelming the server
                    }
                } else {
                    // Error handling
                    console.error('Error processing queue batch', response);
                }
            },
            error: function () {
                console.error('AJAX error while processing queue batch');
            }
        });
    }

    // Handle recurrence trash modal
    $('.evge-trash-recurrence').on('click', function (e) {
        e.preventDefault();
        const $link = $(this);
        const recurrenceId = $link.attr('href').split('id=')[1].split('&')[0];
        const templateId = $link.closest('tr').find('input[name="event[]"]').val();

        // Show loading state
        const loadingContent = `
			<div class="evge-narrow-modal-inner evge-recurrence-modal-content-inner">
				<div class="evge-modal-section">
					<div class="evge-standard-dialog">
						<p>${evgeCPTAdmin.i18n.loading}</p>
					</div>
				</div>
			</div>
		`;

        // Show modal with loading state
        $('.evge-modal-placeholder').html(loadingContent);
        $('.evge-modal').addClass('evge-narrow-max-width-modal evge-centered-modal evge-recurrence-modal').removeClass('evge-medium-max-width-modal');
        $('body').addClass('evge-modal-is-open');

        // Fetch series information
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'evge_get_recurrence_trash_options',
                nonce: evgeCPTAdmin.nonce,
                event_id: recurrenceId
            },
            success: function (response) {
                if (response.success) {
                    // Update modal with server-generated HTML
                    $('.evge-modal-placeholder').html(response.data.html);

                    // Handle modal actions
                    $('.evge-trash-single-recurrence').on('click', function () {
                        window.location.href = $link.attr('href');
                    });

                    $('.evge-trash-all-recurrences').on('click', function (event) {
                        event.preventDefault();
                        const $button = $(this);
                        $button.prop('disabled', true);

                        $.ajax({
                            url: ajaxurl,
                            type: 'POST',
                            data: {
                                action: 'evge_trash_all_recurrences',
                                nonce: evgeCPTAdmin.nonce,
                                series_id: $button.data('series-id')
                            },
                            success: function (response) {
                                if (response.success) {
                                    // Update modal with success content
                                    $('.evge-modal-placeholder').html(response.data.html);

                                    // Add listeners for all modal closing methods
                                    $('.evge-modal-close, .evge-modal-backdrop, .evge-action-modal-close').on('click', function () {
                                        $('body').removeClass('evge-modal-is-open');
                                        window.location.reload();
                                    });
                                } else {
                                    $button.prop('disabled', false);
                                    alert(response.data.message || evgeCPTAdmin.i18n.errorTrashingRecurrences);
                                }
                            },
                            error: function () {
                                $button.prop('disabled', false);
                                alert(evgeCPTAdmin.i18n.errorTrashingRecurrences);
                            }
                        });
                    });

                    $('.evge-modal-close').on('click', function () {
                        $('body').removeClass('evge-modal-is-open');
                    });
                } else {
                    alert(response.data.message || evgeCPTAdmin.i18n.errorLoadingSeriesInfo);
                }
            },
            error: function () {
                alert(evgeCPTAdmin.i18n.errorLoadingSeriesInfo);
            }
        });

        $('.evge-modal-close, .evge-modal-backdrop, .evge-action-modal-close').on('click', function () {
            $('body').removeClass('evge-modal-is-open');
        });
    });

    // Handle template event trash modal
    $('.evge-trash-template').on('click', function (e) {
        e.preventDefault();
        const $link = $(this);
        const eventId = $link.attr('href').split('id=')[1].split('&')[0];

        // Show loading state
        const loadingContent = `
			<div class="evge-narrow-modal-inner evge-recurrence-modal-content-inner">
				<div class="evge-modal-section">
					<div class="evge-standard-dialog">
						<p>${evgeCPTAdmin.i18n.loading}</p>
					</div>
				</div>
			</div>
		`;

        // Show modal with loading state
        $('.evge-modal-placeholder').html(loadingContent);
        $('.evge-modal').addClass('evge-narrow-max-width-modal evge-centered-modal evge-recurrence-modal').removeClass('evge-medium-max-width-modal');
        $('body').addClass('evge-modal-is-open');

        // Fetch template event trash options
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'evge_get_recurrence_template_trash_options',
                nonce: evgeCPTAdmin.nonce,
                event_id: eventId
            },
            success: function (response) {
                if (response.success) {
                    // Update modal with server-generated HTML
                    $('.evge-modal-placeholder').html(response.data.html);

                    $('.evge-modal-close, .evge-modal-backdrop, .evge-action-modal-close').on('click', function () {
                        $('body').removeClass('evge-modal-is-open');
                    });
                    // Handle template event deletion
                    $('.evge-trash-template-event').on('click', function (event) {
                        event.preventDefault();
                        const $button = $(this);
                        const eventId = $button.data('event-id');
                        $button.prop('disabled', true);


                        $.ajax({
                            url: ajaxurl,
                            type: 'POST',
                            data: {
                                action: 'evge_trash_all_recurrences',
                                include_template_event: true,
                                nonce: evgeCPTAdmin.nonce,
                                event_id: eventId
                            },
                            success: function (response) {
                                if (response.success) {
                                    window.location.reload();
                                } else {
                                    $button.prop('disabled', false);
                                    alert(response.data.message || evgeCPTAdmin.i18n.errorTrashingTemplate);
                                }
                            },
                            error: function () {
                                $button.prop('disabled', false);
                                alert(evgeCPTAdmin.i18n.errorTrashingTemplate);
                            }
                        });
                    });
                } else {
                    alert(response.data.message || evgeCPTAdmin.i18n.errorLoadingSeriesInfo);
                }
            },
            error: function () {
                alert(evgeCPTAdmin.i18n.errorLoadingSeriesInfo);
            }
        });

        // Handle modal closing
        $('.evge-modal-close, .evge-modal-backdrop, .evge-action-modal-close').on('click', function () {
            $('body').removeClass('evge-modal-is-open');
            // Trigger custom event for admin modal close
            $(document).trigger('evge_admin_modal_closed');
        });
    });

});