/**
 * @file assets/js/adminjs/admin-collections.js
 * Reading-order drag-and-drop and banner image picker on the Collections tab.
 * Sortable machinery delegated to MBS_AdminUtils.initReadingOrderSortable() (D-006).
 * Banner picker delegated to MBS_AdminUtils.createMediaFrame() (F-BNR-C / PLG-052).
 * @package MyBookShowroom
 * @since   1.0.0
 */

( function ( $ ) {
	'use strict';

	var __ = wp.i18n.__;

	MBS_AdminUtils.initReadingOrderSortable( { entity: 'collection' } );

	// Collection Banner Upload (F-BNR-C)
	var collectionBannerRef = { frame: null };

	$( document ).on( 'click', '.mbs-collection-banner-select', function ( e ) {
		e.preventDefault();
		var $btn      = $( this );
		var termId    = $btn.data( 'term-id' );
		var inputId   = $btn.data( 'input' );
		var previewId = $btn.data( 'preview' );

		if ( collectionBannerRef.frame ) {
			collectionBannerRef.frame.open();
			return;
		}

		collectionBannerRef.frame = MBS_AdminUtils.createMediaFrame( {
			title:      __( 'Select Collection Banner', 'my-book-showroom' ),
			buttonText: __( 'Use this image', 'my-book-showroom' ),
			outerRef:   collectionBannerRef,
			onSelect: function ( attachment ) {
				var imgSrc = ( attachment.sizes && attachment.sizes.medium )
					? attachment.sizes.medium.url
					: attachment.url;
				$( '#' + inputId ).val( attachment.id );
				$( '#' + previewId ).attr( 'src', imgSrc ).prop( 'hidden', false );
				$btn.text( __( 'Change', 'my-book-showroom' ) );
				$( '.mbs-collection-banner-remove[data-term-id="' + termId + '"]' ).prop( 'hidden', false );
				$( '#mbs-collection-banner-hint-' + termId ).prop( 'hidden', false );
			},
		} );
	} );

	$( document ).on( 'click', '.mbs-collection-banner-remove', function ( e ) {
		e.preventDefault();
		var $btn      = $( this );
		var termId    = $btn.data( 'term-id' );
		var previewId = $btn.data( 'preview' );
		var inputId   = $btn.data( 'input' );
		$( '#' + previewId ).prop( 'hidden', true ).attr( 'src', '' );
		$( '#' + inputId ).val( '' );
		$( '.mbs-collection-banner-select[data-term-id="' + termId + '"]' ).text( __( 'Add Banner', 'my-book-showroom' ) );
		$btn.prop( 'hidden', true );
	} );

} )( jQuery );
