$( document ).ready(function() {
    $(document).on('input', '#af2_iconpicker_search', function() {
        const value = $(this).val();
        const iconpicker = $(this).closest('.af2_fontawesome_iconpicker');

        $(iconpicker).find('.af2_iconpicker_icon').removeClass('af2_hide');
        $($(iconpicker).find('.af2_iconpicker_icon').toArray().filter(element => !$(element).data('iconid').toLowerCase().includes(value))).addClass('af2_hide');
    });

    $(document).on('click', '.af2_iconpicker_icon', function(e) {
        const iconpicker = $(this).closest('.af2_fontawesome_iconpicker');
        $(iconpicker).find('.af2_iconpicker_icon').removeClass('selected');
        $(this).addClass('selected');
        $(iconpicker).find('#af2_iconpicker_save').attr('data-iconvalue', $(this).data('iconid'));
    });

    $(document).on('click', '#af2_iconpicker_save', function() { 
        const id = $(this).data('objectid');
        const iconpicker = $(this).closest('.af2_fontawesome_iconpicker');
        const val = $(iconpicker).find('#af2_iconpicker_save').data('iconvalue');

        if(val == null || val.trim() == '') { af2_close_modal(); return; }

        let event = jQuery.Event('icon_picked');
        event.value = val;
        event.object_id = id;
        $('#'+id).trigger(event);
        af2_close_modal();
    });
});