jQuery(function($) {
    $('input[name="widget_display_mode"]').on('change', function() {
        if ($(this).val() === 'all') {
            $('.widget-pages-row').hide();
        } else {
            $('.widget-pages-row').show();
        }
    });
    if ($.fn.select2 && $('.inqyra-select2-pages').length) {
        $('.inqyra-select2-pages').select2({
            ajax: {
                url: inqyraAdmin.ajaxUrl,
                dataType: 'json',
                delay: 300,
                data: function(params) {
                    return {
                        action: 'inqyra_search_pages',
                        nonce: inqyraAdmin.nonce,
                        search: params.term
                    };
                },
                processResults: function(data) {
                    return { results: data.data || [] };
                }
            },
            minimumInputLength: 2,
            placeholder: inqyraAdmin.strings.search_pages || 'Search pages...',
            width: '100%'
        });
    }
    $('#inqyra-page-targeting-form').on('submit', function(e) {
        e.preventDefault();
        var $btn = $('#inqyra-save-page-targeting');
        var $spinner = $btn.next('.spinner');
        $btn.prop('disabled', true);
        $spinner.addClass('is-active');
        var formData = $(this).serializeArray();
        formData.push({ name: 'action', value: 'inqyra_save_agent' });
        formData.push({ name: 'nonce', value: inqyraAdmin.nonce });
        if (!$('#widget_pages').val() || $('#widget_pages').val().length === 0) {
            formData.push({ name: 'widget_pages[]', value: '' });
        }
        $.post(inqyraAdmin.ajaxUrl, formData, function(response) {
            $btn.prop('disabled', false);
            $spinner.removeClass('is-active');
            if (response.success) {
                $btn.text(inqyraAdmin.strings.saved || 'Saved!');
                setTimeout(function() {
                    $btn.text(inqyraAdmin.strings.save_changes || 'Save Changes');
                }, 2000);
            } else {
                alert(response.data && response.data.message ? response.data.message : inqyraAdmin.strings.error);
            }
        }).fail(function() {
            $btn.prop('disabled', false);
            $spinner.removeClass('is-active');
            alert(inqyraAdmin.strings.error);
        });
    });
});
