/**
 * WooCommerce Customizations JavaScript
 *
 * Client-side validation and enhancements for dojo products
 *
 * @package Karate_Club_Manager
 * @since 1.0.0
 */

(function($) {
	'use strict';

	/**
	 * Dojo Product Handler
	 */
	var KCM_WooCommerce = {

		/**
		 * Initialize
		 */
		init: function() {
			this.memberSelectorValidation();
			this.preventEmptyMemberSubmission();
		},

		/**
		 * Member selector validation
		 */
		memberSelectorValidation: function() {
			var $memberSelect = $('#kcm_member_id');

			if ($memberSelect.length === 0) {
				return;
			}

			// Add error message container if it doesn't exist
			if ($memberSelect.next('.kcm-member-error').length === 0) {
				$memberSelect.after('<div class="kcm-member-error">Please select a member.</div>');
			}

			// Validate on change
			$memberSelect.on('change', function() {
				var $this = $(this);
				var $container = $this.closest('.kcm-member-selector');

				if ($this.val() === '') {
					$container.addClass('error');
				} else {
					$container.removeClass('error');
				}
			});
		},

		/**
		 * Prevent form submission if no member selected
		 */
		preventEmptyMemberSubmission: function() {
			var $form = $('form.cart');

			if ($form.length === 0) {
				return;
			}

			$form.on('submit', function(e) {
				var $memberSelect = $('#kcm_member_id');

				// If member selector exists (dojo product)
				if ($memberSelect.length > 0) {
					var memberValue = $memberSelect.val();
					var $container = $memberSelect.closest('.kcm-member-selector');

					// Check if member is selected
					if (!memberValue || memberValue === '') {
						e.preventDefault();

						// Show error
						$container.addClass('error');

						// Scroll to error
						$('html, body').animate({
							scrollTop: $container.offset().top - 100
						}, 500);

						// Focus the select
						$memberSelect.focus();

						return false;
					}
				}
			});
		}
	};

	/**
	 * Initialize when document is ready
	 */
	$(document).ready(function() {
		KCM_WooCommerce.init();
	});

})(jQuery);
