(function() {
    var radios = document.querySelectorAll('input[name="sitestaffr_knowledge_mode"]');
    var status = document.getElementById('knowledge-mode-status');
    if (!radios.length || !status) return;
    var previousValue = document.querySelector('input[name="sitestaffr_knowledge_mode"]:checked');
    previousValue = previousValue ? previousValue.value : 'search';

    radios.forEach(function(radio) {
        radio.addEventListener('change', function() {
            var selected = this;
            status.textContent = 'Saving...';
            status.style.color = '#666';

            var data = new FormData();
            data.append('action', 'sitestaffr_save_knowledge_mode');
            data.append('nonce', sitestaffr_knowledge.knowledge_mode_nonce);
            data.append('knowledge_mode', selected.value);
            fetch(sitestaffr_knowledge.ajax_url, { method: 'POST', body: data })
                .then(function(r) { return r.json(); })
                .then(function(d) {
                    if (d.success) {
                        status.textContent = 'Saved';
                        status.style.color = '#10b981';
                        previousValue = selected.value;
                        setTimeout(function() { status.textContent = ''; }, 2000);
                    } else {
                        status.textContent = 'Save failed';
                        status.style.color = '#991b1b';
                        var prev = document.querySelector('input[name="sitestaffr_knowledge_mode"][value="' + previousValue + '"]');
                        if (prev) prev.checked = true;
                    }
                })
                .catch(function() {
                    status.textContent = 'Save failed';
                    status.style.color = '#991b1b';
                    var prev = document.querySelector('input[name="sitestaffr_knowledge_mode"][value="' + previousValue + '"]');
                    if (prev) prev.checked = true;
                });
        });
    });
})();
