<?php

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

use Prodigy\Includes\Helpers\Prodigy_Formatting;

?>

<template id="gallery-slide">
	<?php echo wp_kses( prodigy_get_remote_gallery_thumb_html( array(), 0 ), Prodigy_Formatting::get_allowed_html() ); ?>
</template>


<div id="gallery"
		class="<?php echo esc_attr( $gallery_classname ); ?> prodigy-custom-template prodigy-product__gallery-main-image-container">
	<?php if ( ! empty( $price['sale-price'] ) && isset( $sale_badge ) && $sale_badge ) : ?>
			<div class="prodigy-product-list__item-label">
				<span class="prodigy-product-list__item-label-text"><?php esc_html_e( 'Sale', 'prodigy-commerce' ); ?></span>
			</div>
	<?php endif; ?>

	<div
		id="gallery-main"
		class="prodigy-product__gallery swiper"
		data-images='<?php echo wp_json_encode( $attachments ); ?>'
		data-ratio="<?php echo esc_attr( $ratio ); ?>"
	>
		<?php if ( isset( $post_thumbnail_id ) && $post_thumbnail_id ) : ?>
				<div class="swiper-wrapper">
			<?php
			if ( $attachments ) {
				foreach ( $attachments as $image_id => $attachment ) {
					echo wp_kses( prodigy_get_remote_gallery_thumb_html( $attachment, $image_id ), Prodigy_Formatting::get_allowed_html() );
				}
			}
			?>
				</div>
			<?php if ( ! empty( $attachments ) ) : ?>
					<button
						class="prodigy-product__gallery-nav prodigy-product__gallery-nav-prev icon icon-arrow-left"
						aria-label="<?php esc_html_e( 'Previous slide', 'prodigy-commerce' ); ?>"
						style="display: none;"
						type="button"
						aria-controls="gallery-count-block"
					></button>
					<button
						class="prodigy-product__gallery-nav prodigy-product__gallery-nav-next icon icon-arrow-right"
						aria-label="<?php esc_attr_e( 'Next slide', 'prodigy-commerce' ); ?>"
						style="display: none;"
						type="button"
						aria-controls="gallery-count-block"
					></button>
					<button
						class="prodigy-product__gallery-icon prodigy-product__gallery-icon--fullscreen icon icon-fullscreen icon-fullscreen-js"
						aria-label="<?php esc_attr_e( 'Toggle Fullscreen mode', 'prodigy-commerce' ); ?>"
						type="button"
					></button>
					<div class="prodigy-product__gallery-count"
							aria-atomic="true"
							aria-live="polite"
							id="gallery-count-block"
							aria-label="<?php esc_attr_e( 'Current slide out of total slides', 'prodigy-commerce' ); ?>"></div>
			<?php endif; ?>
		<?php else : ?>
				<i class="icon icon-image" role="presentation"
					aria-label="<?php esc_attr_e( 'Empty image icon', 'prodigy-commerce' ); ?>"></i>
		<?php endif; ?>
	</div>

	<?php if ( isset( $post_thumbnail_id ) && $post_thumbnail_id && $show_thumbnails ) : ?>
		<?php if ( isset( $settings ) ) : ?>
			<?php
			do_action(
				'prodigy_product_thumbnails',
				array(
					'images'   => $attachments,
					'settings' => $settings,
				)
			);
			?>
		<?php else : ?>
			<?php do_action( 'prodigy_product_thumbnails', array( 'images' => $attachments ) ); ?>
		<?php endif; ?>
	<?php endif; ?>
