var Wick = window.Wick || {};

Wick.PLPFilters = {
    ROOT_WRAPPER:
        '.page-KitchenPLPPage, .products-list-page:not(.page-responsiveThematicProductListPage)',
    ROOT: '.plp-filters',
    GROUP: '.plp-filters__group',
    APPLY_BTN: '.plp-filters__apply',
    draftState: null,

    INPUTS: '.filter-card__checkbox, .swatch__checkbox, .checkbox__input',

    appliedState: {},

    init() {
        // 1) initialize submodules
        Wick.PLPFiltersPanel.init();
        Wick.PLPFiltersMobile.init();

        // 2) initial state with URL
        const root = $(Wick.PLPFilters.ROOT);
        const rootWrapper = $(Wick.PLPFilters.ROOT_WRAPPER);
        if (!root.length) {
            return;
        }

        Wick.PLPFilters.appliedState = Wick.PLPFilters.readStateFromURL(rootWrapper);
        Wick.PLPFilters.draftState = Wick.PLPUtils.cloneState(Wick.PLPFilters.appliedState);
        Wick.PLPFilters.setDOMFromState(rootWrapper, Wick.PLPFilters.appliedState);

        // 3) chips
        Wick.PLPChips.bindChipActions(rootWrapper);

        // 4) apply (desktop "View results")
        $(document).on('click', Wick.PLPFilters.APPLY_BTN, Wick.PLPFilters.applyFilters);

        // 5) primary render
        Wick.PLPFilters.updateSelectedUI(rootWrapper);

        // 6) handle browser back/forward navigation
        Wick.PLPFilters.handlePageShow();
    },

    // Handle bfcache (back/forward cache)
    handlePageShow() {
        window.addEventListener('pageshow', function () {
            const rootWrapper = $(Wick.PLPFilters.ROOT_WRAPPER);
            const stateScope = rootWrapper.add($(Wick.PLPFiltersMobile.MODAL_SEL));

            Wick.PLPFilters.appliedState = Wick.PLPFilters.readStateFromURL(stateScope);
            Wick.PLPFilters.draftState = Wick.PLPFilters.appliedState;
            Wick.PLPFilters.setDOMFromState(stateScope, Wick.PLPFilters.appliedState);
        });
    },

    // ===== URL <-> STATE
    readStateFromURL(rootWrapper) {
        const url = new URL(window.location.href);
        const params = url.searchParams;
        const state = {};

        const groupsMeta = Wick.PLPUtils.getGroupsMeta(rootWrapper, Wick.PLPFilters.GROUP);
        if (!groupsMeta.length) {
            return state;
        }

        const byDomName = {};
        groupsMeta.forEach((m) => {
            byDomName[m.domName] = m;
        });

        for (const [key, val] of params.entries()) {
            const meta = byDomName[key];
            if (!meta) {
                continue;
            }

            const values = val
                .split(',')
                .map((v) => v.trim())
                .filter(Boolean);
            if (!values.length) {
                continue;
            }

            values.forEach((want) => {
                const inp = meta.group
                    .find(Wick.PLPFilters.INPUTS)
                    .filter(function () {
                        return $(this).val() === want;
                    })
                    .first();

                if (!inp.length) {
                    return;
                }

                const originalValue = inp.val();
                if (!state[meta.domName]) {
                    state[meta.domName] = new Set();
                }
                state[meta.domName].add(originalValue);
            });
        }

        return state;
    },

    writeStateToURL(state) {
        const url = new URL(window.location.href);

        const groupsMeta = Wick.PLPUtils.getGroupsMeta(
            $(Wick.PLPFilters.ROOT_WRAPPER),
            Wick.PLPFilters.GROUP
        );
        const groupKeysDecoded = new Set(groupsMeta.map((m) => m.domName));

        const pairs = [];
        for (const [k, v] of url.searchParams.entries()) {
            if (!groupKeysDecoded.has(k)) {
                pairs.push(`${encodeURIComponent(k)}=${encodeURIComponent(v)}`);
            }
        }

        groupsMeta.forEach((meta) => {
            const set = state[meta.domName];
            if (!set || !set.size) return;

            const keyEnc = encodeURIComponent(meta.domName);
            const valueEnc = Array.from(set)
                .map((v) => encodeURIComponent(v))
                .join(',');
            pairs.push(`${keyEnc}=${valueEnc}`);
        });

        url.search = pairs.join('&');

        window.location.href = url.origin + url.pathname + url.search;
    },

    // set checkboxes according to state (both for desktop and modal)
    setDOMFromState(rootWrapper, state) {
        rootWrapper.find(Wick.PLPFilters.INPUTS).prop('checked', false);

        Object.keys(state).forEach((groupDomName) => {
            state[groupDomName].forEach((originalValue) => {
                const want = originalValue;

                const cand = rootWrapper
                    .find(Wick.PLPFilters.INPUTS)
                    .filter(function () {
                        const i = $(this);
                        const valMatch = i.val() === want;
                        const g = i.closest(Wick.PLPFilters.GROUP);
                        const groupMatch = g.length ? g.attr('data-filter') === groupDomName : true;
                        return valMatch && groupMatch;
                    })
                    .first();

                if (cand.length) {
                    cand.prop('checked', true);
                }
            });
        });
    },

    collectStateFromDOM(rootWrapper) {
        const state = {};
        rootWrapper
            .find(Wick.PLPFilters.INPUTS)
            .filter(':checked')
            .each((_, el) => {
                const input = $(el);
                const group = input.closest(Wick.PLPFilters.GROUP);
                const groupDomName = group.attr('data-filter') || '';
                if (!groupDomName) {
                    return;
                }

                const val = (input.val() || '').trim();
                if (!val) {
                    return;
                }

                if (!state[groupDomName]) {
                    state[groupDomName] = new Set();
                }
                state[groupDomName].add(val);
            });
        return state;
    },

    // ===== APPLY
    applyFromScopes(scopeForCollect, push) {
        const nextState = Wick.PLPFilters.collectStateFromDOM(scopeForCollect);

        Wick.PLPFilters.draftState = nextState;
        Wick.PLPFilters.appliedState = nextState;
        Wick.PLPFilters.writeStateToURL(Wick.PLPFilters.appliedState, !!push);
    },

    applyFilters(e) {
        e.preventDefault();
        const scope = $(Wick.PLPFilters.ROOT_WRAPPER).add($(Wick.PLPFiltersMobile.MODAL_SEL));
        Wick.PLPFilters.applyFromScopes(scope, true);
    },

    // ===== RENDER
    updateSelectedUI(rootWrapper) {
        Wick.PLPChips.renderGroupCounters(rootWrapper);
        Wick.PLPChips.renderChips(rootWrapper);
        Wick.PLPFiltersMobile.updateMobileFilterInfo();
    },

    totalApplied() {
        return Object.values(Wick.PLPFilters.appliedState).reduce((n, set) => n + set.size, 0);
    },

    // Wick.PLPUtils for appliedState
    removeFromApplied(groupDomName, valOriginal) {
        const st = Wick.PLPFilters.appliedState[groupDomName];
        if (!st) {
            return;
        }
        st.delete(valOriginal);
        if (st.size === 0) {
            delete Wick.PLPFilters.appliedState[groupDomName];
        }
    },

    exportState() {
        const out = {};
        Object.keys(Wick.PLPFilters.appliedState).forEach((g) => {
            out[g] = Array.from(Wick.PLPFilters.appliedState[g]);
        });
        return out;
    },
};

Wick.Overlay = (function () {
    const BODY_CLASS = 'page-responsiveThematicProductListPage';

    if (!$('body').hasClass(BODY_CLASS)) {
        return;
    }

    const $filterMobile = $('.filter-results_mobile');

    $(document).on('click', '#open-overlay', function (event) {
        event.preventDefault();

        $('body').addClass('is-filters-visible');
        $filterMobile.addClass('show');
    });

    $(document).on('click', '#close-overlay, .filter-results__btn-close', function (event) {
        event.preventDefault();

        if ($filterMobile.hasClass('show')) {
            $('body').removeClass('is-filters-visible');
            $filterMobile.removeClass('show');
        }
    });

    $(document).on(
        'click',
        '.filter-results_desktop .filter__item input[type="checkbox"]',
        function () {
            $(this).closest('form').submit();
        }
    );
})();

$(function () {
    Wick.PLPFilters.init();
});
