import { createShowMoreLess } from '../page/utils/show-more-less';

var Wick = window.Wick || (window.Wick = {});

function waitFor(getter, cb, opts) {
    opts = opts || {};
    var timeout = opts.timeout || 8000;
    var interval = opts.interval || 50;

    var start = Date.now();
    (function tick() {
        var val;
        try {
            val = getter();
        } catch (e) {
            val = null;
        }

        if (val) {
            cb(val);
            return;
        }

        if (Date.now() - start > timeout) {
            return;
        }

        setTimeout(tick, interval);
    })();
}

// show-more-less
(function () {
    const SEL = {
        OPEN: '#open-overlay',
        CLOSE: '#close-overlay, .filter-results__btn-close',
        FILTER_RESULT: '.filter-results_desktop',
        FILTER_MOBILE: '.filter-results_mobile',
        CATEGORY: '.filter__item--category',
    };

    const SRPShowMoreLess = createShowMoreLess({
        excludeGroup: ($group) => $group.hasClass(SEL.CATEGORY),
    });

    function initInScope() {
        const $fm = $(SEL.FILTER_MOBILE);
        SRPShowMoreLess.init($(SEL.FILTER_RESULT));
        SRPShowMoreLess.init($fm);
    }

    function resetInMobile() {
        const $fm = $(SEL.FILTER_MOBILE);
        SRPShowMoreLess.resetAll($fm);
    }

    $(function () {
        initInScope();
    });

    $(document)
        .off('click.srpSmlEmu', SEL.OPEN)
        .on('click.srpSmlEmu', SEL.OPEN, function (e) {
            e.preventDefault();
            initInScope();
            resetInMobile();
        });

    $(document)
        .off('click.srpSmlEmu', SEL.CLOSE)
        .on('click.srpSmlEmu', SEL.CLOSE, function (e) {
            e.preventDefault();
            resetInMobile();
        });
})();

(function () {
    waitFor(
        function () {
            return Wick.Sort;
        },
        function (Sort) {
            Sort.ROOT = '.products-list-page:not(.page-KitchenPLPPage)';
            Wick.Sort.ROOT = Sort.ROOT;

            var $root = $(Sort.ROOT);
            if (!$root.length) return;

            if (Sort.__emuBound) return;
            Sort.__emuBound = true;

            $root.off('click', Sort.TRIGGER_MOBILE);
            $root.off('click', Sort.TRIGGER_DESKTOP_BTN);
            $root.off('keydown', Sort.TRIGGER_MOBILE + ', ' + Sort.TRIGGER_DESKTOP_BTN);
            $root.off('click', Sort.OPTION);

            $root.on('click', Sort.TRIGGER_MOBILE, function (e) {
                e.stopPropagation();

                if ($(e.target).closest(Sort.DROPDOWN).length) return;
                e.preventDefault();
                Sort.toggle($(e.currentTarget));
            });

            $root.on('click', Sort.TRIGGER_DESKTOP_BTN, function (e) {
                e.stopPropagation();

                e.preventDefault();
                Sort.toggle($(e.currentTarget).closest(Sort.WRAP));
            });

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

            $root.on('click', Sort.OPTION, function (e) {
                e.preventDefault();
                e.stopPropagation();

                var opt = $(e.currentTarget);
                var value = opt.data('value');
                var label = Sort.valueToLabel(value);

                if (opt.data('is-plp-srp')) {
                    var wrap = opt.closest(Sort.WRAP);
                    wrap.find(Sort.OPTION).removeClass('is-active');
                    opt.addClass('is-active');

                    $(Sort.INFO).text(label);
                    Sort.closeAll();
                    return;
                }

                Sort.updateSortParamInURL(value);
            });

            (function bootstrapEmu() {
                var urlParams = new URLSearchParams(window.location.search);
                var value = urlParams.get('sortBy') || 'relevance';
                var label = Sort.valueToLabel(value);

                var $wraps = $root.find(Sort.WRAP);

                $wraps.each(function (_, el) {
                    var w = $(el);
                    w.find(Sort.OPTION)
                        .removeClass('is-active')
                        .filter('[data-value="' + value + '"]')
                        .addClass('is-active');
                });

                $(Sort.INFO).text(label);
            })();
        }
    );
})();
