/**
 * Elementor frontend handler — Product Image widget.
 *
 * Only drives the optional lightbox (zoom) link mode; everything else is pure
 * CSS. The overlay is shared across every instance on the page.
 *
 * @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 with an open() method.
	 */
	function getLightbox() {
		if ( lightbox ) {
			return lightbox;
		}

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

		var imgEl = overlay.querySelector( '.captwiki-pi-lightbox__img' );

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

		overlay.querySelector( '.captwiki-pi-lightbox__close' ).addEventListener( 'click', close );
		overlay.addEventListener( 'click', function ( e ) {
			if ( e.target === overlay ) {
				close();
			}
		} );
		document.addEventListener( 'keyup', function ( e ) {
			if ( e.key === 'Escape' && overlay.classList.contains( 'is-open' ) ) {
				close();
			}
		} );

		lightbox = {
			open: function ( src ) {
				if ( ! src ) {
					return;
				}
				imgEl.src = src;
				overlay.classList.add( 'is-open' );
				document.body.classList.add( 'captwiki-pi-lightbox-open' );
			},
		};

		return lightbox;
	}

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

		var trigger = root.querySelector( '.captwiki-pi__lightbox' );
		if ( ! trigger ) {
			return;
		}

		trigger.addEventListener( 'click', function ( e ) {
			e.preventDefault();
			getLightbox().open( trigger.getAttribute( 'data-full' ) );
		} );
	}

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

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

} )( jQuery, window, document );
