jQuery(document).ready(function ($) {
    // Toggle label text
    $('#speeinch-schedule-enabled').on('change', function () {
        $(this).next('span').text($(this).is(':checked') ? speeinchSchedule.activeText : speeinchSchedule.inactiveText);
    });

    // Save schedule
    $('#speeinch-schedule-form').on('submit', function (e) {
        e.preventDefault();

        var btn = $('#speeinch-save-schedule');
        var spinner = $('#speeinch-schedule-spinner');
        var status = $('#speeinch-schedule-status');

        btn.attr('disabled', true);
        spinner.addClass('is-active');
        status.html('');

        $.ajax({
            type: 'POST',
            url: speeinch.ajaxurl,
            data: {
                action: 'speeinch_save_schedule',
                security: $('#speeinch_schedule_security').val(),
                schedule_enabled: $('#speeinch-schedule-enabled').is(':checked') ? 1 : 0,
                schedule_frequency: $('#speeinch-schedule-frequency').val()
            },
            success: function (response) {
                spinner.removeClass('is-active');
                btn.attr('disabled', false);
                if (response.success) {
                    status.html('<span style="color:#22c55e;">✓ ' + response.data.message + '</span>');
                    if (response.data.next_run) {
                        // Refresh to show next run time
                        setTimeout(function () { location.reload(); }, 1000);
                    }
                } else {
                    status.html('<span style="color:#ef4444;">✗ ' + (response.data || 'Failed') + '</span>');
                }
            },
            error: function (xhr) {
                spinner.removeClass('is-active');
                btn.attr('disabled', false);
                status.html('<span style="color:#ef4444;">✗ Request failed (HTTP ' + xhr.status + ')</span>');
            }
        });
    });
});
