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

	// Uploading files
	var file_frame, series_img_frame;

	/**
	 * Format bytes to human-readable format matching PHP format_bytes function
	 *
	 * @param {number} size File size in bytes
	 * @param {number} precision Number of decimal places (default: 2)
	 * @return {string|false} Formatted file size or false on failure
	 */
	function formatBytes( size, precision ) {
		precision = precision || 2;
		if ( ! size ) {
			return false;
		}

		var base = Math.log( size ) / Math.log( 1024 );
		var suffixes = [ '', 'k', 'M', 'G', 'T' ];
		var value = Math.pow( 1024, base - Math.floor( base ) );
		var roundedValue = Math.round( value * Math.pow( 10, precision ) ) / Math.pow( 10, precision );
		var formattedSize = roundedValue + suffixes[ Math.floor( base ) ];

		return formattedSize;
	}

	/**
	 * Normalize duration string to SSP format (H:i:s with hours always included).
	 * WordPress Media Library may provide "0:28" (no hours), but SSP uses "00:00:28" format.
	 * If duration already has 3 parts, it's already in the correct format.
	 *
	 * @param {string} duration Duration string (e.g., "0:28" or "00:42:17")
	 * @return {string} Normalized duration in H:i:s format (e.g., "00:00:28")
	 */
	function normalizeDurationToSspFormat( duration ) {
		if ( ! duration || typeof duration !== 'string' ) {
			return '';
		}

		// Parse the duration string
		var parts = duration.split(':');

		if ( parts.length !== 2 ) {
			// This is either H:MM:SS or unknown format - return as-is
			return duration;
		}

		// Format: "M:SS" - add hours as "00" to match SSP format
		var minutes = parseInt( parts[0], 10 );
		var seconds = parseInt( parts[1], 10 );
		var pad = function( num ) {
			return num.toString().padStart( 2, '0' );
		};
		return '00:' + pad( minutes ) + ':' + pad( seconds );
	}

	/**
	 * Populate filesize, duration, and date recorded fields from a media attachment.
	 *
	 * @param {Object} attachment Media attachment object from wp.media (toJSON()).
	 */
	function populateAudioMetaFromAttachment( attachment ) {
		// File size
		if ( attachment.filesizeInBytes ) {
			$( '#filesize_raw' ).val( attachment.filesizeInBytes.toString() ).trigger( 'change' );
			var formattedSize = formatBytes( attachment.filesizeInBytes );
			if ( formattedSize ) {
				$( '#filesize' ).val( formattedSize ).trigger( 'change' );
			}
		}

		// Duration
		if ( attachment.fileLength ) {
			var normalizedDuration = normalizeDurationToSspFormat( attachment.fileLength );
			if ( normalizedDuration ) {
				$( '#duration' ).val( normalizedDuration ).trigger( 'change' );
			}
		}

		// Date recorded
		var $dateRecorded = $( '#date_recorded' );
		if ( $dateRecorded.length ) {
			var attachmentDate = attachment.date ? new Date( attachment.date ) : new Date();
			var year = attachmentDate.getFullYear();
			var month = String( attachmentDate.getMonth() + 1 ).padStart( 2, '0' );
			var day = String( attachmentDate.getDate() ).padStart( 2, '0' );
			var hours = String( attachmentDate.getHours() ).padStart( 2, '0' );
			var minutes = String( attachmentDate.getMinutes() ).padStart( 2, '0' );
			var seconds = String( attachmentDate.getSeconds() ).padStart( 2, '0' );
			var isoDatetime = year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds;
			$dateRecorded.val( isoDatetime ).trigger( 'change' );

			// Update datepicker display field
			var $dateRecordedDisplay = $( '#date_recorded_display' );
			if ( $dateRecordedDisplay.length ) {
				var display = attachmentDate.toLocaleDateString( undefined, { day: 'numeric', month: 'long', year: 'numeric' } );
				$dateRecordedDisplay.val( display );
			}

			// Update time input
			var $dateRecordedTime = $( '#date_recorded_time' );
			if ( $dateRecordedTime.length ) {
				$dateRecordedTime.val( hours + ':' + minutes );
			}
		}
	}

	$.fn.ssp_upload_media_file = function( button, validateCallback = null ) {
		//var button_id = button.attr('id');
		var field_class = button.data( 'field' );
		var preview_class = button.data( 'preview' );

		// Create the media frame.
		file_frame = wp.media.frames.file_frame = wp.media({
		  title: $( this ).data( 'uploader_title' ),
		  button: {
		    text: $( this ).data( 'uploader_button_text' ),
		  },
		  multiple: false
		});

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

			if ( typeof validateCallback === 'function' && ! validateCallback(attachment) ) {
				return;
			}

			$('input.' + field_class).val(attachment.url).trigger('change');
			if ( preview_class ) {	
				$('.' + preview_class).attr('src', attachment.url);
			}

			// Extract file size and duration from Media Library metadata for audio_file field
			if ( field_class === 'ssp-field-audio_file' ) {
				populateAudioMetaFromAttachment( attachment );
			}
		});

		// Finally, open the modal
		file_frame.open();
	};

  /* Add/Edit Series Image */
	$('#series_upload_image_button').on('click', function( event ){
		event.preventDefault();
		var send_attachment_bkp = wp.media.editor.send.attachment;
    var button = $(this);
		var button_id = button.attr('id');
		var preview_id = button_id.replace( '_upload', '' ).replace( '_button', '_preview' );
		var field_id = button_id.replace( '_upload', '' ).replace( '_button', '_id' );

		// If the media frame already exists, reopen it.
		if ( series_img_frame ) {
		  series_img_frame.open();
		  return;
		}

		// Create the media frame.
		series_img_frame = wp.media({
			title: $( this ).data( 'uploader_title' ),
		  button: {
		    text: $( this ).data( 'uploader_button_text' ),
		  },
			library: {
				type: [ 'image' ]
    	},
		  multiple: false
		});

		series_img_frame.on( 'select', function() {
      // Get media attachment details from the frame state
      var attachment = series_img_frame.state().get('selection').first().toJSON();

      // Send the attachment URL to our custom image input field.
      $('#' + preview_id).attr('src', attachment.url);

      // Send the attachment id to our hidden input
      $('#' + field_id).val(attachment.id);
		});

    // Finally, open the modal on click
    series_img_frame.open();
	});

	/* Remove/clear Series Image */
	$('#series_remove_image_button').on('click', function( event ){
		event.preventDefault();
		var button = $(this);
		var button_id = button.attr('id');
		var preview_id = button_id.replace( '_remove', '' ).replace( '_button', '_preview' );
		var field_id = button_id.replace( '_remove', '' ).replace( '_button', '_id' );

		if ( confirm('Are you sure?') ) {
        var src = $('#' + preview_id).attr('data-src');
        $('#' + preview_id).attr('src', src);
        $('#' + field_id).val('');
    }
	});

	/* ADD/EDIT EPISODE */
	$('body').on('click', '.ssp-upload-file', function( event ){
		event.preventDefault();
		$.fn.ssp_upload_media_file( $(this) );
	});

	$('#episode_embed_code').on('click', function() {
		$(this).select();
	});

	$( '.episode_embed_code_size_option' ).on('change', function() {

		var width = $( '#episode_embed_code_width' ).val();
		var height = $( '#episode_embed_code_height' ).val();
		var post_id = $( '#post_ID' ).val();

		$.post(
		    ajaxurl,
		    {
		        'action': 'update_episode_embed_code',
		        'nonce': ssp_admin.nonce,
		        'width': width,
		        'height': height,
		        'post_id': post_id,
		    },
		    function( response ){
		        if( response && response.success ) {
		        	$( '#episode_embed_code' ).val( response.data );
		        	$( '#episode_embed_code' ).select();
		        }
		    }
		);
	});

	/* DATEPICKER + TIME */

	/**
	 * Combine date and time inputs into the hidden storage field.
	 *
	 * @param {jQuery} $datepickerDisplay The visible datepicker text input.
	 */
	function updateDatetimeHiddenField( $datepickerDisplay ) {
		var save_field = $datepickerDisplay.attr( 'id' ).replace( '_display', '' );
		var $hidden    = $( '#' + save_field );
		var $time      = $( '#' + save_field + '_time' );
		var dateText   = $datepickerDisplay.val();

		if ( ! dateText ) {
			$hidden.val( '' ).trigger( 'change' );
			return;
		}

		var d    = $.datepicker.parseDate( 'd MM, yy', dateText );
		var date = $.datepicker.formatDate( 'yy-mm-dd', d );
		var time = $time.length && $time.val() ? $time.val() + ':00' : '00:00:00';

		$hidden.val( date + ' ' + time ).trigger( 'change' );
	}

	$('.ssp-datepicker').datepicker({
		changeMonth: true,
		changeYear: true,
		showAnim: 'slideDown',
		dateFormat: 'd MM, yy',
		onClose: function () {
			updateDatetimeHiddenField( $( this ) );
		}
	});

	$('.ssp-datepicker').change( function () {
		updateDatetimeHiddenField( $( this ) );
	});

	$('.ssp-timepicker').on( 'change', function () {
		var save_field_id = $( this ).attr( 'id' ).replace( '_time', '' );
		var $datepickerDisplay = $( '#' + save_field_id + '_display' );
		updateDatetimeHiddenField( $datepickerDisplay );
	});

	/* SETTINGS PAGE */

	$('#feed-series-toggle').on('click', function(e) {

		if ( $(this).hasClass( 'series-open' ) ) {
			$('#feed-series-list').slideUp('fast');
			$(this).removeClass( 'series-open' );
			$(this).addClass( 'series-closed' );

		} else if ( $(this).hasClass( 'series-closed' ) ) {
			$('#feed-series-list').slideDown('fast');
			$(this).removeClass( 'series-closed' );
			$(this).addClass( 'series-open' );

		}

	});

	$('#ss_podcasting_data_image_delete').on('click', function() {
		$( '#ss_podcasting_data_image' ).val( '' );
		$( '#ss_podcasting_data_image_preview' ).attr('src', '');
		return false;
	});

	$('#cover_image_button, #ss_podcasting_data_image_button').on('click', function (e) {
		var coverImgValidator = function (attachment) {
				return attachment.width === attachment.height && attachment.width >= 300;
			},
			feedImgValidator = function (attachment) {
				var minWidth = 1400,
					maxWidth = 3000;
				return attachment.width >= minWidth &&
					attachment.width <= maxWidth &&
					attachment.height === attachment.width;
			},
			validateImage = 'cover_image' === $(e.target).data('validator') ? coverImgValidator : feedImgValidator,
			description = $(this).parent().find('.description'),
			$img = 'cover_image_button' === $(e.target).prop('id') ? $('#cover_image_id') : $('#ss_podcasting_data_image_preview');


		$.fn.ssp_upload_media_file($(this), validateImage);

		description.css('color', '');

		file_frame.on('select', function () {
			var attachment = file_frame.state().get('selection').first().toJSON();
			if (validateImage(attachment)) {
				$img.val(attachment.id);
			} else {
				description.css('color', 'red');
			}
		});
	});

	$('.ssp-image-delete').on('click', function(){
		$('.' + $(this).data('field')).val('').trigger('change');
		$('.' + $(this).data('field') + '_id').val('').trigger('change');
		$('.' + $(this).data('preview')).attr('src', '').trigger('change');
	});

	$('.js-ssp-select2').select2({ width: '100%' });

	/**
	* Provides possibility to dynamically change the dynamo URL when the episode title or episode podcast is changed.
	* */
	var initDynamoBtn = function () {
		// Make sure it's an episode page and dynamo btn exists
		var $dynamo = $('.ssp-dynamo');
		if (!$dynamo.length) {
			return;
		}

		var $link = $dynamo.find('a'),
			href = $link.attr('href'),
			url = new URL(href),
			changeUrlArg = function (arg, value) {
				url.searchParams.set(arg, value);
				url.search = url.searchParams.toString();
				$link.attr('href', url.toString());
			}

		$(document).on('keyup', '.wp-block-post-title', function (e) {
			var title = $(e.target).text();

			if (title) {
				changeUrlArg('t', title);
			}
		});

		$(document).on('change', '.editor-post-taxonomies__hierarchical-terms-list', function (e) {
			var $target = $(e.target),
				$parent = $target.closest('.editor-post-taxonomies__hierarchical-terms-list');
			if ('Podcasts' !== $parent.attr('aria-label')) {
				return;
			}

			var subtitle = $parent.find('input:checked').first().closest('div').find('label').text();

			if (!subtitle) {
				subtitle = $dynamo.data('default-podcast-title');
			}

			changeUrlArg('s', subtitle.replace(" (default)", ""))
		});
	}

	var initNotifications = function () {
		$('.notice.is-constant').on( 'click', '.notice-dismiss', function () {
			var $notice = $(this).closest('.notice'),
				data = {
					'action': 'remove_constant_notice',
					'id': $notice.data('id'),
					'nonce': $notice.data('nonce'),
				};

			$.post(ajaxurl, data);
		});
	};

	var initSSPControls = function () {
		$('.js-open-ssp-controls').on('click', function () {
			$('.ssp-open').trigger('click');
		});

		// Send changed event to Gutenberg
		$('.ssp-sync').on('change', function () {
			var value = $(this).val();
			value = 'checkbox' === $(this).attr('type') && ! $(this).is(':checked')  ? '' : value;
			document.dispatchEvent(new CustomEvent('changedSSPField', {
				'detail': { field: $(this).prop('name'), value: value }
			}));
		});

		// Listen changed event from Gutenberg
		document.addEventListener('changedSSPGutField', function ( event ) {
			var data = event.detail;

			$('input.ssp-sync[type="text"][name="' + data.field + '"]').val(data.value);
			$('input.ssp-sync[type="number"][name="' + data.field + '"]').val(data.value);
			$('input.ssp-sync[type="hidden"][name="' + data.field + '"]').val(data.value);
			$('input.ssp-sync[type="time"][name="' + data.field + '"]').val(data.value);
			$('input.ssp-sync[type="radio"][name="' + data.field + '"][value="' + data.value + '"]').prop('checked', true);
			$('select.ssp-sync[name="' + data.field + '"] option[value="' + data.value + '"]').prop('selected', true);
			$('input.ssp-sync[type="checkbox"][name="' + data.field + '"]').prop('checked', 'on' === data.value);
			$('img.ssp-sync.ssp-preview-' + data.field).prop('src', data.value);
		});
	};

	initDynamoBtn();
	initNotifications();
	initSSPControls();
});
