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

( function ( $ ) {
	'use strict';

	var __ = wp.i18n.__;

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

	// Universe Banner Upload (F-BNR-U)
	var universeBannerRef = { frame: null };

	$( document ).on( 'click', '.mbs-universe-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 ( universeBannerRef.frame ) {
			universeBannerRef.frame.open();
			return;
		}

		universeBannerRef.frame = MBS_AdminUtils.createMediaFrame( {
			title:      __( 'Select Universe Banner', 'my-book-showroom' ),
			buttonText: __( 'Use this image', 'my-book-showroom' ),
			outerRef:   universeBannerRef,
			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-universe-banner-remove[data-term-id="' + termId + '"]' ).prop( 'hidden', false );
				$( '#mbs-universe-banner-hint-' + termId ).prop( 'hidden', false );
			},
		} );
	} );

	$( document ).on( 'click', '.mbs-universe-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-universe-banner-select[data-term-id="' + termId + '"]' ).text( __( 'Add Banner', 'my-book-showroom' ) );
		$btn.prop( 'hidden', true );
	} );

} )( jQuery );
