/**
 * Hero slider — element keys per layout (Customize / Design lists).
 */

/** Reorderable content-stack keys (excludes column media — same as image-left/right heroes). */
export const SLIDE_LAYOUT_ELEMENTS = {
	simple: [ 'badge', 'header', 'subheader', 'image', 'logos', 'buttons' ],
	'image-left': [ 'badge', 'header', 'subheader', 'logos', 'buttons' ],
	'image-right': [ 'badge', 'header', 'subheader', 'logos', 'buttons' ],
	'video-background': [ 'badge', 'header', 'subheader', 'logos', 'buttons' ],
};

/**
 * Elements shown in the list but not drag-reorderable (column media lives outside
 * the content stack, like standalone media-left / media-right heroes).
 */
export const SLIDE_LAYOUT_STATIC_ELEMENTS = {
	'image-left': [ 'image' ],
	'image-right': [ 'image' ],
};

/** Layout options for Add slide / slide field select. */
export const SLIDE_LAYOUT_OPTIONS = [
	{ value: 'simple', label: 'Simple' },
	{ value: 'image-left', label: 'Media left' },
	{ value: 'image-right', label: 'Media right' },
	{ value: 'video-background', label: 'Video background' },
];

/**
 * @param {string} layout
 * @return {string}
 */
export function slideLayoutLabel( layout ) {
	const key = String( layout || 'simple' ).toLowerCase();
	const found = SLIDE_LAYOUT_OPTIONS.find( ( opt ) => opt.value === key );
	return found?.label || key;
}

/**
 * Reorderable element keys for a slide layout.
 *
 * @param {string} [layout]
 * @return {string[]}
 */
export function slideOrderDefaults( layout = 'simple' ) {
	const key = String( layout || 'simple' ).toLowerCase();
	return [
		...( SLIDE_LAYOUT_ELEMENTS[ key ] || SLIDE_LAYOUT_ELEMENTS.simple ),
	];
}

/**
 * Non-reorderable element keys still shown in the Elements list.
 *
 * @param {string} [layout]
 * @return {string[]}
 */
export function slideStaticElementKeys( layout = 'simple' ) {
	const key = String( layout || 'simple' ).toLowerCase();
	return [ ...( SLIDE_LAYOUT_STATIC_ELEMENTS[ key ] || [] ) ];
}

/**
 * Styleable fields available for a given slide layout (order + static).
 *
 * @param {Array<object>} styleable
 * @param {string} layout
 * @return {Array<object>}
 */
export function styleableFieldsForSlideLayout( styleable, layout ) {
	const key = String( layout || 'simple' ).toLowerCase();
	const allowed = new Set( [
		...slideOrderDefaults( key ),
		...slideStaticElementKeys( key ),
	] );
	return ( styleable || [] ).filter( ( f ) => allowed.has( f.key ) );
}

export { slideIndexFromElement, isSliderChromeTarget } from './selectionChrome';

/**
 * Pause autoplay and jump to a slide across parent + preview iframes.
 * While held, remounts keep autoplay off and stay on this slide.
 *
 * @param {number} index
 * @param {ParentNode|Document} [scope]
 */
export function focusBmSliderSlide( index, scope = document ) {
	const i = Number( index );
	if ( ! Number.isFinite( i ) || i < 0 ) {
		return;
	}
	const docs = [ scope ];
	try {
		scope.querySelectorAll?.( 'iframe' )?.forEach( ( frame ) => {
			try {
				if ( frame.contentDocument ) {
					docs.push( frame.contentDocument );
				}
			} catch ( e ) {
				// ignore
			}
		} );
	} catch ( e ) {
		// ignore
	}

	docs.forEach( ( doc ) => {
		const win = doc.defaultView || ( typeof window !== 'undefined' ? window : null );
		const api = win?.jocbmSlider;
		let roots = [];
		if ( doc.nodeType === 1 ) {
			// Element scope: only sliders under this block root.
			if ( doc.matches?.( '[data-bm-slider]' ) ) {
				roots = [ doc ];
			} else {
				roots = Array.from(
					doc.querySelectorAll?.( '[data-bm-slider]' ) || []
				);
			}
		} else {
			// Document: prefer the selected Gutenberg block so sibling heroes
			// are not all advanced to the same slide.
			const selected = doc.querySelector?.(
				'.wp-block.is-selected [data-bm-slider], .block-editor-block-list__block.is-selected [data-bm-slider], .is-selected [data-bm-slider]'
			);
			const preview = doc.querySelector?.(
				'.bm-preview-root [data-bm-slider]'
			);
			if ( selected ) {
				roots = [ selected ];
			} else if ( preview ) {
				roots = [ preview ];
			} else {
				roots = Array.from(
					doc.querySelectorAll?.( '[data-bm-slider]' ) || []
				);
			}
		}
		roots.forEach( ( root ) => {
			if ( api && typeof api.hold === 'function' ) {
				api.hold( root, i );
				return;
			}
			// Fallback when hold API is unavailable (older runtime).
			if ( typeof api?.pause === 'function' ) {
				api.pause( root );
			}
			if ( typeof api?.go === 'function' ) {
				api.go( root, i );
			}
			root.setAttribute?.( 'data-bm-hold-slide', String( i ) );
		} );
	} );
}

/**
 * Clear hold so autoplay can resume (when selection / slide focus is cleared).
 *
 * @param {ParentNode|Document} [scope]
 */
export function releaseBmSliderFocus( scope = document ) {
	const docs = [ scope ];
	try {
		scope.querySelectorAll?.( 'iframe' )?.forEach( ( frame ) => {
			try {
				if ( frame.contentDocument ) {
					docs.push( frame.contentDocument );
				}
			} catch ( e ) {
				// ignore
			}
		} );
	} catch ( e ) {
		// ignore
	}

	docs.forEach( ( doc ) => {
		const win = doc.defaultView || ( typeof window !== 'undefined' ? window : null );
		const api = win?.jocbmSlider;
		let roots = [];
		if ( doc.nodeType === 1 ) {
			if ( doc.matches?.( '[data-bm-slider]' ) ) {
				roots = [ doc ];
			} else {
				roots = Array.from(
					doc.querySelectorAll?.( '[data-bm-slider]' ) || []
				);
			}
		} else {
			const selected = doc.querySelector?.(
				'.wp-block.is-selected [data-bm-slider], .block-editor-block-list__block.is-selected [data-bm-slider], .is-selected [data-bm-slider]'
			);
			const preview = doc.querySelector?.(
				'.bm-preview-root [data-bm-slider]'
			);
			if ( selected ) {
				roots = [ selected ];
			} else if ( preview ) {
				roots = [ preview ];
			} else {
				roots = Array.from(
					doc.querySelectorAll?.( '[data-bm-slider]' ) || []
				);
			}
		}
		roots.forEach( ( root ) => {
			if ( api && typeof api.release === 'function' ) {
				api.release( root );
				return;
			}
			root.removeAttribute?.( 'data-bm-hold-slide' );
		} );
	} );
}
