var Wick = window.Wick || {};

Wick.Sort = {
    ROOT: '.page-KitchenPLPPage, .products-list-page:not(.page-responsiveThematicProductListPage)',
    WRAP: '.sort',
    DROPDOWN: '.sort-dd',
    OPTION: '.sort-opt',
    INFO: '.js-sort-info',
    CHEVRON: '.sort__chevron',

    TRIGGER_MOBILE: '.sort--mobile',
    TRIGGER_DESKTOP_BTN: '.sort--desktop .sort-button',

    MAP_VALUE_TO_LABEL: {
        relevance: 'Relevance',
        priceLow: 'Price (lowest first)',
        priceHigh: 'Price (highest first)',
    },

    init: function () {
        const root = $(Wick.Sort.ROOT);
        if (!root.length) {
            return;
        }

        root.on('click', Wick.Sort.TRIGGER_MOBILE, (e) => {
            if ($(e.target).closest(Wick.Sort.DROPDOWN).length) {
                return;
            }
            e.preventDefault();
            Wick.Sort.toggle($(e.currentTarget));
        });

        root.on('click', Wick.Sort.TRIGGER_DESKTOP_BTN, (e) => {
            e.preventDefault();
            Wick.Sort.toggle($(e.currentTarget).closest(Wick.Sort.WRAP));
        });

        root.on('keydown', `${Wick.Sort.TRIGGER_MOBILE}, ${Wick.Sort.TRIGGER_DESKTOP_BTN}`, (e) => {
            if (e.key === 'Enter' || e.key === ' ') {
                e.preventDefault();
                Wick.Sort.toggle($(e.currentTarget).closest(Wick.Sort.WRAP));
            }
        });

        root.on('click', Wick.Sort.OPTION, (e) => {
            e.preventDefault();
            e.stopPropagation();

            const opt = $(e.currentTarget);
            const value = opt.data('value');

            if (opt.data('is-plp-srp')) {
                return;
            }

            Wick.Sort.updateSortParamInURL(value);
        });

        $(document).on('click', (e) => {
            const open = $(`${Wick.Sort.WRAP}.is-open`);
            if (!open.length) {
                return;
            }
            if (!open.is(e.target) && open.has(e.target).length === 0) {
                Wick.Sort.closeAll();
            }
        });

        $(document).on('keydown', (e) => {
            if (e.key === 'Escape') {
                Wick.Sort.closeAll();
            }
        });

        Wick.Sort.bootstrap();
    },

    updateSortParamInURL: function (value) {
        const url = new URL(window.location.href);
        const params = url.searchParams;

        if (value === 'relevance') {
            params.delete('sortBy');
        } else {
            params.set('sortBy', value);
        }

        url.search = params.toString();

        window.location.href = url.toString();
    },

    toggle: function (wrap) {
        const isOpen = wrap.hasClass('is-open');
        Wick.Sort.closeAll();
        if (!isOpen) {
            wrap.addClass('is-open');
            wrap.find(Wick.Sort.DROPDOWN).removeAttr('hidden');
            Wick.Sort.setExpanded(wrap, true);

            if (window.Wick && Wick.PLPFilters && typeof Wick.PLPFilters.closeAll === 'function') {
                Wick.PLPFilters.closeAll();
            }
        }
    },

    close: function (wrap) {
        wrap.removeClass('is-open');
        wrap.find(Wick.Sort.DROPDOWN).attr('hidden', true);
        Wick.Sort.setExpanded(wrap, false);
    },

    closeAll: function () {
        const all = $(Wick.Sort.WRAP);
        all.removeClass('is-open');
        all.find(Wick.Sort.DROPDOWN).attr('hidden', true);
        all.each((_, el) => Wick.Sort.setExpanded($(el), false));
    },

    bootstrap: function () {
        const urlParams = new URLSearchParams(window.location.search);
        const value = urlParams.get('sortBy') || 'relevance';
        const label = Wick.Sort.valueToLabel(value);

        $(Wick.Sort.WRAP).each((_, el) => {
            const w = $(el);

            const isPlpSrp = w.find(Wick.Sort.OPTION).first().data('is-plp-srp');

            if (isPlpSrp) {
                return;
            }

            w.find(Wick.Sort.OPTION)
                .removeClass('is-active')
                .filter(`[data-value="${value}"]`)
                .addClass('is-active');
        });

        const hasPlpSrp = $(Wick.Sort.OPTION).first().data('is-plp-srp');

        if (!hasPlpSrp) {
            $(document).trigger('sort:change', { value, label });
            $(Wick.Sort.INFO).text(label);
        }
    },

    setExpanded: function (wrap, expanded) {
        const btn = wrap.is('.sort--mobile') ? wrap : wrap.find('.sort-button').first();
        if (btn.length) {
            btn.attr('aria-expanded', expanded ? 'true' : 'false');
        }
    },

    valueToLabel: function (value) {
        return Wick.Sort.MAP_VALUE_TO_LABEL[value] || 'Relevance';
    },
    labelToValue: function (label) {
        const entries = Object.entries(Wick.Sort.MAP_VALUE_TO_LABEL);
        for (const [val, lab] of entries) {
            if (lab.toLowerCase() === label.toString().toLowerCase()) {
                return val;
            }
        }
        return 'relevance';
    },
};

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