/**
 * Recording Thumbnail Uploader
 *
 * Handles custom thumbnail uploads for Zoom recording files using WordPress Media Library.
 *
 * @package SOVLIX\ZMEET
 * @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', '.zmeet-upload-thumbnail-btn', this.openMediaUploader.bind(this));
			$(document).on('click', '.zmeet-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: zmeetThumbnailUploader.i18n.selectImage,
				button: {
					text: zmeetThumbnailUploader.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: zmeetThumbnailUploader.ajaxUrl,
				type: 'POST',
				data: {
					action: 'zmeet_upload_thumbnail',
					nonce: zmeetThumbnailUploader.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 
							: zmeetThumbnailUploader.i18n.uploadError;
						RecordingThumbnailUploader.showMessage('error', errorMessage);
					}
				},
				error: function() {
					RecordingThumbnailUploader.showMessage('error', zmeetThumbnailUploader.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(zmeetThumbnailUploader.i18n.confirmRemove)) {
				return;
			}

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

			$.ajax({
				url: zmeetThumbnailUploader.ajaxUrl,
				type: 'POST',
				data: {
					action: 'zmeet_remove_thumbnail',
					nonce: zmeetThumbnailUploader.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 
							: zmeetThumbnailUploader.i18n.removeError;
						RecordingThumbnailUploader.showMessage('error', errorMessage);
						$button.prop('disabled', false).removeClass('loading');
					}
				},
				error: function() {
					RecordingThumbnailUploader.showMessage('error', zmeetThumbnailUploader.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('.zmeet-recording-card-wrapper');
			
			// Update thumbnail image in the current card
			const $img = $wrapper.find('.zmeet-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
			$('.zmeet-recording-archive img, .zmeet-recording-lightbox img, .zmeet-sidebar-thumbnail, .zmeet-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
			$('.zmeet-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
			$('.zmeet-sidebar-item').each(function() {
				const $item = $(this);
				const $link = $item.find('.zmeet-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
			$('.zmeet-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('.zmeet-thumbnail-controls');
			$container.addClass('has-custom-thumbnail');
			$button.text(zmeetThumbnailUploader.i18n.changeThumbnail);

			// Add remove button if it doesn't exist
			if (!$container.find('.zmeet-remove-thumbnail-btn').length) {
				const $removeBtn = $('<button>')
					.attr('type', 'button')
					.addClass('zmeet-remove-thumbnail-btn')
					.attr('data-post-id', postId)
					.attr('data-file-id', fileId)
					.text(zmeetThumbnailUploader.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
			$('.zmeet-thumbnail-notice').remove();

			// Create and show notification
			const $notice = $('<div>')
				.addClass('zmeet-thumbnail-notice zmeet-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('zmeet-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);
