/**
 * Craft Addons - Flip Container inline-editor preview.
 *
 * Loaded inside the WPBakery frontend (inline) editor iframe only (vc_is_inline).
 * Shows one face at a time as a single card and adds a "Flip" button to reveal
 * the other side for editing - instead of two separate stacked boxes. The current
 * side is shown by the Front/Back badge on each face.
 */
( function () {
	'use strict';

	function faces( card ) {
		return card.querySelectorAll( '.vc_cafw_flip_face' );
	}

	// Name of the currently visible side (from its hidden Front/Back label).
	function visibleSide( card ) {
		var sides = faces( card );
		for ( var i = 0; i < sides.length; i++ ) {
			if ( ! sides[ i ].hidden ) {
				var label = sides[ i ].querySelector( '.cafw-flip__editor-label' );
				return label ? label.textContent.trim() : '';
			}
		}
		return '';
	}

	// Show the current side inside the button (e.g. "Front ↻"); CSS keeps a fixed
	// width so Front and Back render the same size.
	function updateButton( card, btn ) {
		var side = visibleSide( card );
		btn.textContent = ( side || 'Flip' ) + ' ↻';
	}

	function flip( card, btn ) {
		faces( card ).forEach( function ( side ) {
			side.hidden = ! side.hidden;
			if ( ! side.hidden ) {
				side.classList.add( 'cafw-flip-anim' );
				window.setTimeout( function () {
					side.classList.remove( 'cafw-flip-anim' );
				}, 400 );
			}
		} );
		updateButton( card, btn );
	}

	function init() {
		document.querySelectorAll( '.cafw-flip--editor' ).forEach( function ( card ) {
			if ( card.querySelector( ':scope > .cafw-flip__flip-toggle' ) ) {
				return;
			}
			var sides = faces( card );
			if ( sides.length < 2 ) {
				return;
			}
			sides.forEach( function ( side, i ) {
				side.hidden = 0 !== i;
			} );
			var btn = document.createElement( 'button' );
			btn.type = 'button';
			btn.className = 'cafw-flip__flip-toggle';
			btn.setAttribute( 'contenteditable', 'false' );
			btn.addEventListener( 'click', function ( e ) {
				e.preventDefault();
				e.stopPropagation();
				flip( card, btn );
			} );
			card.appendChild( btn );
			updateButton( card, btn );
		} );
	}

	// The inline editor injects/re-renders elements after load; re-attach as needed.
	if ( window.MutationObserver ) {
		var pending = null;
		new MutationObserver( function () {
			window.clearTimeout( pending );
			pending = window.setTimeout( init, 200 );
		} ).observe( document.documentElement, { childList: true, subtree: true } );
	}

	if ( 'loading' === document.readyState ) {
		document.addEventListener( 'DOMContentLoaded', init );
	} else {
		init();
	}
} )();
