document.addEventListener('DOMContentLoaded', function () {

    const blocks = [
        '#rec1610114641',
        '#rec1609973771',
        '#rec1610112571',
        '#rec1610115811',
        '#rec1610116831',
        '#rec1496761731'
    ];

    blocks.forEach(id => {
        const el = document.querySelector(id + ' .js-store-grid-cont');
        if (!el) return;

        let isDown = false;
        let startX;
        let scrollLeft;
        let velocity = 0;
        let momentumID;

        const momentum = () => {
            el.scrollLeft += velocity;
            velocity *= 0.95; // сила замедления инерции

            if (Math.abs(velocity) > 0.3) {
                momentumID = requestAnimationFrame(momentum);
            }
        };

        el.addEventListener('mousedown', (e) => {
            isDown = true;
            startX = e.pageX - el.offsetLeft;
            scrollLeft = el.scrollLeft;
            velocity = 0;
            cancelAnimationFrame(momentumID);
        });

        el.addEventListener('mouseleave', () => isDown = false);
        el.addEventListener('mouseup', () => {
            isDown = false;
            momentum();
        });

        el.addEventListener('mousemove', (e) => {
            if (!isDown) return;
            e.preventDefault();
            const x = e.pageX - el.offsetLeft;
            const walk = (x - startX);
            el.scrollLeft = scrollLeft - walk;
            velocity = -(walk * 0.5);
        });

        /* Touch for mobile */
        let lastTouchX = 0;
        let lastMoveTime = 0;

        el.addEventListener('touchstart', (e) => {
            cancelAnimationFrame(momentumID);
            lastTouchX = e.touches[0].pageX;
            lastMoveTime = Date.now();
            velocity = 0;
        });

        el.addEventListener('touchmove', (e) => {
            const currentX = e.touches[0].pageX;
            const delta = lastTouchX - currentX;
            const now = Date.now();

            el.scrollLeft += delta;

            velocity = delta / (now - lastMoveTime) * 20;

            lastTouchX = currentX;
            lastMoveTime = now;
        });

        el.addEventListener('touchend', () => {
            momentum();
        });
    });

});


