function formatNumberInElement(selector) {
    const formatter = new Intl.NumberFormat('en-GB');

    document.querySelectorAll(selector).forEach((el) => {
        const rawText = el.textContent.trim();

        const number = Number(rawText.replace(/[^\d]/g, ''));

        if (!Number.isNaN(number)) {
            el.textContent = formatter.format(number);
        }
    });
}

(function () {
    const SELECTORS = {
        $sidebar: $('.filter-results_desktop'),
        $heading: $('.filter-results__heading'),
        $offerBanner: $('.offer-banner'),
        $offerBannerIndent: 40,
        offerBannerCloseIcon:
            '.icon.notification__close, .icon.notification__close_white, .notification__close',
    };

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

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

    function applyTop() {
        if (!SELECTORS.$sidebar.length) return;

        if (!isDesktop()) {
            SELECTORS.$sidebar.css('top', '');
            SELECTORS.$heading.css('top', '');
            return;
        }

        const top = getOfferBannerHeight();

        SELECTORS.$sidebar.css('top', top + 'px');

        if (SELECTORS.$heading.length) {
            SELECTORS.$heading.css('top', top + 'px');
        }
    }

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

    $(document).ready(function () {
        formatNumberInElement('.product-count');
        applyTop();
        $(window).on('resize', _.debounce(applyTop, 100));
        setupOfferBannerCloseHook();
    });
})();
