/**
 * 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
 */

// Import Motion au début du fichier
import { animate } from "https://cdn.jsdelivr.net/npm/motion@11.18.2/+esm";


const TestimonialsSlider = {
	// Configuration principale
	CONFIG: {
		CLONE_MULTIPLIER: 10,
		SPEED: 1, // Vitesse de défilement : 1 = normal, 0.5 = plus lent, 2 = plus rapide
	},

	selectors: {
		container: '.wp-block-orphic-ui-testimonials-container',
		list: '.testimonials-container',
		slide: '.testimonial-unit-slide'
	},

	timeline: null,
	animation: null,

	init: function() {
		
		// Vérifions si le DOM est déjà chargé
		if (document.readyState === 'loading') {
			document.addEventListener('DOMContentLoaded', () => this.initializeSliders());
		} else {
			this.initializeSliders();
		}
	},

	initializeSliders: function() {
		
		const sliders = document.querySelectorAll(this.selectors.container);

		if (!sliders.length) {
			console.warn('No sliders found with selector:', this.selectors.container);
			// Vérifions si l'élément existe avec une autre méthode
			const allElements = document.getElementsByTagName('*');
			const possibleSliders = Array.from(allElements).filter(el => 
				el.className && el.className.includes('testimonials')
			);
		}

		sliders.forEach((slider, index) => {
			this.setupSlider(slider);
		});
	},

	setupSlider: function(slider) {
		
		const container = slider.querySelector(this.selectors.list);
		
		const slides = slider.querySelectorAll(this.selectors.slide);

		if (!container) {
			console.error('Container element not found with selector:', this.selectors.list);
			return;
		}
		
		if (!slides.length) {
			console.warn('No slides found in container with selector:', this.selectors.slide);
			return;
		}

		const direction = container.dataset.direction;
		
		try {
			this.cloneSlides(container, slides);
			
			this.initializeAnimation(container, slides, direction);
			
			this.setupEventListeners(slider);
		} catch (error) {
			console.error('Error during slider setup:', error);
		}
	},

	cloneSlides: function(container, slides) {
		for (let i = 0; i < this.CONFIG.CLONE_MULTIPLIER; i++) {
			slides.forEach(slide => {
				const clone = slide.cloneNode(true);
				container.appendChild(clone);
			});
		}
	},

	initializeAnimation: function(container, slides, direction) {
		const slideWidth = slides[0].offsetWidth;
		
		if (direction === 'left') {
      const totalWidth = slideWidth * slides.length * this.CONFIG.CLONE_MULTIPLIER;
			container.style.transform = 'translateX(0)';
			this.createTimeline(container, totalWidth, slides.length, 'left');
		} else {
      const totalWidth = slideWidth * slides.length * (this.CONFIG.CLONE_MULTIPLIER - 4);
			container.style.transform = `translateX(-${totalWidth}px)`;
			this.createTimeline(container, totalWidth, slides.length, 'right');
		}
	},

	createTimeline: function(container, totalWidth, slidesCount, direction) {
		const duration = (totalWidth / 100) * (5 / this.CONFIG.SPEED);

		if (this.animation) {
			this.animation.stop();
		}

		const startX = direction === 'left' ? 0 : -totalWidth;
		const endX = direction === 'left' ? -totalWidth : 0;

		// Créer une animation infinie
		const animate_loop = () => {
			try {
				this.animation = animate(container, {
					transform: `translateX(${endX}px)`
				}, {
					duration: duration,
					easing: 'linear',
					repeat: Infinity
				});
			} catch (error) {
				console.error('Failed to start animation:', error);
			}
		};

		animate_loop();
	},

	setupEventListeners: function(slider) {
		slider.addEventListener('mouseenter', () => {
			if (this.animation) this.animation.pause();
		});
		
		slider.addEventListener('mouseleave', () => {
			if (this.animation) this.animation.play();
		});
	},
};

// Initialize the module
try {
	TestimonialsSlider.init();
} catch (error) {
	console.error('Error during initialization:', error);
}
