import { appendLoader, showLoader, hideLoader } from '../page/utils/loader';

function initStoreLocatorLoadMore() {
    const PAGE_SIZE = 8;

    const SELECTORS = {
        cards: '.cards-store-list',
        btnMore: '.store-locator__load-button_more',
        loader: '.store-locator-loader',
    };

    const loaderPayload = {
        wrapper: 'body',
        hidden: true,
        modifier: 'store-locator-loader',
    };

    const $cards = $(SELECTORS.cards);
    const $btnMore = $(SELECTORS.btnMore);

    let visibleCount = PAGE_SIZE;

    function updateVisibility() {
        $cards.each(function (index) {
            $(this).toggle(index < visibleCount);
        });

        if (visibleCount >= $cards.length) {
            $btnMore.hide();
        } else {
            $btnMore.show();
        }

        Wick.StoreCardsAlign?.align();
    }

    function loadMore() {
        showLoader(SELECTORS.loader);
        $btnMore.prop('disabled', true);

        setTimeout(() => {
            visibleCount += PAGE_SIZE;
            updateVisibility();

            hideLoader(SELECTORS.loader);
            $btnMore.prop('disabled', false).blur();
        }, 1000);
    }

    function init() {
        if (!$cards.length || !$btnMore.length) {
            return;
        }

        if (!$(SELECTORS.loader).length) {
            appendLoader(loaderPayload);
        }

        updateVisibility();

        $btnMore.on('click', loadMore);
    }

    init();
}

$(document).ready(function () {
    initStoreLocatorLoadMore();
});
