jQuery(function ($) {

    const feedback = $("#sifency-ajax-feedback");

    function showMessage(msg, type = "success") {
        feedback
            .html("<p>" + msg + "</p>")
            .removeClass()
            .addClass("notice notice-" + type)
            .fadeIn();

        setTimeout(() => feedback.fadeOut(), 1800);
    }

    function saveSetting(el) {
        const $el = $(el);
        const name = $el.data("setting");
        let value = $el.is(":checkbox") ? ($el.is(":checked") ? "on" : "off") : $el.val();

        $.post(SifencyOptions.ajaxurl, {
            action: "sifency_save_admin_setting",
            nonce: SifencyOptions.nonce,
            setting_name: name,
            setting_value: value
        })
        .done(res => {
            if (res.success) showMessage("Saved!", "success");
            else showMessage(res.data.message, "error");
        })
        .fail(() => showMessage("AJAX error occurred", "error"));
    }

    // Save checkboxes instantly
    $(document).on("change", ".sifency-ajax-save[type='checkbox']", function () {
        saveSetting(this);
    });

    // Debounced save for textarea input
    let timer = null;
    $(document).on("keyup", ".sifency-ajax-save:not([type='checkbox'])", function () {
        const el = this;
        clearTimeout(timer);
        timer = setTimeout(() => saveSetting(el), 800);
    });

});
