/**
 * GENE Motion Blocks — shared media helpers (editor + save).
 *
 * Every media block maps the WordPress media object down to the small, stable
 * shape we store in attributes, and renders an <img> or a muted <video> from it.
 * Keeping one copy here means the new blocks (compare / marquee / cube / stack /
 * reveal / tilt) don't each re-derive it, and the saved markup stays identical
 * across blocks.
 */

/** Map one WP media object to our stored shape ({} when empty). */
export function mapOne( m ) {
	if ( ! m || ! m.url ) return {};
	return {
		id: m.id,
		url: m.url,
		alt: m.alt || '',
		type: m.type === 'video' ? 'video' : 'image',
		poster: ( m.image && m.image.src ) || '',
	};
}

/** Map an array of WP media objects (gallery / multiple="add" selections). */
export function mapMedia( media ) {
	return ( media || [] ).map( mapOne );
}

/**
 * Render a stored media item. In the editor a video is muted + playsInline and
 * left un-played (calm canvas); on the front end (`live`) it also loops and
 * autoplays so it behaves like the image fallbacks around it. `lazy` adds
 * loading="lazy" to images in saved markup.
 */
export function Media( { m, live, lazy } ) {
	if ( ! m || ! m.url ) return null;
	if ( m.type === 'video' ) {
		return (
			<video
				src={ m.url }
				poster={ m.poster || undefined }
				muted
				playsInline
				loop={ live ? true : undefined }
				autoPlay={ live ? true : undefined }
				preload="metadata"
			/>
		);
	}
	return (
		<img src={ m.url } alt={ m.alt || '' } loading={ lazy ? 'lazy' : undefined } />
	);
}
