/**
 * @file assets/js/adminjs/mbs-admin-icon-picker.js
 * MBS.IconPicker — PRO custom icon media uploader for buy-link rows.
 *
 * Triggered by .mbs-change-icon-btn on a buy-link or reader-platform row.
 * Opens the WP media library (images only). On attachment selection:
 *   - Updates the hidden .mbs-buy-link-icon-id input.
 *   - Updates the .mbs-buy-link-icon-preview <img> src.
 *
 * Loaded on the Book Editor screen, PRO only.
 * Dependency: mbs-book-editor (ensures wp.media is loaded).
 * @package MyBookShowroom
 */

// =============================================================================
// Icon Picker (PRO)
// =============================================================================

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

	/**
	 * @namespace MBS.IconPicker
	 */
	MBS.IconPicker = {

		/**
		 * Cached wp.media frame instance.
		 * Reused across button clicks; destroyed and re-created if $activeRow changes.
		 * @type {wp.media.view.MediaFrame|null}
		 */
		_frame: null,

		/**
		 * The buy-link / platform row whose icon is being edited.
		 * @type {jQuery|null}
		 */
		_$activeRow: null,

		/**
		 * Bind click handler on .mbs-change-icon-btn (delegated from document).
		 * @returns {void}
		 */
		init: function() {
			$( document ).on( 'click', '.mbs-change-icon-btn', function( e ) {
				e.preventDefault();
				MBS.IconPicker._$activeRow = $( this ).closest( '.mbs-buy-link-row, .mbs-platform-row' );
				MBS.IconPicker.openFrame();
			} );
		},

		/**
		 * Open (or create) the wp.media frame.
		 * @returns {void}
		 */
		openFrame: function() {
			if ( ! MBS.IconPicker._frame ) {
				MBS.IconPicker._frame = wp.media( {
					title:    __( 'Select Icon', 'my-book-showroom' ),
					button:   { text: __( 'Use as Icon', 'my-book-showroom' ) },
					multiple: false,
					library:  { type: 'image' }
				} );
				MBS.IconPicker._frame.on( 'select', MBS.IconPicker.onSelect );
			}
			MBS.IconPicker._frame.open();
		},

		/**
		 * Handle attachment selection from the media library.
		 * Updates hidden ID input and icon preview image in the active row.
		 * @returns {void}
		 */
		onSelect: function() {
			var attachment = MBS.IconPicker._frame.state().get( 'selection' ).first().toJSON();
			var $row       = MBS.IconPicker._$activeRow;
			if ( ! $row || ! $row.length ) { return; }

			// Update hidden attachment-ID input.
			$row.find( '.mbs-buy-link-icon-id' ).val( attachment.id );

			// Update preview image — use thumbnail size if available, else full URL.
			var previewUrl = ( attachment.sizes && attachment.sizes.thumbnail )
				? attachment.sizes.thumbnail.url
				: attachment.url;

			var $wrap = $row.find( '.mbs-buy-link-icon-wrap' );
			var $img  = $wrap.find( '.mbs-buy-link-icon-preview' );
			if ( ! $img.length ) {
				$img = $( '<img>' ).attr( { width: 24, height: 24, alt: '' } ).addClass( 'mbs-buy-link-icon-preview' );
				$wrap.empty().append( $img );
			}
			$img.attr( 'src', previewUrl ).show();
			$wrap.find( '.mbs-buy-link-icon-placeholder' ).hide();
		}

	};

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

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