</div>
<script>
	jQuery(document).ready(function ($) {
		let thumbsDirection = 'horizontal';
		let thumbsSlidesPerView = $('#gallery-thumbs').length ? ($('#gallery-thumbs').data('slides') || 3) : 3;
		let thumbsSpaceBetween = $('#gallery-thumbs').length ? ($('#gallery-thumbs').data('spacing') || 10) : 10;

		if ($('#gallery').hasClass('prodigy-product__gallery-container--left') || $('#gallery').hasClass('prodigy-product__gallery-container--right')) {
			const ratio = $('#gallery-main').data('ratio');
			const width = $('#gallery-main').width();
			const height = width / ratio;
			$('#gallery').height(height);
			thumbsDirection = 'vertical';
			thumbsSlidesPerView = 'auto';
		}

		let allowThumbsScroll = false;

		const initNav = (swiper, el) => {
			el.on(
				'click',
				'.prodigy-product__gallery-nav-prev',
				function () {
					if (swiper === swiperThumbs) {
						allowThumbsScroll = true;
					}
					if (swiper.isBeginning) {
						swiper.slideTo(swiper.slides.length - 1);
					} else {
						swiper.slidePrev();
					}
				},
			);
			el.on(
				'click',
				'.prodigy-product__gallery-nav-next',
				function () {
					if (swiper === swiperThumbs) {
						allowThumbsScroll = true;
					}
					if (swiper.isEnd) {
						swiper.slideTo(0);
					} else {
						swiper.slideNext();
					}
				},
			);
		};

		let swiperThumbs = null;
		if ($('#gallery-thumbs').length) {
			const thumbSlides = $('#gallery-thumbs .swiper-slide');
			let validSlidesCount = 0;

			thumbSlides.each(function () {
				const $slide = $(this);
				const imgUrl = $slide.find('image[href]').attr('href') || '';
				const imgSrc = $slide.find('img[src]').attr('src') || '';
				if ((imgUrl && imgUrl.trim() !== '') || (imgSrc && imgSrc.trim() !== '')) {
					validSlidesCount++;
				}
			});

			if (validSlidesCount <= 1) {
				$('#gallery-thumbs').addClass('prodigy-gallery-thumbs-empty').hide();
			} else {
				swiperThumbs = new Swiper(
					'#gallery-thumbs',
					{
						direction: thumbsDirection,
						slidesPerView: thumbsSlidesPerView,
						spaceBetween: thumbsSpaceBetween,
						speed: 500,
						slideToClickedSlide: false,
						watchSlidesProgress: true,
						watchSlidesVisibility: true,
						preventClicks: false,
						preventClicksPropagation: false,
						on: {
							init: function (swiper) {
								let actualValidSlides = 0;
								$('#gallery-thumbs .swiper-slide').each(function () {
									const $slide = $(this);
									const imgUrl = $slide.find('image[href]').attr('href') || '';
									const imgSrc = $slide.find('img[src]').attr('src') || '';
									if ((imgUrl && imgUrl.trim() !== '') || (imgSrc && imgSrc.trim() !== '')) {
										actualValidSlides++;
									}
								});

								if (actualValidSlides <= 1) {
									$('#gallery-thumbs').addClass('prodigy-gallery-thumbs-empty').hide();
									return;
								}

								if (thumbsDirection === 'horizontal') {
									const slides = $('#gallery-thumbs .swiper-slide');
									if (slides.length > thumbsSlidesPerView) {
										$('#gallery-thumbs .prodigy-product__gallery-nav').show();
										initNav(swiper, $('#gallery-thumbs'));
									}
								} else if (thumbsDirection === 'vertical') {
									let slidesHeight = 0;
									let mainHeight = $('#gallery-main').outerHeight();
									swiper.slides.forEach(
										slide => {
											slidesHeight += $(slide).outerHeight();
										},
									);
									if (slidesHeight > mainHeight) {
										$('#gallery-thumbs .prodigy-product__gallery-nav').show();
										initNav(swiper, $('#gallery-thumbs'));
									}
								}
							},
						},
					},
				);

				const originalUpdate = swiperThumbs.update;
				swiperThumbs.update = function () {
					return originalUpdate.apply(this, arguments);
				};
			}
		}

		let swiperMain = null;
		if (swiperThumbs) {
			const thumbsRef = swiperThumbs;

			swiperMain = new Swiper(
				'#gallery-main',
				{
					speed: 500,
					pagination: {
						el: '.prodigy-product__gallery-count',
						type: 'fraction',
					},
					thumbs: {
						swiper: swiperThumbs,
						slideThumbActiveClass: 'swiper-slide-thumb-active',
						thumbsContainerClass: 'swiper-container-thumbs',
						autoScrollOffset: 0,
					},
					on: {
						init: function (swiper) {
							const slides = $('#gallery-main .swiper-slide');
							if (slides.length > 1) {
								$('#gallery-main .prodigy-product__gallery-nav').show();
								initNav(swiper, $('#gallery-main'));
							}
						},
						slideChange: function (swiper) {
							// Update active class without auto-scrolling thumbnails
							if (thumbsRef && !thumbsRef.destroyed) {
								const activeIndex = swiper.activeIndex;
								thumbsRef.slides.forEach((slide, index) => {
									if (index === activeIndex) {
										slide.classList.add('swiper-slide-thumb-active');
									} else {
										slide.classList.remove('swiper-slide-thumb-active');
									}
								});
							}
						},
					},
				},
			);

			const originalThumbsSlideTo = thumbsRef.slideTo.bind(thumbsRef);

			thumbsRef.slideTo = function (index, speed, runCallbacks, internal) {
				if (internal === 'controller' || (internal && typeof internal === 'object' && internal.controller)) {
					return false;
				}
				if (!allowThumbsScroll) {
					return false;
				}
				allowThumbsScroll = false; // Reset flag after use
				return originalThumbsSlideTo(index, speed, runCallbacks, internal);
			};

			const originalThumbsSlidePrev = thumbsRef.slidePrev.bind(thumbsRef);
			const originalThumbsSlideNext = thumbsRef.slideNext.bind(thumbsRef);

			thumbsRef.slidePrev = function (speed, runCallbacks) {
				allowThumbsScroll = true;
				const result = originalThumbsSlidePrev(speed, runCallbacks);
				allowThumbsScroll = false;
				return result;
			};

			thumbsRef.slideNext = function (speed, runCallbacks) {
				allowThumbsScroll = true;
				const result = originalThumbsSlideNext(speed, runCallbacks);
				allowThumbsScroll = false;
				return result;
			};

			$('#gallery-thumbs').on('click', '.swiper-slide', function (e) {
				e.stopPropagation();
				e.preventDefault();
				const slideIndex = $(this).index();
				if (swiperMain && !swiperMain.destroyed) {
					swiperMain.slideTo(slideIndex, 500);
				}
				return false;
			});
		} else {
			swiperMain = new Swiper(
				'#gallery-main',
				{
					speed: 500,
					pagination: {
						el: '.prodigy-product__gallery-count',
						type: 'fraction',
					},
					on: {
						init: function (swiper) {
							const slides = $('#gallery-main .swiper-slide');
							if (slides.length > 1) {
								$('#gallery-main .prodigy-product__gallery-nav').show();
								initNav(swiper, $('#gallery-main'));
							}
						},
					},
				},
			);
		}

		setTimeout(function () {
			if ($('#gallery-thumbs').length && !$('#gallery-thumbs').hasClass('prodigy-gallery-thumbs-empty')) {
				let validSlidesCount = 0;
				$('#gallery-thumbs .swiper-slide').each(function () {
					const $slide = $(this);
					const imgUrl = $slide.find('image[href]').attr('href') || '';
					const imgSrc = $slide.find('img[src]').attr('src') || '';
					if ((imgUrl && imgUrl.trim() !== '') || (imgSrc && imgSrc.trim() !== '')) {
						validSlidesCount++;
					}
				});

				if (validSlidesCount <= 1) {
					$('#gallery-thumbs').addClass('prodigy-gallery-thumbs-empty').hide();
				}
			}
		}, 500);
	});
</script>


