/**
 * Media library picker that works in the admin SPA and Gutenberg.
 * Uses wp.media directly — no MediaUploadCheck / block-editor settings required.
 */
import { __ } from '@wordpress/i18n';

/**
 * Open the WP media modal.
 *
 * @param {object}   options
 * @param {Function} options.onSelect
 * @param {string[]} [options.allowedTypes]
 * @param {boolean}  [options.multiple]
 * @param {string}   [options.title]
 */
export function openMediaLibrary( {
	onSelect,
	allowedTypes = [ 'image' ],
	multiple = false,
	title,
} = {} ) {
	const wpMedia =
		typeof window !== 'undefined' && window.wp && window.wp.media
			? window.wp.media
			: null;

	if ( ! wpMedia || typeof onSelect !== 'function' ) {
		window.alert(
			__(
				'Media library is not available. Reload the page and try again.',
				'joc-blockora-morph'
			)
		);
		return;
	}

	const types = Array.isArray( allowedTypes )
		? allowedTypes.filter( Boolean )
		: [ 'image' ];

	const frame = wpMedia( {
		title: title || __( 'Select media', 'joc-blockora-morph' ),
		button: {
			text: __( 'Use media', 'joc-blockora-morph' ),
		},
		multiple: Boolean( multiple ),
		library: types.length
			? {
					type: types.length === 1 ? types[ 0 ] : types,
			  }
			: undefined,
	} );

	frame.on( 'select', () => {
		const selection = frame.state().get( 'selection' );
		if ( ! selection ) {
			frame.close();
			return;
		}
		if ( multiple ) {
			onSelect( selection.toJSON() );
		} else {
			const first = selection.first();
			if ( first ) {
				onSelect( first.toJSON() );
			}
		}
		// Ensure the modal + backdrop release focus/pointer capture.
		frame.close();
	} );

	frame.on( 'close', () => {
		try {
			frame.detach();
		} catch ( e ) {
			// ignore
		}
	} );

	frame.open();
}

/**
 * Drop-in render-prop picker (same shape as block-editor MediaUpload).
 *
 * @param {object}   props
 * @param {Function} props.onSelect
 * @param {string[]} [props.allowedTypes]
 * @param {boolean}  [props.multiple]
 * @param {string}   [props.title]
 * @param {*}        [props.value] unused — kept for MediaUpload API parity
 * @param {Function} props.render  ({ open }) => ReactNode
 */
export default function BmMediaUpload( {
	onSelect,
	allowedTypes = [ 'image' ],
	multiple = false,
	title,
	value, // eslint-disable-line no-unused-vars
	render,
} ) {
	if ( typeof render !== 'function' ) {
		return null;
	}

	const open = () =>
		openMediaLibrary( {
			onSelect,
			allowedTypes,
			multiple,
			title,
		} );

	return render( { open } );
}
