/**
 * PC Changelog Manager - Public JavaScript
 *
 * @package PCChangelogManager
 */

(function($) {
	'use strict';

	$(document).ready(function() {
		// Handle upvote button clicks
		$(document).on('click', '.pc-clm-upvote-btn', function(e) {
			e.preventDefault();
			
			var $button = $(this);
			var postId = $button.data('post-id');
			var $count = $button.find('.pc-clm-upvote-count');
			var $label = $button.siblings('.pc-clm-upvote-label');
			var originalCount = parseInt($count.text());
			
			// Prevent multiple clicks
			if ($button.prop('disabled')) {
				return;
			}
			
			$button.prop('disabled', true);
			
			// Show loading state
			$button.addClass('loading');
			
			// Make AJAX request
			$.ajax({
				url: pc_clm_ajax.ajax_url,
				type: 'POST',
				data: {
					action: 'pc_clm_upvote',
					post_id: postId,
					nonce: pc_clm_ajax.nonce
				},
				success: function(response) {
					if (response.success) {
						// Update the count
						$count.text(response.data.vote_count);
						
						// Update label
						var labelText = response.data.vote_count === 1 ? 'upvote' : 'upvotes';
						$label.text(labelText);
						
						// Mark as voted
						$button.addClass('voted');
						$button.prop('disabled', true);
						
						// Show success message (optional)
						showNotification(response.data.message, 'success');
					} else {
						// Show error message
						showNotification(response.data.message, 'error');
						// Re-enable button if not already voted
						if (!response.data.voted) {
							$button.prop('disabled', false);
						}
					}
				},
				error: function(xhr, status, error) {
					console.error('Upvote error:', error);
					showNotification('An error occurred. Please try again.', 'error');
					$button.prop('disabled', false);
				},
				complete: function() {
					$button.removeClass('loading');
				}
			});
		});
		
		// Helper function to show notifications
		function showNotification(message, type) {
			var $notification = $('<div class="pc-clm-notification pc-clm-notification-' + type + '">' + message + '</div>');
			
			// Add to page
			$('body').append($notification);
			
			// Show with animation
			setTimeout(function() {
				$notification.addClass('show');
			}, 100);
			
			// Auto hide after 3 seconds
			setTimeout(function() {
				$notification.removeClass('show');
				setTimeout(function() {
					$notification.remove();
				}, 300);
			}, 3000);
		}
		
		// Handle keyboard accessibility for upvote buttons
		$(document).on('keydown', '.pc-clm-upvote-btn', function(e) {
			if (e.key === 'Enter' || e.key === ' ') {
				e.preventDefault();
				$(this).click();
			}
		});
		
		// Add hover effects for upvote buttons
		$('.pc-clm-upvote-btn:not(.voted)').hover(
			function() {
				$(this).addClass('hover');
			},
			function() {
				$(this).removeClass('hover');
			}
		);
	});
	
})(jQuery);