/**
 * Media Slider widget — Swiper initialization.
 *
 * @package ThemeREX\AutoDealer
 */
(function () {
	'use strict';

	/**
	 * Initialize a single media slider instance.
	 *
	 * @param {HTMLElement} el The .trx-ad-media-slider wrapper.
	 */
	function initSlider(el) {
		if (typeof Swiper === 'undefined' || el.dataset.trxAdInit) {
			return;
		}
		el.dataset.trxAdInit = '1';

		var thumbsPer = parseInt(el.dataset.thumbsPer, 10) || 5;
		var autoplay  = el.dataset.autoplay === '1';
		var loop      = el.dataset.loop === '1';

		// Thumbs Swiper.
		var thumbsEl     = el.querySelector('.trx-ad-ms-thumbs');
		var thumbsSwiper = null;
		var slideCount   = el.querySelectorAll('.trx-ad-ms-main .swiper-slide').length;

		if (thumbsEl) {
			thumbsSwiper = new Swiper(thumbsEl, {
				slidesPerView: thumbsPer,
				spaceBetween: 8,
				freeMode: true,
				watchSlidesProgress: true,
				slideToClickedSlide: true,
				breakpoints: {
					0:   { slidesPerView: Math.min(thumbsPer, 3) },
					600: { slidesPerView: Math.min(thumbsPer, 4) },
					900: { slidesPerView: thumbsPer }
				}
			});
		}

		// Main Swiper.
		// `rewind` gives the user-requested wraparound (next-on-last → first,
		// prev-on-first → last) without `loop`'s side effect of duplicating +
		// rotating slides — preserving the source order Featured → Gallery → Video.
		var mainOpts = {
			spaceBetween: 0,
			navigation: {
				nextEl: el.querySelector('.swiper-button-next'),
				prevEl: el.querySelector('.swiper-button-prev')
			},
			rewind: loop && slideCount > 1,
			on: {
				slideChange: function () {
					// Pause all videos when sliding away.
					el.querySelectorAll('video').forEach(function (v) { v.pause(); });
				}
			}
		};

		if (autoplay) {
			mainOpts.autoplay = { delay: 5000, disableOnInteraction: true };
		}

		if (thumbsSwiper) {
			mainOpts.thumbs = { swiper: thumbsSwiper };
		}

		new Swiper(el.querySelector('.trx-ad-ms-main'), mainOpts);

		// Lazy-load external video embeds on poster click.
		el.querySelectorAll('.trx-ad-ms-video-poster').forEach(function (poster) {
			poster.addEventListener('click', function () {
				var embedUrl = poster.getAttribute('data-embed');
				var separator = embedUrl.indexOf('?') !== -1 ? '&' : '?';
				var iframe = document.createElement('iframe');
				iframe.src = embedUrl + separator + 'autoplay=1';
				iframe.allowFullscreen = true;
				iframe.allow = 'autoplay; fullscreen';
				iframe.style.cssText = 'position:absolute;inset:0;width:100%;height:100%;border:0;';
				var slide    = poster.closest('.swiper-slide');
				var playIcon = slide.querySelector('.trx-ad-ms-play');
				if (playIcon) playIcon.remove();
				poster.replaceWith(iframe);
			});
		});
	}

	/**
	 * Initialize all media sliders on the page.
	 */
	function initAll() {
		document.querySelectorAll('.trx-ad-media-slider:not([data-trx-ad-init])').forEach(initSlider);
	}

	// DOM ready.
	if (document.readyState === 'loading') {
		document.addEventListener('DOMContentLoaded', initAll);
	} else {
		initAll();
	}

	// Elementor editor support.
	if (typeof jQuery !== 'undefined') {
		jQuery(window).on('elementor/frontend/init', function () {
			if (typeof elementorFrontend !== 'undefined') {
				elementorFrontend.hooks.addAction(
					'frontend/element_ready/trx_ad_media_slider.default',
					function ($scope) {
						var el = $scope[0].querySelector('.trx-ad-media-slider');
						if (el) {
							delete el.dataset.trxAdInit;
							initSlider(el);
						}
					}
				);
			}
		});
	}
})();
