/**
 * Technicalistic — Portfolio Thumbnails meta box.
 * Opens the WordPress media library, lets the editor pick up to N
 * images, and stores their attachment IDs in a hidden CSV input.
 */
( function ( $ ) {
	'use strict';

	$( function () {
		var $list  = $( '#jb-portfolio-thumbs-list' );
		var $input = $( '#jb-portfolio-thumbs-ids' );
		var $btn   = $( '#jb-portfolio-thumbs-add' );

		if ( ! $list.length || ! $input.length || ! $btn.length ) {
			return;
		}

		var cfg = window.TechnicalisticThumbs || {};
		var max = parseInt( cfg.max, 10 ) || 3;

		function syncInput() {
			var ids = $list.find( '.jb-thumb' ).map( function () {
				return $( this ).data( 'id' );
			} ).get();
			$input.val( ids.join( ',' ) );
		}

		function addThumb( id, url ) {
			if ( $list.find( '.jb-thumb[data-id="' + id + '"]' ).length ) {
				return;
			}
			if ( $list.find( '.jb-thumb' ).length >= max ) {
				return;
			}
			var $thumb = $(
				'<div class="jb-thumb" data-id="' + id + '">' +
					'<img src="' + url + '" alt="" />' +
					'<button type="button" class="jb-thumb-remove" aria-label="' +
						( cfg.removeLabel || 'Remove' ) +
					'">&times;</button>' +
				'</div>'
			);
			$list.append( $thumb );
		}

		$list.on( 'click', '.jb-thumb-remove', function ( e ) {
			e.preventDefault();
			$( this ).closest( '.jb-thumb' ).remove();
			syncInput();
		} );

		// Drag-to-reorder via simple swap on adjacent click — keep it light;
		// users can also just remove + reselect to reorder.

		var frame;
		$btn.on( 'click', function ( e ) {
			e.preventDefault();

			if ( frame ) {
				frame.open();
				return;
			}

			frame = wp.media( {
				title: cfg.title || 'Select portfolio thumbnails',
				button: { text: cfg.buttonText || 'Use these images' },
				library: { type: 'image' },
				multiple: 'add'
			} );

			frame.on( 'select', function () {
				var selection = frame.state().get( 'selection' );
				selection.each( function ( attachment ) {
					var a    = attachment.toJSON();
					var size = a.sizes && a.sizes.thumbnail ? a.sizes.thumbnail.url : a.url;
					addThumb( a.id, size );
				} );
				syncInput();
			} );

			frame.open();
		} );
	} );
} )( jQuery );
