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

Wick.StoreCardsAlign = (function () {
    const SELECTORS = {
        card: '.card-store',
        info: '.card-store__info',
        accordionHeader: '.opening-times-accordion__header',
    };

    let resizeTimeout;

    function alignCardInfoHeights() {
        const rows = [];

        $(SELECTORS.card).each(function () {
            const $card = $(this);
            const top = $card.offset().top;

            let row = rows.find((r) => Math.abs(r.top - top) < 5);

            if (!row) {
                row = { top: top, items: [] };
                rows.push(row);
            }

            row.items.push($card);
        });

        rows.forEach((row) => {
            let maxHeight = 0;

            // reset
            row.items.forEach(($card) => {
                $card.find(SELECTORS.info).css('min-height', '');
            });

            // find max
            row.items.forEach(($card) => {
                const h = $card.find(SELECTORS.info).outerHeight();
                if (h > maxHeight) maxHeight = h;
            });

            // apply
            row.items.forEach(($card) => {
                $card.find(SELECTORS.info).css('min-height', maxHeight + 'px');
            });
        });
    }

    function bindEvents() {
        // load
        $(window).on('load', alignCardInfoHeights);

        // resize
        $(window).on('resize', () => {
            clearTimeout(resizeTimeout);
            resizeTimeout = setTimeout(alignCardInfoHeights, 100);
        });

        // accordion
        $(document).on('click', SELECTORS.accordionHeader, () => {
            setTimeout(alignCardInfoHeights, 0);
        });
    }

    function init() {
        bindEvents();
    }

    init();

    return {
        init: init,
        align: alignCardInfoHeights,
    };
})();
