/**
 * Widget admin scripts for ShopBar theme.
 *
 * @package shopbar
 */

jQuery(document).ready(function($) {

	// ── Generic repeater (Announcement Bar: info / links / social) ──

	/**
	 * Re-index the items inside a repeater so the field-name array keys
	 * are sequential (0,1,2,...) after add/remove.
	 *
	 * @param {jQuery} $rep The repeater wrapper element.
	 */
	function shopbarReindexRepeater( $rep ) {
		var group = $rep.data( 'repeater' );
		$rep.find( '.shopbar-repeater-item' ).each( function( idx ) {
			$( this ).find( 'input, select' ).each( function() {
				var name = $( this ).attr( 'name' );
				if ( ! name ) {
					return;
				}
				var pattern = new RegExp( '\\[' + group + '\\]\\[\\d+\\]' );
				$( this ).attr( 'name', name.replace( pattern, '[' + group + '][' + idx + ']' ) );
			} );
		} );
	}

	// Add repeater item (clones the last row and clears it).
	$( document ).on( 'click', '.shopbar-repeater-add', function( e ) {
		e.preventDefault();
		var $rep   = $( this ).closest( '.shopbar-repeater' );
		var $items = $rep.find( '.shopbar-repeater-items' );
		var $last  = $items.find( '.shopbar-repeater-item' ).last();

		if ( ! $last.length ) {
			return;
		}

		var $clone = $last.clone();
		$clone.find( 'input' ).val( '' );
		$clone.find( 'select' ).each( function() {
			this.selectedIndex = 0;
		} );
		$items.append( $clone );
		shopbarReindexRepeater( $rep );
	} );

	// Remove repeater item (keeps at least one row).
	$( document ).on( 'click', '.shopbar-repeater-remove', function( e ) {
		e.preventDefault();
		var $rep   = $( this ).closest( '.shopbar-repeater' );
		var $item  = $( this ).closest( '.shopbar-repeater-item' );

		if ( $rep.find( '.shopbar-repeater-item' ).length > 1 ) {
			$item.fadeOut( 180, function() {
				$( this ).remove();
				shopbarReindexRepeater( $rep );
			} );
		} else {
			$item.find( 'input' ).val( '' );
			$item.find( 'select' ).each( function() {
				this.selectedIndex = 0;
			} );
		}
	} );

	// ── Footer About Widget ──

	// Logo upload.
	$( document ).on( 'click', '.shopbar-logo-upload', function( e ) {
		e.preventDefault();
		var button = $( this );
		var frame = wp.media( {
			title: 'Select Footer Logo',
			button: { text: 'Use as Logo' },
			multiple: false
		} );
		frame.on( 'select', function() {
			var attachment = frame.state().get( 'selection' ).first().toJSON();
			button.siblings( '.shopbar-logo-id' ).val( attachment.id );
			button.siblings( '.shopbar-logo-preview' ).html( '<img src="' + attachment.url + '" style="max-width:100%;height:auto;border:1px solid #ddd;border-radius:4px;padding:4px;">' ).show();
			button.siblings( '.shopbar-logo-remove' ).show();
		} );
		frame.open();
	} );

	// Logo remove.
	$( document ).on( 'click', '.shopbar-logo-remove', function( e ) {
		e.preventDefault();
		var button = $( this );
		button.siblings( '.shopbar-logo-id' ).val( '' );
		button.siblings( '.shopbar-logo-preview' ).hide();
		button.hide();
	} );
} );
