/**
 * Use this file for JavaScript code that you want to run in the front-end
 * on posts/pages that contain this block.
 *
 * When this file is defined as the value of the `viewScript` property
 * in `block.json` it will be enqueued on the front end of the site.
 *
 * Example:
 *
 * ```js
 * {
 *   "viewScript": "file:./view.js"
 * }
 * ```
 *
 * If you're not making any changes to this file because your project doesn't need any
 * JavaScript running in the front-end, then you should delete this file and remove
 * the `viewScript` property from `block.json`.
 *
 * @see https://developer.wordpress.org/block-editor/reference-guides/block-api/block-metadata/#view-script
 */

/* eslint-disable no-console */
console.log(
	'Hello World! (from block-and-function-orphic-block-and-function block)'
);
/* eslint-enable no-console */

document.addEventListener('DOMContentLoaded', function() {
    const sliders = document.querySelectorAll('.wp-block-orphic-ui-testimonials-container');
    
    sliders.forEach(slider => {
        const direction = slider.dataset.direction || 'left';
        const container = slider.querySelector('.testimonials-container');
        const slides = container.querySelectorAll('.testimonial-unit-slide');
        
        // Clone slides for infinite effect
        slides.forEach(slide => {
            const clone = slide.cloneNode(true);
            container.appendChild(clone);
        });

        let position = 0;
        let animation = null;
        const speed = 1; // pixels per frame
        const gap = 20; // gap between slides

        function animate() {
            const containerWidth = container.offsetWidth;
            const totalWidth = Array.from(slides).reduce((acc, slide) => {
                return acc + slide.offsetWidth + gap;
            }, 0);

            position += direction === 'left' ? -speed : speed;

            // Reset position for infinite loop
            if (direction === 'left' && Math.abs(position) >= totalWidth) {
                position = 0;
            } else if (direction === 'right' && position >= 0) {
                position = -totalWidth;
            }

            container.style.transform = `translateX(${position}px)`;
            animation = requestAnimationFrame(animate);
        }

        // Start animation
        animation = requestAnimationFrame(animate);

        // Pause on hover
        container.addEventListener('mouseenter', () => {
            cancelAnimationFrame(animation);
        });

        container.addEventListener('mouseleave', () => {
            animation = requestAnimationFrame(animate);
        });
    });
});
