( function( $ ) {

	/**
	 * Image preview and slider
	 *
	 * @type {Object}
	 */
	var rweSlider = {

		init: function() {

			var $carousel = $( '.rwe-gallery__for' ),
				$nav      = $( '.rwe-gallery__nav' );

			if ( ! $carousel.length ) {

				return;

			}

			$carousel.slick( {
				slidesToShow: 1,
				slidesToScroll: 1,
				arrows: false,
				fade: true,
				centerPadding: '0',
				asNavFor: '.rwe-gallery__nav'
			} );

			$nav.slick( {
				slidesToShow: 4,
				slidesToScroll: 1,
				focusOnSelect: true,
				centerPadding: '0',
				asNavFor: '.rwe-gallery__for'
			} );

			$carousel.slickLightbox({
				itemSelector: 'a',
				itemTemplate: function (source, caption, lazy, el) {
					var isVideo = false;
					// Try to detect if this is a video slide
					if (el && (el.getAttribute && el.getAttribute('data-type') === 'video')) {
						isVideo = true;
					}
					if (isVideo) {
						return '<div class="slick-lightbox-slick-item">\n  <div class="slick-lightbox-slick-item-inner">\n    <div class="rwe-lightbox-video-container" style="position:relative;display:inline-block;">\n      <video muted preload="metadata" style="max-width:100%;max-height:80vh;display:block;margin:0 auto;pointer-events:none;">\n        <source src="' + source + '" type="video/mp4" />\n        Your browser does not support the video tag.\n      </video>\n      <div class="rwe-lightbox-video-play-overlay" style="position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);z-index:2;cursor:pointer;width:44px;height:44px;display:flex;align-items:center;justify-content:center;"><svg width="44" height="44" viewBox="0 0 44 44"><circle cx="22" cy="22" r="22" fill="rgba(0,0,0,0.5)"/><polygon points="18,11 34,22 18,33" fill="#fff"/></svg></div>\n      <div class="rwe-lightbox-video-pause-overlay" style="position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);z-index:2;cursor:pointer;width:44px;height:44px;display:none;align-items:center;justify-content:center;"><svg width="44" height="44" viewBox="0 0 44 44"><circle cx="22" cy="22" r="22" fill="rgba(0,0,0,0.5)"/><rect x="12" y="10" width="6" height="24" fill="#fff"/><rect x="26" y="10" width="6" height="24" fill="#fff"/></svg></div>\n    </div>\n    ' + (caption || '') + '\n  </div>\n</div>';
					} else {
						var imgSourceParams;
						var altText = caption ? caption.replace(/<[^>]*>?/gm, '').replace(/"/g, '&quot;') : 'Gallery image';
						if (lazy === true) {
							imgSourceParams = ' data-lazy="' + source + '" src="' + lazyPlaceholder + '" ';
						} else {
							imgSourceParams = ' src="' + source + '" ';
						}
						return '<div class="slick-lightbox-slick-item">\n  <div class="slick-lightbox-slick-item-inner">\n    <img class="slick-lightbox-slick-img" ' + imgSourceParams + ' alt="' + altText + '" />\n    ' + caption + '\n  </div>\n</div>';
					}
				},
				src: function (el) {
					return $(el).attr('href');
				},
				caption: false
			});

			// Prevent FOUC of the image slider
			setTimeout( function() {

				// Fade out the preloader
				$( '.rwe-single__gallery' ).find( '.rwe-circle-preloader' ).fadeOut( 'fast', function() {

					// Fade in the image slider
					$( '.rwe-gallery' ).removeAttr( 'style' );
					$( '.slick-track, .rwe-gallery' ).fadeTo( 800, 1 );

				} );

			}, 400 );

		},

	};

  /**
   * pikaday date selector.
   *
   * @type {Object}
   */
  var pikaday = {

    init: function() {

      if ( ! $( '.js-date' ).length ) {

        return;

      }

      $( '.js-date' ).each( function() {
        new Pikaday( {
          field: $( this )[0],
          format: 'MM-DD-YYYY'
        } );
      } );

    },

  };

	/**
   * Wishlist submission validation
   *
   * @type {Object}
   */
	var submitWishlist = {

		submit: function( e ) {

			var date = $( '#event_date' ).val();

			if ( ! date.length ) {

				e.preventDefault();

				return;

			}

			$( '#event_date' ).css( 'border-color', '' );
			$( '.rwe-wishlist-error' ).remove();
			jQuery( '.rwe-wishlist-form .rwe-circle-preloader' ).addClass( 'hidden' );

			jQuery( '.rwe-wishlist-form input' ).each( function() {

				jQuery( this ).removeAttr( 'disabled' ).css( 'opacity', 1 );

			} );

			if ( ! submitWishlist.validateDate( date ) ) {

				$( '#event_date' ).css( 'border-color', '#ffa5a5' ).after( '<p class="rwe-wishlist-error">' + rwe.i18n.invalidDateFormat + '</p>' );

				e.preventDefault();

				return;

			}

			jQuery( '.rwe-wishlist-form input' ).each( function() {

				jQuery( this ).css( 'opacity', 0.5 );

			} );

			jQuery( '.rwe-wishlist-form .rwe-circle-preloader' ).removeClass( 'hidden' );

		},

		validateDate: function( date ) {

			var dateRegex = /^(0[1-9]|1[0-2])-(0[1-9]|1\d|2\d|3[01])-(19|20)\d{2}$/;

			return dateRegex.test( date );

		},

	};

  // Video controls
  $( '.rwe-gallery__item video' ).on( 'click', function( e ) {
	  var video  = $( this );
	  var play   = $( this ).next( '.controls' ).find( '.play' );
	  var pause  = $( this ).next( '.controls' ).find( '.pause' );
	  var parent = $( this ).parent( '.rwe-gallery__item' );
	  if( video[0].paused || video[0].ended ) {
		  video[0].play();
		  play.hide();
		  pause.show();
		  parent.toggleClass( 'is_playing' );
	  } else {
		  video[0].pause();
		  play.show();
		  pause.hide();
		  parent.toggleClass( 'is_playing' );
	  }
	  return false;
  } );

	$( '.rwe-gallery__item video' ).on( 'ended', function( e ) {
		var play   = $( this ).next( '.controls' ).find( '.play' );
		var pause  = $( this ).next( '.controls' ).find( '.pause' );
		var parent = $( this ).parent( '.rwe-gallery__item' );

		play.show();
		pause.hide();
		parent.toggleClass( 'is_playing' );
		return false;
	} );

	// Image preview and slider
	$( window ).on( 'load', rweSlider.init );

  // Date picker
  $( window ).on( 'load', pikaday.init );

  // Clientside validatiion the wishlist fields as needed
  $( 'body' ).on( 'submit', '.rwe-wishlist-form', submitWishlist.submit );

  // When you select an item from the #rwe-item__variations dropdown, append the select value as a query parameter and reload the page
	  $( 'body' ).on( 'change', '#rwe-item__variations', function() {
		  console.log( 'Variation selected' );
	  var selectedVariation = $( this ).val();

	  if ( selectedVariation ) {

		  var url = new URL( window.location.href );
		  url.searchParams.set( 'variation', selectedVariation );
		  window.location.href = url.toString();

	 }

  } );

	// --- Video Icon for Thumbnail Nav ---
function injectNavVideoIcons() {
    $('.rwe-gallery__nav .rwe-gallery__thumb--video').each(function() {
        var $thumb = $(this);
        if (!$thumb.find('.rwe-nav-video-icon').length) {
            $thumb.css('position', 'relative');
            $thumb.append('<div class="rwe-nav-video-icon" style="position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);pointer-events:none;z-index:2;width:24px;height:24px;display:flex;align-items:center;justify-content:center;"><svg width="24" height="24" viewBox="0 0 24 24"><circle cx="12" cy="12" r="12" fill="rgba(0,0,0,0.5)"/><polygon points="10,6 19,12 10,18" fill="#fff"/></svg></div>');
        }
    });
}

	// --- Video Play Button and Lightbox Logic for Main Slider ---
function injectVideoOverlays() {
    $('.rwe-gallery__for .slick-slide').each(function() {
        var $slide = $(this);
        var $video = $slide.find('video');
        if ($video.length && !$slide.find('.rwe-video-play-overlay').length) {
            // Mute the video
            $video.prop('muted', true);
            $video.css('pointer-events', 'none');
            $video.wrap('<div class="rwe-video-container" style="position:relative;display:inline-block;width:100%"></div>');
            var $container = $video.parent();
            // Overlay for opening lightbox
            $container.append('<div class="rwe-video-lightbox-overlay" style="position:absolute;top:0;left:0;width:100%;height:100%;z-index:1;cursor:pointer;"></div>');
            // Play overlay (centered, 44x44)
            $container.append('<div class="rwe-video-play-overlay" style="position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);z-index:2;cursor:pointer;width:44px;height:44px;display:flex;align-items:center;justify-content:center;"><svg width="44" height="44" viewBox="0 0 44 44"><circle cx="22" cy="22" r="22" fill="rgba(0,0,0,0.5)"/><polygon points="18,11 34,22 18,33" fill="#fff"/></svg></div>');
            // Pause overlay (centered, 44x44)
            $container.append('<div class="rwe-video-pause-overlay" style="position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);z-index:2;cursor:pointer;width:44px;height:44px;display:none;align-items:center;justify-content:center;"><svg width="44" height="44" viewBox="0 0 44 44"><circle cx="22" cy="22" r="22" fill="rgba(0,0,0,0.5)"/><rect x="12" y="10" width="6" height="24" fill="#fff"/><rect x="26" y="10" width="6" height="24" fill="#fff"/></svg></div>');
            // Attach direct ended event handler to video
            $video.off('ended.rwe').on('ended.rwe', function() {
                var $container = $(this).closest('.rwe-video-container');
                $container.find('.rwe-video-play-overlay').show();
                $container.find('.rwe-video-pause-overlay').hide();
            });
        }
    });
}

$(function() {
    injectVideoOverlays();
    $('.rwe-gallery__for').on('init', function() {
        injectVideoOverlays();
    });
    $('.rwe-gallery__for').on('afterChange', function() {
        injectVideoOverlays();
    });

    // Inject play icons on video thumbnails in the nav track
    $('.rwe-gallery__nav').on('init', function() {
        injectNavVideoIcons();
    });

    // Play overlay: play video inline
    $('.rwe-gallery__for').on('click', '.rwe-video-play-overlay', function(e) {
        e.preventDefault(); // Prevent navigation if inside anchor
        e.stopPropagation();
        var $container = $(this).closest('.rwe-video-container');
        var $video = $container.find('video')[0];
        if ($video.paused || $video.ended) {
            $video.play();
            $container.find('.rwe-video-play-overlay').hide();
            $container.find('.rwe-video-pause-overlay').show();
        }
    });

    // Pause overlay: pause video inline
    $('.rwe-gallery__for').on('click', '.rwe-video-pause-overlay', function(e) {
        e.preventDefault(); // Prevent navigation if inside anchor
        e.stopPropagation();
        var $container = $(this).closest('.rwe-video-container');
        var $video = $container.find('video')[0];
        if (!$video.paused) {
            $video.pause();
            $container.find('.rwe-video-play-overlay').show();
            $container.find('.rwe-video-pause-overlay').hide();
        }
    });

    // Lightbox overlay: open video in lightbox
    $('.rwe-gallery__for').on('click', '.rwe-video-lightbox-overlay', function(e) {
        e.preventDefault();
        e.stopPropagation();
        var $slide = $(this).closest('.slick-slide');
        // Find the anchor element inside the slide and trigger its click
        var $anchor = $slide.find('a').first();
        if ($anchor.length) {
            $anchor.trigger('click');
        } else {
            // Fallback: trigger click on the slide itself
            $slide.trigger('click');
        }
    });

    // Update overlays on video play/pause/ended events
    $('.rwe-gallery__for').on('play pause ended', 'video', function(e) {
        var $container = $(this).closest('.rwe-video-container');
        if (e.type === 'play') {
            $container.find('.rwe-video-play-overlay').hide();
            $container.find('.rwe-video-pause-overlay').show();
        } else if (e.type === 'pause') {
            $container.find('.rwe-video-play-overlay').show();
            $container.find('.rwe-video-pause-overlay').hide();
        } else if (e.type === 'ended') {
            // When video ends, always show play overlay and hide pause overlay
            $container.find('.rwe-video-play-overlay').show();
            $container.find('.rwe-video-pause-overlay').hide();
        }
    });
});

} )( jQuery );
