(function ($) {
	"use strict";

	var WidgetStickyVideo = function ($scope, $) {
		if ($scope.find( '.ec-sticky-video-wrapper' ).length) {
			var esvwrap     = $scope.find( '.ec-sticky-video-wrapper' );
			var esvideo     = esvwrap.find( '.ec-sticky-video' );
			var videoHeight = esvideo.outerHeight();
			var isPlaying   = false;
			var isSticky    = false;

			function ecVideoSticky() {
				if ( ! isPlaying) {
					return;
				}

				var windowScrollTop = $( window ).scrollTop();
				var videoBottom     = videoHeight + esvwrap.offset().top;

				if (windowScrollTop > videoBottom && ! isSticky) {
					isSticky = true;
					esvwrap.height( videoHeight );
					esvideo.addClass( 'ec-video-stick' ).css(
						{
							'opacity': '1',
							'transform': 'translateX(100%)',
							'transition': 'opacity 0.4s ease, transform 0.4s ease'
						}
					);

					setTimeout(
						function () {
							esvideo.css( { 'transform': 'translateX(0)' } );
						},
						10
					);
				} else if (windowScrollTop <= videoBottom && isSticky) {
					isSticky = false;
					esvideo.css(
						{
							'transform': 'translateX(100%)',
							'opacity': '0'
						}
					);

					setTimeout(
						function () {
							esvideo.removeClass( 'ec-video-stick' );
							esvwrap.height( 'auto' );
							esvideo.css(
								{
									'opacity': '',
									'transform': '',
									'transition': ''
								}
							);

						},
						400
					);
				}
			}

			$( window ).on( 'scroll', ecVideoSticky );
			esvwrap.find( '.ec-custom-video' ).on(
				'play',
				function () {
					isPlaying = true;
					ecVideoSticky();
				}
			);

			esvwrap.find( '.ec-custom-video' ).on(
				'pause ended',
				function () {
					setTimeout(
						function () {
							// Only hide the video if it's still paused after a short delay
							if (esvwrap.find( '.ec-custom-video' )[0].paused) {
								console.log( 'hiii' );
								isPlaying = false;
								if (isSticky) {
									isSticky = false;
									esvideo.css(
										{
											'transform': 'translateX(100%)',
											'opacity': '0'
										}
									);

									setTimeout(
										function () {
											esvideo.removeClass( 'ec-video-stick' );
											esvwrap.height( 'auto' );
											esvideo.css(
												{
													'opacity': '',
													'transform': '',
													'transition': ''
												}
											);
										},
										400
									);
								}
							}
						},
						100
					); // 100ms delay to verify if it's a real pause
				}
			);
		}
	};

	$( window ).on(
		'elementor/frontend/init',
		function () {
			elementorFrontend.hooks.addAction( 'frontend/element_ready/ecafe-sticky-video.default', WidgetStickyVideo );
		}
	);
})( jQuery );