<script>
class CustomerReviews {
	constructor() {
		this.customerSmallReviewGrids = document.querySelectorAll(".customer_review_small--grid");
		this.customerReviewGrids = document.querySelectorAll(".customer_review--grids");
		this.init();
	}

	handleSlide(reviewId) {
		const gridToSlide = Array.from(this.customerReviewGrids).find(crg =>
			crg.parentElement.parentElement.dataset.postId === reviewId
		);

		if (!gridToSlide) return;

		const slider = gridToSlide.closest('.slick-track');
		const slideWidth = slider.querySelector('.slick-current')?.offsetWidth;
		
		if (!slideWidth) return;

		const currentPosition = getComputedStyle(slider).transform;
		const translatedValue = currentPosition.match(/matrix\((?:[^,]*,){4}\s*(-?\d+\.?\d*)/)?.[1] || 0;

		const targetIndex = gridToSlide.closest('.jet-listing-grid__item').dataset.slickIndex;
	
		const newPosition = targetIndex * slideWidth;
		slider.style.transition = 'transform 0.5s';
		slider.style.transform = `translate3d(${newPosition}px, 0, 0)`; 

		this.updateActiveClass(reviewId);
	}

	updateActiveClass(reviewId) {
		this.customerReviewGrids.forEach(crg => {
			const parentEl = crg.parentElement.parentElement;
			if (parentEl) {
				parentEl.classList.remove("slick-current", "slick-active");

				if (parentEl.dataset.postId === reviewId) {
					parentEl.classList.add("slick-current", "slick-active");
				}
			}
		});
	}

	init() {
		const gridWidth = this.customerSmallReviewGrids[0].offsetWidth;

		document.documentElement.style.setProperty('--customer-review-small-grid-width', `${gridWidth}px`);

		this.customerSmallReviewGrids.forEach(csrg => {
			const parentEl = csrg.parentElement.parentElement;
			parentEl.classList.remove("clicked-slide");

			csrg.addEventListener("click", () => {
				this.customerSmallReviewGrids.forEach(otherCsrg => {
					const otherParentEl = otherCsrg.parentElement.parentElement;
					if (otherCsrg !== csrg) {
						otherParentEl.classList.remove("clicked-slide");
					}
				});

				parentEl.classList.add("clicked-slide");

				const clickedReviewId = parentEl.dataset.postId;
				if (clickedReviewId) {
					this.handleSlide(clickedReviewId);
				}
			});
		});

		if (this.customerSmallReviewGrids.length > 0) {
			this.customerSmallReviewGrids[0].parentElement.parentElement.classList.add("clicked-slide");
		}
	}
}

document.addEventListener("DOMContentLoaded", () => {
setTimeout(() => {
  new CustomerReviews()
}, 200);
});


</script>
