/**
 * Recording Thumbnail Uploader
 *
 * Handles custom thumbnail uploads for Zoom recording files using WordPress Media Library.
 *
 * @package SOVLIX\MHUB
 * @since   1.0.0
 */

(function($) {
	'use strict';

	/**
	 * Recording Thumbnail Uploader Object
	 */
	const RecordingThumbnailUploader = {
		/**
		 * Initialize the uploader
		 */
		init: function() {
			this.bindEvents();
		},

		/**
		 * Bind event handlers
		 */
		bindEvents: function() {
			$(document).on('click', '.mhub-upload-thumbnail-btn', this.openMediaUploader.bind(this));
			$(document).on('click', '.mhub-remove-thumbnail-btn', this.removeThumbnail.bind(this));
		},

		/**
		 * Open WordPress media uploader
		 *
		 * @param {Event} e Click event
		 */
		openMediaUploader: function(e) {
			e.preventDefault();

			const $button = $(e.currentTarget);
			const postId = $button.data('post-id');
			const fileId = $button.data('file-id');

			// Create WordPress media frame
			const frame = wp.media({
				title: mhubThumbnailUploader.i18n.selectImage,
				button: {
					text: mhubThumbnailUploader.i18n.useImage
				},
				multiple: false,
				library: {
					type: 'image'
				}
			});

			// Handle image selection
			frame.on('select', function() {
				const attachment = frame.state().get('selection').first().toJSON();
				RecordingThumbnailUploader.saveThumbnail(postId, fileId, attachment.url, $button);
			});

			frame.open();
		},

		/**
		 * Save thumbnail via AJAX
		 *
		 * @param {number} postId WordPress post ID
		 * @param {string} fileId Recording file ID
		 * @param {string} imageUrl Selected image URL
		 * @param {jQuery} $button Button element
		 */
		saveThumbnail: function(postId, fileId, imageUrl, $button) {
			// Show loading state
			$button.prop('disabled', true).addClass('loading');

			$.ajax({
				url: mhubThumbnailUploader.ajaxUrl,
				type: 'POST',
				data: {
					action: 'mhub_upload_thumbnail',
					nonce: mhubThumbnailUploader.nonce,
					post_id: postId,
					file_id: fileId,
					image_url: imageUrl
				},
				success: function(response) {
					if (response.success) {
						RecordingThumbnailUploader.updateUI(postId, fileId, imageUrl, $button);
						RecordingThumbnailUploader.showMessage('success', response.data.message);
					} else {
						const errorMessage = response.data && response.data.message 
							? response.data.message 
							: mhubThumbnailUploader.i18n.uploadError;
						RecordingThumbnailUploader.showMessage('error', errorMessage);
					}
				},
				error: function() {
					RecordingThumbnailUploader.showMessage('error', mhubThumbnailUploader.i18n.uploadError);
				},
				complete: function() {
					$button.prop('disabled', false).removeClass('loading');
				}
			});
		},

		/**
		 * Remove thumbnail via AJAX
		 *
		 * @param {Event} e Click event
		 */
		removeThumbnail: function(e) {
			e.preventDefault();

			const $button = $(e.currentTarget);
			const postId = $button.data('post-id');
			const fileId = $button.data('file-id');

			// Show confirmation dialog
			if (!confirm(mhubThumbnailUploader.i18n.confirmRemove)) {
				return;
			}

			// Show loading state
			$button.prop('disabled', true).addClass('loading');

			$.ajax({
				url: mhubThumbnailUploader.ajaxUrl,
				type: 'POST',
				data: {
					action: 'mhub_remove_thumbnail',
					nonce: mhubThumbnailUploader.nonce,
					post_id: postId,
					file_id: fileId
				},
				success: function(response) {
					if (response.success) {
						// Reload page to show fallback thumbnail
						location.reload();
					} else {
						const errorMessage = response.data && response.data.message 
							? response.data.message 
							: mhubThumbnailUploader.i18n.removeError;
						RecordingThumbnailUploader.showMessage('error', errorMessage);
						$button.prop('disabled', false).removeClass('loading');
					}
				},
				error: function() {
					RecordingThumbnailUploader.showMessage('error', mhubThumbnailUploader.i18n.removeError);
					$button.prop('disabled', false).removeClass('loading');
				}
			});
		},

		/**
		 * Update UI after successful upload
		 *
		 * @param {number} postId WordPress post ID
		 * @param {string} fileId Recording file ID
		 * @param {string} imageUrl New thumbnail URL
		 * @param {jQuery} $button Button element
		 */
		updateUI: function(postId, fileId, imageUrl, $button) {
			// Add cache buster to force image reload
			const cacheBuster = '?t=' + new Date().getTime();
			const imageUrlWithCache = imageUrl + cacheBuster;
			
			// Find the card wrapper
			const $wrapper = $button.closest('.mhub-recording-card-wrapper');
			
			// Update thumbnail image in the current card
			const $img = $wrapper.find('.mhub-recording-thumbnail img, img');
			if ($img.length) {
				$img.attr('src', imageUrlWithCache);
			}

			// Method 1: Update by data-file-id attribute
			$('[data-file-id="' + fileId + '"]').each(function() {
				const $element = $(this);
				
				// Update image if it's an img tag
				if ($element.is('img')) {
					$element.attr('src', imageUrlWithCache);
				}
				
				// Update image inside the element
				const $innerImg = $element.find('img');
				if ($innerImg.length) {
					$innerImg.attr('src', imageUrlWithCache);
				}
			});

			// Method 2: Update ALL images in the recording archive that might be this thumbnail
			// This is more aggressive and catches featured player and sidebar
			$('.mhub-recording-archive img, .mhub-recording-lightbox img, .mhub-sidebar-thumbnail, .mhub-recording-thumbnail img').each(function() {
				const $this = $(this);
				const thisSrc = $this.attr('src');
				
				// Check if this image matches by comparing base URL (without query params)
				if (thisSrc) {
					const thisBaseUrl = thisSrc.split('?')[0];
					const newBaseUrl = imageUrl.split('?')[0];
					
					if (thisBaseUrl === newBaseUrl) {
						$this.attr('src', imageUrlWithCache);
					}
				}
			});

			// Method 3: Update featured/main player thumbnail specifically
			$('.mhub-recording-lightbox-video img').each(function() {
				const $this = $(this);
				const thisSrc = $this.attr('src');
				if (thisSrc && thisSrc.split('?')[0] === imageUrl.split('?')[0]) {
					$this.attr('src', imageUrlWithCache);
				}
			});
			
			// Method 4: Update sidebar thumbnails by post ID
			// Find sidebar items and check if they link to this post
			$('.mhub-sidebar-item').each(function() {
				const $item = $(this);
				const $link = $item.find('.mhub-sidebar-link');
				if ($link.length) {
					const href = $link.attr('href');
					// Check if this sidebar item is for the current post
					if (href && (href.includes('p=' + postId) || href.includes('/' + postId + '/') || href.endsWith('/' + postId))) {
						const $sidebarImg = $item.find('img');
						if ($sidebarImg.length) {
							$sidebarImg.attr('src', imageUrlWithCache);
						}
					}
				}
			});
			
			// Method 5: Update new videos section thumbnails
			$('.mhub-new-video-thumbnail img').each(function() {
				const $this = $(this);
				const thisSrc = $this.attr('src');
				if (thisSrc && thisSrc.split('?')[0] === imageUrl.split('?')[0]) {
					$this.attr('src', imageUrlWithCache);
				}
			});

			// Update button state
			const $container = $button.closest('.mhub-thumbnail-controls');
			$container.addClass('has-custom-thumbnail');
			$button.text(mhubThumbnailUploader.i18n.changeThumbnail);

			// Add remove button if it doesn't exist
			if (!$container.find('.mhub-remove-thumbnail-btn').length) {
				const $removeBtn = $('<button>')
					.attr('type', 'button')
					.addClass('mhub-remove-thumbnail-btn')
					.attr('data-post-id', postId)
					.attr('data-file-id', fileId)
					.text(mhubThumbnailUploader.i18n.removeCustomThumbnail);
				
				$button.after($removeBtn);
			}
		},

		/**
		 * Show notification message
		 *
		 * @param {string} type Message type ('success' or 'error')
		 * @param {string} message Message text
		 */
		showMessage: function(type, message) {
			// Remove any existing notices
			$('.mhub-thumbnail-notice').remove();

			// Create and show notification
			const $notice = $('<div>')
				.addClass('mhub-thumbnail-notice mhub-thumbnail-notice-' + type)
				.text(message)
				.appendTo('body')
				.hide()
				.fadeIn(300);

			// Auto-hide success messages after 3 seconds
			if (type === 'success') {
				setTimeout(function() {
					$notice.fadeOut(300, function() {
						$(this).remove();
					});
				}, 3000);
			} else {
				// Add close button for error messages
				const $closeBtn = $('<button>')
					.addClass('mhub-thumbnail-notice-close')
					.html('&times;')
					.attr('aria-label', 'Close')
					.on('click', function() {
						$notice.fadeOut(300, function() {
							$(this).remove();
						});
					});
				
				$notice.append($closeBtn);
			}
		}
	};

	// Initialize on document ready
	$(document).ready(function() {
		// Only initialize if wp.media is available
		if (typeof wp !== 'undefined' && typeof wp.media !== 'undefined') {
			RecordingThumbnailUploader.init();
		}
	});

})(jQuery);
