/**
 * Settings Page JS for Codeandcore User Registration for CF7
 */
(function($) {
    'use strict';

    $(document).ready(function() {
        const $container = $('.cnc-cf7-settings-container');
        const $spinner = $container.find('.spinner');
        const $statusBadge = $container.find('.cnc-cf7-status-badge');
        const $enableBtn = $container.find('.cnc-cf7-enable-tracking');
        const $disableBtn = $container.find('.cnc-cf7-disable-tracking');

        function updateStatusUI(status) {
            if (status === 'yes') {
                $statusBadge.removeClass('disabled').addClass('enabled');
                $statusBadge.html('<span class="dashicons dashicons-yes"></span> ' + 'ENABLED');
                $enableBtn.prop('disabled', true);
                $disableBtn.prop('disabled', false);
            } else {
                $statusBadge.removeClass('enabled').addClass('disabled');
                $statusBadge.html('<span class="dashicons dashicons-no"></span> ' + 'DISABLED');
                $enableBtn.prop('disabled', false);
                $disableBtn.prop('disabled', true);
            }
        }

        function handleTrackingChange(status) {
            $spinner.addClass('is-active');
            
            $.ajax({
                url: cnc_cf7_settings.ajaxurl,
                type: 'POST',
                data: {
                    action: 'cnc_cf7_tracking_optin',
                    status: status,
                    nonce: cnc_cf7_settings.nonce
                },
                success: function(response) {
                    $spinner.removeClass('is-active');
                    if (response.success) {
                        updateStatusUI(status);
                        // Optional: Show a toast/notice
                    } else {
                        alert(cnc_cf7_settings.strings.optin_error);
                    }
                },
                error: function() {
                    $spinner.removeClass('is-active');
                    alert(cnc_cf7_settings.strings.optin_error);
                }
            });
        }

        $enableBtn.on('click', function() {
            handleTrackingChange('yes');
        });

        $disableBtn.on('click', function() {
            handleTrackingChange('no');
        });
    });

})(jQuery);
