(function ($, document, window, viewport) {
    'use strict';

    // PLUGIN CLASS
    // ============
    const MORE_FILTERS_ELEMENT_SELECTOR = 'body[data-page="2"] .et-product-list-filter-top, body[data-page="24"] .et-product-list-filter-top';

    const MoreFiltersPlugin = {

        currentViewport: null,
        isExpanded: false,
        $filterItems: null,
        $moreFiltersTrigger: null,
        limits: null,

        /**
         * @this {PluginBase & MoreFiltersPlugin}
         * @param {HTMLElement} element
         * @param {Object} options
         */
        init: function (element, options) {
            this.$filterItems = this.$el.find('.et-product-list-filter-item').not('.et-product-list-filter-item-mobile'); // Ignore filter items that appear in mobile dialogs;
            if(this.$el.hasClass('et-filters-active')) {
                // We are actively filtering, do not hide filters
                return;
            }

            this.limits = this.$el.data('more-filters-limit');
            if(!this.limits) {
                // Limit data is missing, abort
                return;
            }
            if(!this.$filterItems.length) {
                // No filter items available anyway
                return;
            }
            this.$moreFiltersTrigger = this.$el.find('.et-more-filters-trigger');
            if(!this.$moreFiltersTrigger.length) {
                // No "more filters trigger found", abort
                return;
            }

            this.currentViewport = this.getCurrentViewport();
            this.registerEvents();
            this.hideFilters();

            $(window).on('resize', () => {
                let viewportBefore = this.currentViewport;
                this.currentViewport = this.getCurrentViewport();
                if(viewportBefore !== this.currentViewport) {
                    if(!this.isExpanded) {
                        // Viewport changed
                        this.hideFilters();
                    }
                }
            });
            $(document).on('evo:loaded.evo.content', () => {
                // possibly page navigation
                this.$el = $(MORE_FILTERS_ELEMENT_SELECTOR);
                if(!this.$el.length) {
                    // No more filters element found, abort
                    return;
                }
                if(this.$el.hasClass('et-filters-active')) {
                    // We are actively filtering, do not hide filters
                    return;
                }
                // reassign current filter items and trigger, the old ones are gone now
                this.$filterItems = this.$el.find('.et-product-list-filter-item').not('.et-product-list-filter-item-mobile'); // Ignore filter items that appear in mobile dialogs
                if(!this.$filterItems.length) {
                    // No filter items available, abort
                    return;
                }
                this.$moreFiltersTrigger = this.$el.find('.et-more-filters-trigger');
                if(!this.$moreFiltersTrigger.length) {
                    // No "more filters trigger found", abort
                    return;
                }
                if(!this.isExpanded) {
                    this.hideFilters();
                }
                this.registerEvents();
            });
        },

        getCurrentViewport: function() {
            return viewport.current();
        },

        registerEvents: function() {
            this.$moreFiltersTrigger.off('.et-more-filters').on('click.et-more-filters', () => {
                this.showFilters();
                this.hideTrigger();
                this.isExpanded = true;
            });

            this.Events.publish('easytemplate/Plugin/etMoreFiltersPlugin/onRegisterEvents', [this]);
        },

        hideFilters: function() {
            let filtersToShowLimit = parseInt(this.limits[this.currentViewport]);
            if(isNaN(filtersToShowLimit)) {
                // Filter limit could not be parsed to a number
                return;
            }
            // No limit, show everything
            this.showFilters();
            if(filtersToShowLimit > 0) {
                // first reset all styles
                this.hideTrigger();
                this.showFilters();
                // limit all filter items after the limit, but only if we have 2 more filters than allowed. Otherwise the more button would just take the place of the last available filter, making the click useless / redundant
                if(this.$filterItems.length > filtersToShowLimit + 1) {
                    this.$filterItems.slice(filtersToShowLimit).css({display: 'none'});
                    this.showTrigger();
                }
            }

            this.Events.publish(
                'easytemplate/Plugin/etMoreFiltersPlugin/onHideFilters',
                [this, {filtersToShowLimit}]
            );
        },

        showFilters: function() {
            // We show filter items by unsetting inline displays
            this.$filterItems.css({display: ''});
            this.Events.publish('easytemplate/Plugin/etMoreFiltersPlugin/onShowFilters', [this]);
        },
        hideTrigger: function() {
            this.$moreFiltersTrigger.hide();
            this.Events.publish('easytemplate/Plugin/etMoreFiltersPlugin/onHideTrigger', [this]);
        },
        showTrigger: function() {
            this.$moreFiltersTrigger.show();
            this.Events.publish('easytemplate/Plugin/etMoreFiltersPlugin/onShowTrigger', [this]);
        }
    };

    // REGISTER AND ADD THE PLUGIN
    // ===========================
    if (!window.easytemplate && !window.easytemplate.PluginManager) {
        throw Error('Cannot initialize Easytemplate Plugin. plugin-manager.js has to be loaded first!');
    }

    /** @type {PluginManager} manager */
    const manager = window.easytemplate.PluginManager;
    manager.addPlugin(MORE_FILTERS_ELEMENT_SELECTOR, MoreFiltersPlugin, 'etMoreFiltersPlugin');
})(jQuery, document, window, ResponsiveBootstrapToolkit);