/**
 * @file assets/js/adminjs/repeater/mbs-book-cover.js
 * MBS.BookCover — default book cover wp.media handler (BUG-08)
 * Component of admin-repeater.js — extracted Session 94.
 * Dependency: mbs-admin-repeater (namespace initializer).
 * @package MyBookShowroom
 */

// =============================================================================
// Book Default Cover Upload  (BUG-08)
// =============================================================================
// The Upload Cover button in the Book Header had no wp.media handler — clicking
// it did nothing. This module wires it up exactly like the format-row cover
// picker in MBS.Repeater, but scoped to the single book-level default cover.
// =============================================================================

(function( MBS, $, undefined ) {
	'use strict';
	var __ = wp.i18n.__;

	MBS.BookCover = {
		mediaFrame: null,

		init: function() {
			if ( ! $( '#mbs-cover-upload' ).length ) {
				return;
			}
			this.bindUpload();
			this.bindRemove();
		},

		bindUpload: function() {
			const self = this;

			$( '#mbs-cover-upload' ).on( 'click', function( e ) {
				e.preventDefault();

				// Reuse the same frame instance to avoid duplicating event listeners.
				if ( self.mediaFrame ) {
					self.mediaFrame.open();
					return;
				}

				self.mediaFrame = wp.media( {
					title:    __( 'Select Book Cover', 'my-book-showroom' ),
					button:   { text: __( 'Use this image', 'my-book-showroom' ) },
					multiple: false,
					library:  { type: 'image' }
				} );

				self.mediaFrame.on( 'select', function() {
					const attachment = self.mediaFrame.state().get( 'selection' ).first().toJSON();
					const url        = ( attachment.sizes && attachment.sizes.medium )
					                 ? attachment.sizes.medium.url
					                 : attachment.url;

					// Update hidden field (name="_thumbnail_id" — WordPress featured image).
					$( '#mbs_cover_id' ).val( attachment.id );

					// Refresh preview.
					$( '#mbs-cover-preview' ).html(
						$( '<img>', {
							src:   url,
							alt:   __( 'Book cover', 'my-book-showroom' ),
							style: 'max-width:200px;display:block;margin-bottom:8px;'
						} )
					);

					// Update button label.
					$( '#mbs-cover-upload' ).text( __( 'Replace Cover', 'my-book-showroom' ) );

					// Show remove button — create it if PHP didn't render it
					// (PHP only renders it when a cover is already saved).
					if ( ! $( '#mbs-cover-remove' ).length ) {
						$( '#mbs-cover-upload' ).after(
							$( '<button>', {
								type:  'button',
								id:    'mbs-cover-remove',
								class: 'button button-link-delete mbs-cover-remove',
								text:  __( 'Remove', 'my-book-showroom' )
							} ).css( 'margin-left', '6px' )
						);
					} else {
						$( '#mbs-cover-remove' ).show();
					}
				} );

				self.mediaFrame.open();
			} );
		},

		bindRemove: function() {
			// Delegated so it catches both the PHP-rendered button and any
			// dynamically inserted one added by bindUpload above.
			$( document ).on( 'click', '#mbs-cover-remove, .mbs-cover-remove', function( e ) {
				e.preventDefault();
				// Empty value → save() calls delete_post_thumbnail().
				$( '#mbs_cover_id' ).val( '' );
				$( '#mbs-cover-preview' ).empty();
				$( '#mbs-cover-upload' ).text( __( 'Upload Cover', 'my-book-showroom' ) );
				$( this ).hide();
			} );
		}
	};

	$( function() {
		MBS.BookCover.init();
	} );

} )( window.MBS = window.MBS || {}, jQuery );
