/**
 * Odysseo — WordPress media picker for theme image fields.
 *
 * Single image: .odysseo-media-btn writes the chosen URL into the input named by
 * data-target and updates its preview; .odysseo-media-clear empties it.
 *
 * Gallery: a .odysseo-gallery-grid (data-target = a hidden textarea of one URL
 * per line) renders WordPress-style thumbnails. The matching .odysseo-media-btn
 * (data-multiple="1") adds images; each thumbnail has a remove button and the
 * grid is drag-sortable. The hidden textarea stays the source of truth on save.
 *
 * @package Odysseo
 */
( function ( $ ) {
	'use strict';

	function urlsOf( $field ) {
		var v = $.trim( $field.val() );
		if ( ! v ) {
			return [];
		}
		return v.split( /\r?\n/ ).map( function ( s ) { return $.trim( s ); } ).filter( function ( s ) { return s; } );
	}

	function renderGrid( $grid ) {
		var $field = $( '#' + $grid.data( 'target' ) );
		if ( ! $field.length ) {
			return;
		}
		var urls = urlsOf( $field );
		$grid.empty();
		if ( ! urls.length ) {
			$grid.append( '<span class="odysseo-gallery-empty">No images yet.</span>' );
			return;
		}
		urls.forEach( function ( u ) {
			var $item = $( '<div class="odysseo-gallery-item"></div>' );
			$item.append( $( '<img alt="">' ).attr( 'src', u ) );
			$item.append( '<button type="button" class="odysseo-gallery-remove" aria-label="Remove">×</button>' );
			$item.data( 'url', u );
			$grid.append( $item );
		} );
	}

	// Rebuild the hidden textarea from the current thumbnail order.
	function syncFromGrid( $grid ) {
		var $field = $( '#' + $grid.data( 'target' ) );
		var urls = [];
		$grid.children( '.odysseo-gallery-item' ).each( function () {
			urls.push( $( this ).data( 'url' ) );
		} );
		$field.val( urls.join( '\n' ) );
	}

	$( function () {
		$( '.odysseo-gallery-grid' ).each( function () {
			var $grid = $( this );
			renderGrid( $grid );
			if ( $.fn.sortable ) {
				$grid.sortable( {
					items: '> .odysseo-gallery-item',
					stop: function () { syncFromGrid( $grid ); }
				} );
			}
		} );
	} );

	// Media frame: single image or multi-image gallery add.
	$( document ).on( 'click', '.odysseo-media-btn', function ( e ) {
		e.preventDefault();
		var $btn     = $( this );
		var target   = $btn.data( 'target' );
		var multiple = 1 === parseInt( $btn.data( 'multiple' ), 10 );
		var $field   = $( '#' + target );
		if ( ! $field.length || 'undefined' === typeof wp || ! wp.media ) {
			return;
		}
		var frame = wp.media( {
			title: $btn.data( 'title' ) || 'Select image',
			button: { text: 'Use image' },
			library: { type: 'image' },
			multiple: multiple
		} );
		frame.on( 'select', function () {
			var urls = frame.state().get( 'selection' ).map( function ( a ) { return a.toJSON().url; } );
			if ( multiple ) {
				var cur = urlsOf( $field );
				$field.val( cur.concat( urls ).join( '\n' ) );
				renderGrid( $( '.odysseo-gallery-grid[data-target="' + target + '"]' ) );
			} else {
				$field.val( urls[0] );
				var $prev = $( '#' + target + '_preview' );
				if ( $prev.length ) {
					$prev.attr( 'src', urls[0] ).show();
				}
			}
		} );
		frame.open();
	} );

	// Remove a single hero image.
	$( document ).on( 'click', '.odysseo-media-clear', function ( e ) {
		e.preventDefault();
		var target = $( this ).data( 'target' );
		$( '#' + target ).val( '' );
		$( '#' + target + '_preview' ).hide().attr( 'src', '' );
	} );

	// Remove one gallery thumbnail.
	$( document ).on( 'click', '.odysseo-gallery-remove', function ( e ) {
		e.preventDefault();
		var $grid = $( this ).closest( '.odysseo-gallery-grid' );
		$( this ).closest( '.odysseo-gallery-item' ).remove();
		syncFromGrid( $grid );
		if ( ! $grid.children( '.odysseo-gallery-item' ).length ) {
			renderGrid( $grid );
		}
	} );

	// Optional "Edit URLs" toggle to reveal the raw textarea.
	$( document ).on( 'click', '.odysseo-gallery-toggle', function ( e ) {
		e.preventDefault();
		$( '#' + $( this ).data( 'target' ) ).toggle();
	} );

} )( jQuery );
