/* Media library picker for the colour term's shirt photo. */
import $ from 'jquery';
import { chooseImage, type MediaLabels } from './media.ts';

declare const printblobTermImage: MediaLabels;

$( document ).on( 'click', '[data-printblob-term-image] [data-printblob-choose]', function ( event ) {
	event.preventDefault();
	const field = $( this ).closest( '[data-printblob-term-image]' );
	chooseImage( printblobTermImage, ( image ) => {
		const preview = image.sizes?.thumbnail?.url ?? image.url;
		field.find( 'input[name="printblob_image"]' ).val( image.id );
		field.find( '.printblob-term-image__preview' ).empty().append( $( '<img>', { src: preview, alt: '', width: 150 } ) );
		field.find( '[data-printblob-remove]' ).prop( 'hidden', false );
	} );
} );

$( document ).on( 'click', '[data-printblob-term-image] [data-printblob-remove]', function ( event ) {
	event.preventDefault();
	const field = $( this ).closest( '[data-printblob-term-image]' );
	field.find( 'input[name="printblob_image"]' ).val( '' );
	field.find( '.printblob-term-image__preview' ).empty();
	$( this ).prop( 'hidden', true );
} );

// The "Add new term" form is submitted with AJAX; clear the picker afterwards.
$( document ).on( 'ajaxComplete', function ( event, xhr, settings ) {
	if ( typeof settings.data === 'string' && settings.data.indexOf( 'action=add-tag' ) !== -1 ) {
		$( '#addtag [data-printblob-term-image] [data-printblob-remove]' ).trigger( 'click' );
	}
} );
