/**
 * Events Frontend JavaScript
 *
 * Handles event registration modal and AJAX submission
 *
 * @package    Karate_Club_Manager
 * @subpackage Karate_Club_Manager/assets/js
 * @since      1.0.73
 */

(function($) {
	'use strict';

	let selectedEventId = null;

	$(document).ready(function() {
		// Handle "Attend the Event" button click
		$('.kcm-event-attend-btn').on('click', function(e) {
			e.preventDefault();

			selectedEventId = $(this).data('event-id');

			// Get already-registered member IDs for this event.
			var registeredIds = [];
			if (macmEvents.registrations && macmEvents.registrations[selectedEventId]) {
				registeredIds = macmEvents.registrations[selectedEventId];
			}

			// Reset all checkboxes first.
			$('input[name="selected_members[]"]').each(function() {
				var $checkbox = $(this);
				var memberId = $checkbox.val();
				var $option = $checkbox.closest('.kcm-member-option');

				// Skip archived members (already disabled by PHP).
				if ($option.hasClass('kcm-member-archived')) {
					return;
				}

				if (registeredIds.indexOf(memberId) !== -1) {
					// Already registered: check and disable.
					$checkbox.prop('checked', true).prop('disabled', true);
					$option.addClass('kcm-member-registered');
					$option.find('.kcm-member-registered-notice').show();
				} else {
					// Not registered: uncheck and enable.
					$checkbox.prop('checked', false).prop('disabled', false);
					$option.removeClass('kcm-member-registered');
					$option.find('.kcm-member-registered-notice').hide();
				}
			});

			// Enable confirm button only if there are non-disabled unchecked members available.
			updateConfirmButton();

			// Show modal
			$('#kcm-member-modal').fadeIn(300);

			// Hide any previous messages
			$('#kcm-events-message').hide();
		});

		// Handle modal close button
		$('.kcm-modal-close, .kcm-modal-cancel, .kcm-modal-overlay').on('click', function(e) {
			e.preventDefault();
			closeModal();
		});

		// Handle member selection
		$('input[name="selected_members[]"]').on('change', function() {
			updateConfirmButton();
		});

		// Handle registration confirmation
		$('.kcm-modal-confirm').on('click', function(e) {
			e.preventDefault();

			const selectedMemberIds = $('input[name="selected_members[]"]:checked:not(:disabled)').map(function() {
				return $(this).val();
			}).get();

			if (selectedMemberIds.length === 0) {
				showMessage('error', 'Please select at least one member.');
				return;
			}

			// Disable button during submission
			const $btn = $(this);
			const originalText = $btn.text();
			$btn.prop('disabled', true).text('Registering...');

			// Submit via AJAX
			$.ajax({
				url: macmEvents.ajaxurl,
				type: 'POST',
				data: {
					action: 'macm_register_to_event',
					nonce: macmEvents.nonce,
					event_id: selectedEventId,
					member_ids: selectedMemberIds
				},
				success: function(response) {
					if (response.success) {
						showMessage('success', response.data.message);
						closeModal();

						// Reload page after a short delay to show updated registration status
						setTimeout(function() {
							location.reload();
						}, 1500);
					} else {
						// Close modal first so error message is visible
						closeModal();
						showMessage('error', response.data.message);
						$btn.prop('disabled', false).text(originalText);
					}
				},
				error: function(xhr, status, error) {
					closeModal();
					showMessage('error', 'An error occurred. Please try again.');
					$btn.prop('disabled', false).text(originalText);
					console.error('AJAX error:', error);
				}
			});
		});

		// Close modal on escape key
		$(document).on('keydown', function(e) {
			if (e.key === 'Escape' && $('#kcm-member-modal').is(':visible')) {
				closeModal();
			}
		});
	});

	/**
	 * Update confirm button state.
	 * Only enable if at least one non-disabled checkbox is checked.
	 */
	function updateConfirmButton() {
		var anyNewChecked = $('input[name="selected_members[]"]:checked:not(:disabled)').length > 0;
		$('.kcm-modal-confirm').prop('disabled', !anyNewChecked);
	}

	/**
	 * Close modal
	 */
	function closeModal() {
		$('#kcm-member-modal').fadeOut(300);
		selectedEventId = null;
	}

	/**
	 * Show message
	 *
	 * @param {string} type - 'success' or 'error'
	 * @param {string} message - Message text
	 */
	function showMessage(type, message) {
		const $messageBox = $('#kcm-events-message');
		$messageBox
			.removeClass('success error')
			.addClass(type)
			.html(message)
			.fadeIn(300);

		// Scroll to message
		$('html, body').animate({
			scrollTop: $messageBox.offset().top - 100
		}, 300);

		// Auto-hide success messages after 5 seconds
		if (type === 'success') {
			setTimeout(function() {
				$messageBox.fadeOut(300);
			}, 5000);
		}
	}

})(jQuery);
