/**
 * Elementor frontend handler — Product Gallery widget.
 *
 * Drives thumbnail selection, prev/next arrows and a lightweight built-in
 * lightbox. Everything is self-contained (no theme gallery support required) so
 * it works on a single-product template or anywhere a specific product is chosen.
 *
 * @package captain-widgets-kit
 * @since   1.3.0
 */
( function ( $, window, document ) {
	'use strict';

	var lightbox = null;

	/**
	 * Lazily build the shared lightbox overlay.
	 *
	 * @return {Object} Lightbox API.
	 */
	function getLightbox() {
		if ( lightbox ) {
			return lightbox;
		}

		var overlay = document.createElement( 'div' );
		overlay.className = 'captwiki-pg-lightbox';
		overlay.setAttribute( 'role', 'dialog' );
		overlay.setAttribute( 'aria-modal', 'true' );
		overlay.innerHTML =
			'<button type="button" class="captwiki-pg-lightbox__close" aria-label="Close">&times;</button>' +
			'<button type="button" class="captwiki-pg-lightbox__nav captwiki-pg-lightbox__nav--prev" aria-label="Previous">&#10094;</button>' +
			'<img class="captwiki-pg-lightbox__img" src="" alt="" />' +
			'<button type="button" class="captwiki-pg-lightbox__nav captwiki-pg-lightbox__nav--next" aria-label="Next">&#10095;</button>';
		document.body.appendChild( overlay );

		var imgEl   = overlay.querySelector( '.captwiki-pg-lightbox__img' );
		var current = [];
		var index   = 0;

		function show( i ) {
			if ( ! current.length ) {
				return;
			}
			index = ( i + current.length ) % current.length;
			imgEl.src = current[ index ];
		}

		function close() {
			overlay.classList.remove( 'is-open' );
			document.body.classList.remove( 'captwiki-pg-lightbox-open' );
		}

		overlay.querySelector( '.captwiki-pg-lightbox__close' ).addEventListener( 'click', close );
		overlay.querySelector( '.captwiki-pg-lightbox__nav--prev' ).addEventListener( 'click', function () {
			show( index - 1 );
		} );
		overlay.querySelector( '.captwiki-pg-lightbox__nav--next' ).addEventListener( 'click', function () {
			show( index + 1 );
		} );
		overlay.addEventListener( 'click', function ( e ) {
			if ( e.target === overlay ) {
				close();
			}
		} );
		document.addEventListener( 'keyup', function ( e ) {
			if ( ! overlay.classList.contains( 'is-open' ) ) {
				return;
			}
			if ( e.key === 'Escape' ) {
				close();
			} else if ( e.key === 'ArrowLeft' ) {
				show( index - 1 );
			} else if ( e.key === 'ArrowRight' ) {
				show( index + 1 );
			}
		} );

		lightbox = {
			open: function ( images, start ) {
				current = images.filter( Boolean );
				overlay.classList.add( 'is-open' );
				document.body.classList.add( 'captwiki-pg-lightbox-open' );
				show( start || 0 );
			},
		};

		return lightbox;
	}

	/**
	 * Per-instance handler.
	 *
	 * @param {HTMLElement} root Gallery wrapper.
	 */
	function setupInstance( root ) {
		if ( ! root || root.captwikiPgReady ) {
			return;
		}
		root.captwikiPgReady = true;

		var useLightbox = root.getAttribute( 'data-lightbox' ) === '1';
		var thumbs      = Array.prototype.slice.call( root.querySelectorAll( '.captwiki-pg__thumb' ) );
		var mainImg     = root.querySelector( '.captwiki-pg__main-img' );
		var mainBtn     = root.querySelector( '.captwiki-pg__main-btn' );
		var current     = 0;

		// Ordered list of full-size URLs for the lightbox.
		var grids   = Array.prototype.slice.call( root.querySelectorAll( '.captwiki-pg__grid-item' ) );
		var fullSet = ( thumbs.length ? thumbs : grids ).map( function ( el ) {
			return el.getAttribute( 'data-full' );
		} );

		/**
		 * Select a thumbnail and swap the main image.
		 *
		 * @param {number} i Index to activate.
		 */
		function select( i ) {
			if ( ! thumbs.length || ! mainImg ) {
				return;
			}
			current = ( i + thumbs.length ) % thumbs.length;

			thumbs.forEach( function ( t, idx ) {
				t.classList.toggle( 'is-active', idx === current );
			} );

			var large = thumbs[ current ].getAttribute( 'data-large' );
			var full  = thumbs[ current ].getAttribute( 'data-full' );

			mainImg.classList.add( 'is-swapping' );
			window.setTimeout( function () {
				mainImg.src = large;
				mainImg.removeAttribute( 'srcset' );
				mainImg.classList.remove( 'is-swapping' );
			}, 120 );

			if ( mainBtn ) {
				mainBtn.setAttribute( 'data-full', full );
			}
		}

		thumbs.forEach( function ( thumb, idx ) {
			thumb.addEventListener( 'click', function () {
				select( idx );
			} );
		} );

		// Prev / next arrows.
		var prev = root.querySelector( '.captwiki-pg__nav--prev' );
		var next = root.querySelector( '.captwiki-pg__nav--next' );
		if ( prev ) {
			prev.addEventListener( 'click', function () {
				select( current - 1 );
			} );
		}
		if ( next ) {
			next.addEventListener( 'click', function () {
				select( current + 1 );
			} );
		}

		// Lightbox triggers.
		if ( useLightbox ) {
			if ( mainBtn ) {
				mainBtn.addEventListener( 'click', function () {
					getLightbox().open( fullSet, current );
				} );
			}
			grids.forEach( function ( item, idx ) {
				item.addEventListener( 'click', function () {
					getLightbox().open( fullSet, idx );
				} );
			} );
		}
	}

	$( window ).on( 'elementor/frontend/init', function () {
		elementorFrontend.hooks.addAction(
			'frontend/element_ready/captwiki-woo-product-gallery.default',
			function ( $scope ) {
				setupInstance( $scope[ 0 ].querySelector( '.captwiki-pg' ) || $scope[ 0 ] );
			}
		);
	} );

	$( function () {
		document.querySelectorAll( '.captwiki-pg' ).forEach( setupInstance );
	} );

} )( jQuery, window, document );
