export default function ($) {

    let ufilterData = {
        filters: {
            price: {
                fields: {
                    i: 'price_min',
                        x: 'price_max'
                }
            },
            date: {
                fields: {
                    i: 'date_min',
                        x: 'date_max'
                }
            },
            leader: {
                select: 'leaders',
                    field: 'l'
            },
            place: {
                select: 'places',
                    field: 'p'
            },
            status: {
                select: 'status',
                    field: 's'
            },
            search: {
                fields: {
                    q: 'search'
                }
            },
            tag: {
                select: 'tag',
                    field: 't'
            },
            category: {
                select: 'category',
                    field: 'c'
            },
        },
        popovers_open : null,
            popovers : [],
            createFilterString: function(filterKey) {
            var filterData = ufilterData.filters[filterKey];
            var filterStr = filterKey + '=';
            var fillterArr = [];
            if (filterData.fields) {
                for (var fieldIndex in filterData.fields) {
                    var fieldValue = $('.popover-content .f-' + filterData.fields[fieldIndex]).val();
                    filterStr += fieldIndex + ':' + encodeURIComponent(fieldValue) + ',';
                }
            } else if (filterData.select) {
                if(filterKey == 'tag') {
                    var uniqueValues = new Set();
                }
                $('.popover-content .f-' + filterData.select + '-v:checked').each(function() {
                    filterStr += $(this).val() + ',';
                    if(filterKey == 'tag') {
                        let parts = $(this).data('tags').split("..");
                        parts.forEach(part => {
                            uniqueValues.add(part);
                        });
                    }
                });
                if(filterKey == 'tag') {
                    $('.f-form-tag').val([...uniqueValues].join('..'));
                    console.info($('.f-form-tag').val());
                }
            }
            return filterStr.slice(0, -1);  // Letztes Komma entfernen
        },
        removeFilterFromString: function(filterString, filterKey) {
            var filterRegex = new RegExp(filterKey + '=[^|]*\\|?');
            return filterString.replace(filterRegex, '');
        },
        addFilterToString: function(filterString, filterKey) {
            var newFilterValue = ufilterData.createFilterString(filterKey);
            filterString = ufilterData.removeFilterFromString(filterString, filterKey);  // Entfernen Sie zuerst den vorhandenen Filterwert (falls vorhanden)
            // Fügen Sie den neuen Filterwert hinzu
            if (filterString) {
                return filterString + '|' + newFilterValue;
            } else {
                return newFilterValue;
            }
        },
        filterExists: function(filterString, filterKey) {
            var filterRegex = new RegExp(filterKey + '=[^|]*');
            return filterRegex.test(filterString);
        },
        getPopoverContent: function(templateClass) {
            // Hauptgerüst kopieren
            var template = $('.ed-filter-templates .f-default').clone();
            // Inhalt für den Slot extrahieren
            var slotContent = $('.ed-filter-templates .f-' + templateClass).html();
            // Inhalt im Slot des Hauptgerüsts ersetzen
            template.find('.filter-slot').html(slotContent);
            return template.html();
        },
        initPopover : function (elm, filter){
            if(!ufilterData.popovers.includes(filter)) {
                $(elm).popover({
                    placement: 'auto',
                    sanitize: false,
                    // trigger: "click",
                    container: false,//'div.row.show-grid',
                    template: '<div class="popover ed-filter-popover col-xs-12 col-sm-10 col-md-10" role="tooltip">' +
                        '<div class="arrow"></div>' +
                        '<div class="popover-header"><h3 class="popover-title"></h3></div>' +
                        '<div class="popover-content"></div>' +
                        '</div>',
                    content: function(){
                        return ufilterData.getPopoverContent(filter)
                    },
                    title:  $(elm).find('.filter-name').text() + '<span class="close">&times;</span>',
                    html: true
                });
                ufilterData.popovers.push(filter);
            }
        }
    };

    window.widget_func = {
            ufilterData
    };


    $('.ed-filter').click(function () {
        var elm = $(this);
        var filter = elm.data('filter');
        ufilterData.initPopover(elm, filter);
        if(ufilterData.popovers_open != null){
            $(ufilterData.popovers_open).popover('hide');
            if(ufilterData.popovers_open == elm){
                ufilterData.popovers_open = null;
                return;
            }
        }
        ufilterData.popovers_open = elm;
        $(elm).popover('show');
    });
    $(document).on('click', '.popover-header .close', function(){
        $(ufilterData.popovers_open).popover('hide');
        ufilterData.popovers_open = null;
    });
    $(document).on('click', 'a.f-success', function(){
        //Der Filter soll angewendet werden
        var filter = ufilterData.popovers_open.data('filter');
        if(filter =='search'){
            $('.f-form-q').val($('.popover-content .f-search-v').val());
        }else {
            $('.f-form-field').val(ufilterData.addFilterToString(
                $('.f-form-field').val(),
                filter
            ));
            if(filter =='category'){
                //Form URL anpassen
                let url_action = $(".f-category-v-baseurl").data('baseurl') + '/'+ $('input[type="radio"].f-category-v:checked').data('url');
                console.info(url_action);
                $("#ed_filter_form").attr('action', url_action);
            }
        }
        //Formular absenden
        $("#ed_filter_form").submit();
    });
    $(document).on('click', 'a.f-destroy', function(){
        //Der Filter soll angewendet werden
        var filter = ufilterData.popovers_open.data('filter');
        if(filter =='search'){
            $('.f-form-q').val('');
            //Formular absenden
            $("#ed_filter_form").submit();
        }else if(filter =='category'){
        }else {
            if (ufilterData.filterExists($('.f-form-field').val(), filter) === false) {
                $(ufilterData.popovers_open).popover('hide');
                ufilterData.popovers_open = null;
            } else {
                $('.f-form-field').val(//encodeURIComponent(
                    ufilterData.removeFilterFromString(
                        $('.f-form-field').val(),
                        filter
                    )
                );
                if(filter =='tag'){
                    $('.f-form-tag').val('');
                }
                //Formular absenden
                $("#ed_filter_form").submit();
            }
        }
    });
}