/* Flipa front-end: lightbox opener for any .flipa-lb-trigger (data-flipa-src = viewer URL). */
( function () {
	var overlay;
	function ensureOverlay() {
		if ( overlay ) { return overlay; }
		overlay = document.createElement( 'div' );
		overlay.className = 'flipa-lb-overlay';
		overlay.innerHTML = '<div class="flipa-lb-box"><button class="flipa-lb-close" type="button" aria-label="Close">✕</button><iframe allowfullscreen></iframe></div>';
		document.body.appendChild( overlay );
		function close() {
			overlay.classList.remove( 'open' );
			overlay.querySelector( 'iframe' ).src = 'about:blank';
			document.documentElement.style.overflow = '';
		}
		overlay.querySelector( '.flipa-lb-close' ).addEventListener( 'click', close );
		overlay.addEventListener( 'click', function ( e ) { if ( e.target === overlay ) { close(); } } );
		document.addEventListener( 'keydown', function ( e ) {
			if ( e.key === 'Escape' && overlay.classList.contains( 'open' ) ) { close(); }
		} );
		return overlay;
	}
	function open( src ) {
		var o = ensureOverlay();
		o.querySelector( 'iframe' ).src = src;
		o.classList.add( 'open' );
		document.documentElement.style.overflow = 'hidden';
	}
	document.addEventListener( 'click', function ( e ) {
		var t = e.target.closest ? e.target.closest( '.flipa-lb-trigger' ) : null;
		if ( ! t ) { return; }
		var src = t.getAttribute( 'data-flipa-src' );
		if ( src ) { e.preventDefault(); open( src ); }
	} );

	// Inline (seamless) embeds: the engine posts its height; resize the matching iframe to fit.
	window.addEventListener( 'message', function ( e ) {
		var d = e.data;
		if ( ! d || d.flipa !== 'height' || ! d.h ) { return; }
		var frames = document.querySelectorAll( 'iframe[data-flipa-autoheight]' );
		for ( var i = 0; i < frames.length; i++ ) {
			if ( frames[ i ].contentWindow === e.source ) { frames[ i ].style.height = d.h + 'px'; break; }
		}
	} );
} )();
