/**
 * Shared helpers for JBM Library owner-variant selection in Gutenberg.
 */

export const LIB_PREFIX = 'joc-blockora-morph-lib/';

/** Block names that should skip the insert picker once (confirm / switch). */
export const skipPickerOnce = new Set();

export function getEditorMeta() {
	return typeof jocbmEditor !== 'undefined'
		? jocbmEditor
		: { libraryBlocks: [] };
}

export function catalogByName() {
	const map = new Map();
	const blocks = getEditorMeta().libraryBlocks || [];
	blocks.forEach( ( meta ) => {
		if ( meta?.name ) {
			map.set( meta.name, meta );
		}
		( meta?.variants || [] ).forEach( ( variant ) => {
			if ( variant?.name ) {
				map.set( variant.name, { ...variant, packType: 'variant' } );
			}
		} );
	} );
	return map;
}

/**
 * Resolve the original + variants family for a library block name.
 *
 * @param {string} blockName Gutenberg block name.
 * @return {{ parent: object, choices: object[] }|null}
 */
export function findVariantFamily( blockName ) {
	if ( ! blockName || ! String( blockName ).startsWith( LIB_PREFIX ) ) {
		return null;
	}
	const blocks = getEditorMeta().libraryBlocks || [];
	for ( const parent of blocks ) {
		const variants = Array.isArray( parent?.variants ) ? parent.variants : [];
		if ( ! variants.length ) {
			continue;
		}
		if ( parent.name === blockName ) {
			return { parent, choices: [ parent, ...variants ] };
		}
		if ( variants.some( ( variant ) => variant?.name === blockName ) ) {
			return { parent, choices: [ parent, ...variants ] };
		}
	}
	return null;
}
