/**
 * @file assets/js/adminjs/admin-series.js
 * Reading-order drag-and-drop and Series Banner Upload on the Series tab.
 * Sortable machinery delegated to MBS_AdminUtils.initReadingOrderSortable() (D-006).
 * @package MyBookShowroom
 * @since   1.0.0
 */

( function ( $ ) {
	'use strict';

	var __ = wp.i18n.__;

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

	// -- Series Banner Upload (F-011) ----------------------------------------
	// Factory-managed frame via MBS_AdminUtils.createMediaFrame() (PLG-052/BNR-004).
	// outerRef nulls bannerRef.frame on select/close so the re-open guard works.
	var bannerRef = { frame: null };

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

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

	$( document ).on( 'click', '.mbs-series-banner-remove', function ( e ) {
		e.preventDefault();

		var termId    = $( this ).data( 'term-id' );
		var previewId = $( this ).data( 'preview' );
		var inputId   = $( this ).data( 'input' );

		$( '#' + previewId ).prop( 'hidden', true ).attr( 'src', '' );
		$( '#' + inputId ).val( '' );
		$( '.mbs-series-banner-select[data-term-id="' + termId + '"]' ).text( __( 'Add Banner', 'my-book-showroom' ) );
		$( this ).prop( 'hidden', true );
	} );

} )( jQuery );
