(function () {
    const SELECTORS = {
        $filters: $('.plp-filters'),
        $filterBar: $('.plp-filters__bar-mobile'),
        $filterModal: $('.filter-modal'),

        $offerBanner: $('.offer-banner'),
        offerBannerCloseIcon: '.icon.notification__close',
    };

    const CLASSES = {
        plpFiltersStuck: 'plp-filters__bar-stuck',
    };

    function isMobile() {
        return Wick.Responsive.getCurrentBreakpoint() === 'down-sm';
    }

    function getOfferBannerHeight() {
        if (!SELECTORS.$offerBanner.length) return 0;
        return SELECTORS.$offerBanner.outerHeight(true) || 0;
    }

    function applyOfferBannerTop() {
        if (!SELECTORS.$filters.length) return;

        if (!isMobile()) {
            SELECTORS.$filters.css('top', '');
            return;
        }

        const h = getOfferBannerHeight();
        SELECTORS.$filters.css('top', h > 0 ? h + 'px' : '');
    }

    function resetOfferBannerTopToZero() {
        if (!SELECTORS.$filters.length) return;
        SELECTORS.$filters.css('top', '0px');
    }

    function applyStuckState() {
        if (!isMobile()) {
            SELECTORS.$filterBar.removeClass(CLASSES.plpFiltersStuck);
            return;
        }

        if (!SELECTORS.$filters.length || !SELECTORS.$filterBar.length) return;

        const filtersEl = SELECTORS.$filters.get(0);
        if (!filtersEl) return;

        const rect = filtersEl.getBoundingClientRect();
        const bannerHeight = getOfferBannerHeight();

        const shouldStick = rect.top <= bannerHeight;

        if (shouldStick) {
            SELECTORS.$filterBar.addClass(CLASSES.plpFiltersStuck);
        } else {
            SELECTORS.$filterBar.removeClass(CLASSES.plpFiltersStuck);
        }
    }

    function hideModal() {
        if (Wick.Responsive.getCurrentBreakpoint() !== 'down-sm') {
            SELECTORS.$filterModal.modal('hide');
        }
    }

    function setupOfferBannerCloseHook() {
        $(document).on('click', SELECTORS.offerBannerCloseIcon, function () {
            resetOfferBannerTopToZero();
        });
    }

    $(document).ready(function () {
        applyOfferBannerTop();
        applyStuckState();

        $(window).on('scroll', _.debounce(applyStuckState, 50));

        $(window).on(
            'resize',
            _.debounce(function () {
                hideModal();
                applyOfferBannerTop();
                applyStuckState();
            }, 100)
        );

        setupOfferBannerCloseHook();
    });
})();
