/**
 * Card Carousel: Swiper + lightbox. Magnific Popup requires jQuery; all other logic is plain DOM.
 */
( function () {
	'use strict';

	var cardCarouselSwipers = [];
	var resizeScheduled = false;
	var resizeListenerBound = false;

	function scheduleAllSwipersResize() {
		if ( resizeScheduled ) {
			return;
		}
		resizeScheduled = true;
		requestAnimationFrame( function () {
			resizeScheduled = false;
			for ( var i = 0; i < cardCarouselSwipers.length; i++ ) {
				var s = cardCarouselSwipers[ i ];
				if ( s && typeof s.updateSize === 'function' ) {
					try {
						s.updateSize();
						s.update();
					} catch ( e ) {
						// Swiper may be destroyed.
					}
				}
			}
		} );
	}

	function bindGlobalResizeOnce() {
		if ( resizeListenerBound ) {
			return;
		}
		resizeListenerBound = true;
		window.addEventListener( 'resize', scheduleAllSwipersResize, {
			passive: true,
		} );
	}

	/**
	 * @param {Element} wrap Carousel root (.dsm_card_carousel_wrapper).
	 * @param {string}    selector Sibling selector (e.g. .swiper-button-prev).
	 * @return {Element|null}
	 */
	function getSibling( wrap, selector ) {
		var parent = wrap.parentElement;
		if ( ! parent ) {
			return null;
		}
		var found = parent.querySelectorAll( ':scope > ' + selector );
		return found.length ? found[ 0 ] : null;
	}

	/**
	 * Magnific Popup (jQuery plugin API only).
	 */
	function initMagnificPopup() {
		if ( typeof jQuery === 'undefined' || ! jQuery.fn.magnificPopup ) {
			return;
		}
		var $ = jQuery;
		var nodes = document.querySelectorAll(
			'.dsm_card_carousel .dsm_card_carousel_child_image_wrapper'
		);
		if ( ! nodes.length ) {
			return;
		}

		var videoRe =
			/(youtube\.com|youtu\.be|vimeo\.com|dailymotion\.com)/i;

		nodes.forEach( function ( el ) {
			el.addEventListener( 'click', function () {
				var itemsSrc = el.getAttribute( 'data-mfp-src' );
				if (
					! itemsSrc ||
					itemsSrc === 'undefined' ||
					itemsSrc === ''
				) {
					return;
				}

				var type = videoRe.test( itemsSrc ) ? 'iframe' : 'image';
				var classes = '';

				$.magnificPopup.open( {
					delegate: 'a',
					items: {
						src: itemsSrc,
					},
					type: type,
					iframe: {
						markup:
							'<div class="mfp-iframe-scaler dsm-video-popup">' +
							'<div class="mfp-close"></div>' +
							'<iframe class="mfp-iframe" frameborder="0" allowfullscreen allow="autoplay"></iframe>' +
							'</div>',
						patterns: {
							youtube: {
								index: 'youtube.com/',
								id: 'v=',
								src: '//www.youtube.com/embed/%id%?autoplay=1&rel=0',
							},
							youtu_be: {
								index: 'youtu.be',
								id: '/',
								src: '//www.youtube.com/embed/%id%?autoplay=1&rel=0',
							},
							vimeo: {
								index: 'vimeo.com/',
								id: '/',
								src: '//player.vimeo.com/video/%id%?autoplay=1',
							},
							dailymotion: {
								index: 'dailymotion.com',
								id: function ( url ) {
									var m = url.match(
										/^.+dailymotion.com\/(video|hub)\/([^_]+)[^#]*(#video=([^_&]+))?/
									);
									if ( m !== null ) {
										if ( m[ 4 ] !== undefined ) {
											return m[ 4 ];
										}
										return m[ 2 ];
									}
									return null;
								},
								src: 'https://www.dailymotion.com/embed/video/%id%',
							},
						},
						srcAction: 'iframe_src',
					},
					removalDelay: 500,
					mainClass: classes + 'mfp-fade',
				} );
			} );
		} );
	}

	function initSwipers() {
		if ( typeof Swiper === 'undefined' ) {
			return;
		}

		var wrappers = document.querySelectorAll(
			'.dsm_card_carousel .dsm_card_carousel_wrapper'
		);
		if ( ! wrappers.length ) {
			return;
		}

		bindGlobalResizeOnce();

		wrappers.forEach( function ( wrap ) {
			var rawParams = wrap.getAttribute( 'data-params' );
			if (
				! rawParams ||
				typeof rawParams !== 'string' ||
				'' === rawParams.trim()
			) {
				return;
			}

			var parsedParams;
			try {
				parsedParams = JSON.parse( rawParams );
			} catch ( err ) {
				return;
			}
			if (
				! parsedParams ||
				typeof parsedParams !== 'object' ||
				! parsedParams[ 0 ]
			) {
				return;
			}

			var params = parsedParams[ 0 ];

			var prevButton = getSibling( wrap, '.swiper-button-prev' );
			var nextButton = getSibling( wrap, '.swiper-button-next' );
			var paginationEl = getSibling(
				wrap,
				'.swiper-pagination.dsm_card_carousel_pagination'
			);
			if ( ! paginationEl ) {
				paginationEl = getSibling( wrap, '.swiper-pagination' );
			}

			var autoHeight = false !== params.auto_height;
			var checkAutoHeight =
				params.equal_height === true ? false : autoHeight;
			var autoHeightCheckTablet =
				true === params.equal_height_tablet ? false : true;
			var autoHeightCheckPhone =
				true === params.equal_height_phone ? false : true;

			var swiperOptions = {
				resizeObserver: true,
				observer: true,
				observeParents: true,
				observeSlideChildren: true,
				direction: params.direction,
				effect: params.effect,
				coverflowEffect: {
					slideShadows: params.slider_effect_shadows,
					rotate: params.slider_effect_coverflow_rotate,
					depth: params.slider_effect_coverflow_depth,
				},
				flipEffect: {
					rotate: 30,
					slideShadows: params.slider_effect_shadows,
				},
				cubeEffect: {
					slideShadows: params.slider_effect_shadows,
					shadow: params.slider_effect_shadows,
					shadowOffset: 20,
					shadowScale: 0.94,
				},
				centeredSlides: params.centered_slides,
				speed: parseInt( params.speed, 10 ),
				loop: params.loop,
				preventInteractionOnTransition: false,
				autoplay: {
					enabled: params.autoplay,
					delay:
						params.infinite_smooth_scrolling === true &&
						params.slide_to_show < 6
							? 1
							: parseInt( params.autoplay_speed, 10 ),
					disableOnInteraction: false,
				},
				mousewheel: params.mousewheel,
				grabCursor:
					false === params.touch_move ? false : params.grab,
				preloadImages: false,
				lazy: {
					loadPrevNext: true,
				},
				allowTouchMove: params.touch_move,
				a11y: {
					enabled: false,
					slideRole: 'group',
				},
				breakpoints: {
					981: {
						slidesPerView:
							'cube' === params.effect ||
							'flip' === params.effect
								? 1
								: parseInt( params.slide_to_show, 10 ),
						slidesPerGroup: parseInt(
							params.slide_to_scroll,
							10
						),
						spaceBetween: parseInt(
							params.space_between,
							10
						),
						grid: {
							rows: params.slide_row,
							fill: 'row',
						},
						autoHeight:
							'on' === params.multiple_slide_row
								? false
								: checkAutoHeight,
					},
					768: {
						slidesPerView:
							'cube' === params.effect ||
							'flip' === params.effect
								? 1
								: params.slide_to_show_tablet === ''
								? parseInt( params.slide_to_show, 10 )
								: parseInt(
										params.slide_to_show_tablet,
										10
								  ),
						slidesPerGroup:
							params.slide_to_scroll_tablet === ''
								? 1
								: parseInt(
										params.slide_to_scroll_tablet,
										10
								  ),
						spaceBetween:
							params.space_between_tablet === ''
								? 10
								: parseInt(
										params.space_between_tablet,
										10
								  ),
						grid: {
							rows: params.slide_row_tablet,
							fill: 'row',
						},
						autoHeight:
							'on' === params.multiple_slide_row
								? false
								: autoHeightCheckTablet,
					},
					480: {
						slidesPerView:
							'cube' === params.effect ||
							'flip' === params.effect
								? 1
								: params.slide_to_show_phone === ''
								? 1
								: parseInt(
										params.slide_to_show_phone,
										10
								  ),
						slidesPerGroup:
							params.slide_to_scroll_phone === ''
								? 1
								: parseInt(
										params.slide_to_scroll_phone,
										10
								  ),
						spaceBetween:
							params.space_between_phone === ''
								? 10
								: parseInt(
										params.space_between_phone,
										10
								  ),
						grid: {
							rows: params.slide_row_phone,
							fill: 'row',
						},
						autoHeight:
							'on' === params.multiple_slide_row
								? false
								: autoHeightCheckPhone,
					},
					320: {
						slidesPerView:
							'cube' === params.effect ||
							'flip' === params.effect
								? 1
								: params.slide_to_show_phone === ''
								? 1
								: parseInt(
										params.slide_to_show_phone,
										10
								  ),
						slidesPerGroup:
							params.slide_to_scroll_phone === ''
								? 1
								: parseInt(
										params.slide_to_scroll_phone,
										10
								  ),
						spaceBetween:
							params.space_between_phone === ''
								? 10
								: parseInt(
										params.space_between_phone,
										10
								  ),
						grid: {
							rows: params.slide_row_phone,
							fill: 'row',
						},
						autoHeight:
							'on' === params.multiple_slide_row
								? false
								: autoHeightCheckPhone,
					},
				},
			};

			if ( paginationEl ) {
				swiperOptions.pagination = {
					el: paginationEl,
					type: 'bullets',
					clickable: true,
				};
			}

			if ( prevButton && nextButton ) {
				swiperOptions.navigation = {
					nextEl: nextButton,
					prevEl: prevButton,
				};
			}

			var DSM_CardSwiper = new Swiper( wrap, swiperOptions );
			cardCarouselSwipers.push( DSM_CardSwiper );

			if ( params.pause_on_hover === true ) {
				wrap.addEventListener( 'mouseenter', function () {
					DSM_CardSwiper.autoplay.stop();
				} );
				wrap.addEventListener( 'mouseleave', function () {
					DSM_CardSwiper.autoplay.start();
				} );
			}

			var tabsRoot = wrap.closest( '.et_pb_tabs' );
			if ( tabsRoot ) {
				tabsRoot.querySelectorAll( 'a' ).forEach( function ( a ) {
					a.addEventListener( 'click', function () {
						DSM_CardSwiper.slideTo(
							DSM_CardSwiper.realIndex,
							0
						);
					} );
				} );
			}

			var advTabs = wrap.closest( '.dsm_advanced_tabs' );
			if ( advTabs ) {
				advTabs.querySelectorAll( '.dsm-tab' ).forEach( function ( tab ) {
					tab.addEventListener( 'click', function () {
						DSM_CardSwiper.slideTo(
							DSM_CardSwiper.realIndex,
							0
						);
					} );
				} );
			}

			if ( params.autoplay === true ) {
				if ( typeof Waypoint === 'undefined' ) {
					DSM_CardSwiper.autoplay.start();
				} else {
					// eslint-disable-next-line no-new
					new Waypoint( {
						element: wrap,
						handler: function () {
							DSM_CardSwiper.autoplay.start();
							this.destroy();
						},
						offset: params.autoplay_viewport,
					} );
				}
			}
		} );
	}

	function init() {
		if ( document.querySelector( '.dsm_card_carousel' ) ) {
			initMagnificPopup();
		}
		initSwipers();
	}

	if ( document.readyState === 'loading' ) {
		document.addEventListener( 'DOMContentLoaded', init );
	} else {
		init();
	}
} )();
