import { __ } from '@wordpress/i18n';

export const normalizeMediaAttachment = ( attachment ) => {
	if ( ! attachment ) {
		return null;
	}

	const url =
		attachment.url ||
		attachment.source_url ||
		attachment?.sizes?.full?.url ||
		attachment?.sizes?.large?.url ||
		attachment?.sizes?.medium?.url ||
		'';

	return {
		id: attachment.id,
		url,
		alt: attachment.alt,
		title: attachment.title,
		sizes: attachment.sizes ?? {},
	};
};

export const openMediaLibrary = ( {
	field,
	multiple = false,
	value,
	onSelect,
} ) => {
	const wpMedia = window?.wp?.media;

	if ( ! wpMedia ) {
		window.console?.warn( 'WordPress media library is not available' );
		return;
	}

	const frame = wpMedia( {
		title:
			field.mediaTitle ??
			field.label ??
			__( 'Select media', 'cliq-store-locator' ),
		button: {
			text:
				field.mediaButtonLabel ??
				__( 'Use selection', 'cliq-store-locator' ),
		},
		multiple,
		library: field.mediaLibrary ?? {},
	} );

	frame.on( 'open', () => {
		const selection = frame.state().get( 'selection' );
		selection.reset();

		let current = [];

		if ( multiple ) {
			current = ( Array.isArray( value ) ? value : [] ).filter(
				( item ) => item?.id
			);
		} else if ( value && value.id ) {
			current = [ value ];
		}

		current.forEach( ( item ) => {
			const attachment = wpMedia.attachment( item.id );
			if ( attachment ) {
				attachment.fetch();
				selection.add( attachment );
			}
		} );
	} );

	frame.on( 'select', () => {
		const selection = frame.state().get( 'selection' );
		const attachments = selection?.toJSON?.() ?? [];

		if ( multiple ) {
			const normalized = attachments
				.map( normalizeMediaAttachment )
				.filter( Boolean );
			onSelect( normalized );
			return;
		}

		const [ first ] = attachments;
		onSelect( normalizeMediaAttachment( first ) );
	} );

	frame.open();
};
