/**
 * @file assets/js/mbs-media-uploader.js
 * wp.media modal handler for all .mbs-upload-button and video upload elements in the book editor.
 * @package MyBookShowroom
 * @since   1.0.0
 */

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

	var MBS_MediaUploader = {

		init: function() {
			// Use event delegation for dynamically added fields (e.g. format repeater)
			$( document ).on( 'click', '.mbs-upload-button', this.openMediaModal );
			$( document ).on( 'click', '.mbs-remove-button', this.removeImage );
			// Video upload / remove (spinning book video fallback + book trailer).
			$( document ).on( 'click', '.mbs-upload-video-btn', this.openVideoModal );
			$( document ).on( 'click', '.mbs-remove-video-btn', this.removeVideo );
		},

		openMediaModal: function( e ) {
			e.preventDefault();

			var $button = $( this );
			var fieldId = $button.data( 'field' );

			if ( ! fieldId ) {
				return;
			}

			var $hiddenInput = $( '#' + fieldId );
			var $previewContainer = $button.closest( '.mbs-media-uploader' ).find( '.mbs-media-preview' );

			// Create the media frame
			var mediaFrame = wp.media( {
				title:    __( 'Select Cover Image', 'my-book-showroom' ),
				button:   { text: __( 'Use this image', 'my-book-showroom' ) },
				multiple: false,
				library:  { type: 'image' }
			} );

			// When an image is selected
			mediaFrame.on( 'select', function() {
				var attachment = mediaFrame.state().get( 'selection' ).first().toJSON();

				// Update hidden input
				$hiddenInput.val( attachment.id );

				// Update preview
				var img = document.createElement( 'img' );
				img.src = attachment.url;
				img.alt = '';
				img.className = 'mbs-media-preview-img';
				$previewContainer.empty().append( img );
			} );

			// Open the modal
			mediaFrame.open();
		},

		removeImage: function( e ) {
			e.preventDefault();

			var $button = $( this );
			var fieldId = $button.data( 'field' );

			if ( ! fieldId ) {
				return;
			}

			var $hiddenInput = $( '#' + fieldId );
			var $previewContainer = $button.closest( '.mbs-media-uploader' ).find( '.mbs-media-preview' );

			// Clear hidden input and preview
			$hiddenInput.val( '' );
			$previewContainer.empty();
		},

		/**
		 * Open the WP media library filtered to video files.
		 * Used by .mbs-upload-video-btn buttons (spinning book video + book trailer).
		 * Operates on siblings inside the nearest .mbs-video-uploader wrapper.
		 */
		openVideoModal: function( e ) {
			e.preventDefault();

			var $button = $( this );
			var $wrap   = $button.closest( '.mbs-video-uploader' );

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

			mediaFrame.on( 'select', function() {
				var attachment = mediaFrame.state().get( 'selection' ).first().toJSON();

				$wrap.find( 'input[type="hidden"]' ).val( attachment.id );
				$wrap.find( '.mbs-video-filename' )
				     .text( attachment.title || attachment.filename )
				     .show();
				$button.text( __( 'Replace Video', 'my-book-showroom' ) );
				$wrap.find( '.mbs-remove-video-btn' ).show();
			} );

			mediaFrame.open();
		},

		/**
		 * Remove the selected video — clears the hidden input and resets the row UI.
		 * Used by .mbs-remove-video-btn buttons.
		 */
		removeVideo: function( e ) {
			e.preventDefault();

			var $button = $( this );
			var $wrap   = $button.closest( '.mbs-video-uploader' );

			$wrap.find( 'input[type="hidden"]' ).val( '' );
			$wrap.find( '.mbs-video-filename' ).text( '' ).hide();
			$wrap.find( '.mbs-upload-video-btn' ).text( __( 'Upload Video', 'my-book-showroom' ) );
			$button.hide();
		}
	};

	// Initialize when DOM is ready
	$( document ).ready( function() {
		MBS_MediaUploader.init();
	} );

})( jQuery );
