var Wick = window.Wick || {};

Wick.PLPUtils = (function () {
    function cloneState(state) {
        const out = {};
        Object.keys(state).forEach((k) => {
            out[k] = new Set(state[k]);
        });
        return out;
    }

    function syncTwinInputsByName(name, checked, source) {
        const all = $('.filter-card__checkbox, .swatch__checkbox, .checkbox__input').filter(
            function () {
                return $(this).attr('name') === name;
            }
        );
        all.each(function () {
            if (source && this === source[0]) {
                return;
            }
            $(this).prop('checked', checked);
        });
    }

    function getPanelType(panel) {
        if (panel.find('.plp-filters__options--cards').length) {
            return 'cards';
        }
        if (panel.find('.swatch-list').length) {
            return 'swatches';
        }
        return 'text';
    }

    function countItems(panel) {
        const t = getPanelType(panel);
        if (t === 'cards') {
            return panel.find('.filter-card').length || 0;
        }
        if (t === 'swatches') {
            return panel.find('.swatch').length || 0;
        }
        return panel.find('.checkbox').length || 0;
    }

    function setCardsColumns(panel, cols) {
        const wrap = panel.find('.plp-filters__options--cards');
        if (wrap.length) {
            wrap.css('grid-template-columns', `repeat(${cols}, minmax(0,1fr))`);
        }
    }

    function getGroupsMeta(rootWrapper, selGroup) {
        const out = [];
        rootWrapper.find(selGroup).each((_, el) => {
            const group = $(el);
            const domName = group.attr('data-filter') || '';
            if (!domName) {
                return;
            }
            out.push({ domName, paramKey: domName, group });
        });
        return out;
    }

    return {
        cloneState,
        syncTwinInputsByName,
        getPanelType,
        countItems,
        setCardsColumns,
        getGroupsMeta,
    };
})();
