/**
 * FoodOrd Checkout Validation Script
 */

(function($) {
	'use strict';

	/**
	 * Checkout validation handler
	 */
	const FoodordCheckoutValidation = {
		
	/**
	 * Initialize
	 */
	init: function() {
		this.bindEvents();
		this.checkMinimumAmount();
		this.listenForModeChanges();
		this.listenForLocationSelection();
	},
		
	/**
	 * Bind events
	 */
	bindEvents: function() {
		// Listen for cart updates
		$(document.body).on('updated_checkout', this.checkMinimumAmount.bind(this));
		$(document.body).on('update_checkout', this.checkMinimumAmount.bind(this));
		
		// Monitor place order button clicks
		$('form.checkout').on('click', '#place_order', this.validateBeforeSubmit.bind(this));
		
		// Monitor cart total changes
		$(document.body).on('wc_cart_updated', this.checkMinimumAmount.bind(this));
	},
	
	/**
	 * Listen for delivery mode changes
	 */
	listenForModeChanges: function() {
		// Listen for mode changes from delivery-pickup toggle
		$(document).on('wrc:deliveryModeChange', this.handleModeChange.bind(this));
	},

	/**
	 * Listen for address/location selection updates
	 */
	listenForLocationSelection: function() {
		const self = this;
		document.addEventListener('foodord:locationSelected', function(event) {
				if (typeof foodord_checkout_params === 'undefined') {
					return;
				}
				const detail = event && event.detail ? event.detail : {};
				const parsedMinimum = typeof detail.minimum !== 'undefined' ? parseFloat(detail.minimum) : NaN;
				if (!isNaN(parsedMinimum) && parsedMinimum > 0) {
					foodord_checkout_params.minimum_order_amount = parsedMinimum;
				} else {
					foodord_checkout_params.minimum_order_amount = 0;
				}
				self.checkMinimumAmount();
			});
	},
	
	/**
	 * Handle mode changes
	 */
	handleModeChange: function(event) {
		if (!event || !event.detail || !event.detail.mode) {
			return;
		}
		
		// Re-check minimum amount when mode changes
		// Pickup mode should have no minimum, delivery mode should enforce it
		this.checkMinimumAmount();
	},
		
	/**
	 * Check minimum order amount
	 */
	checkMinimumAmount: function() {
		if (typeof foodord_checkout_params === 'undefined') {
			return;
		}
		
		// Check if pickup mode is active - no minimum for pickup
		const currentMode = this.getCurrentMode();
		if (currentMode === 'pickup') {
			this.enableCheckoutButton();
			this.removeNotice();
			return;
		}
		
		const minimumAmount = parseFloat(foodord_checkout_params.minimum_order_amount);
		if (!minimumAmount || minimumAmount <= 0) {
			this.enableCheckoutButton();
			return;
		}
			
			// Get current cart total from page
			const cartTotal = this.getCurrentCartTotal();
			
			if (cartTotal < minimumAmount) {
				this.disableCheckoutButton();
				this.updateNotice(minimumAmount - cartTotal);
			} else {
				this.enableCheckoutButton();
				this.removeNotice();
			}
		},
		
		/**
		 * Get current cart total from checkout page
		 */
		getCurrentCartTotal: function() {
			let total = 0;
			
			// Try to get subtotal from checkout review order table
			const $subtotal = $('.cart-subtotal .woocommerce-Price-amount bdi');
			if ($subtotal.length) {
				const priceText = $subtotal.text().replace(/[^\d.,]/g, '');
				total = parseFloat(priceText.replace(',', '.'));
			}
			
			// Fallback: try order total
			if (!total) {
				const $total = $('.order-total .woocommerce-Price-amount bdi');
				if ($total.length) {
					const priceText = $total.text().replace(/[^\d.,]/g, '');
					total = parseFloat(priceText.replace(',', '.'));
				}
			}
			
			return total;
		},
		
		/**
		 * Disable checkout button
		 */
		disableCheckoutButton: function() {
			const $button = $('#place_order');
			$button.prop('disabled', true);
			$button.addClass('foodord-disabled-checkout');
			
			// Update button text
			if (!$button.data('original-text')) {
				$button.data('original-text', $button.val());
			}
			$button.val(foodord_checkout_params.message_template.replace('%s', this.formatPrice(foodord_checkout_params.minimum_order_amount)));
		},
		
		/**
		 * Enable checkout button
		 */
		enableCheckoutButton: function() {
			const $button = $('#place_order');
			$button.prop('disabled', false);
			$button.removeClass('foodord-disabled-checkout');
			
			// Restore original text
			const originalText = $button.data('original-text');
			if (originalText) {
				$button.val(originalText);
			}
		},
		
		/**
		 * Update minimum order notice
		 */
		updateNotice: function(remaining) {
			const $existingNotice = $('.foodord-checkout-minimum-notice');
			if ($existingNotice.length) {
				// Update existing notice
				$existingNotice.find('.amount').text(this.formatPrice(remaining));
			}
			// Note: Main notice is handled by PHP
		},
		
		/**
		 * Remove minimum order notice
		 */
		removeNotice: function() {
			$('.foodord-minimum-order-notice').fadeOut(300, function() {
				$(this).remove();
			});
		},
		
	/**
	 * Validate before submit
	 */
	validateBeforeSubmit: function(e) {
		if (typeof foodord_checkout_params === 'undefined') {
			return true;
		}
		
		// No minimum for pickup mode
		const currentMode = this.getCurrentMode();
		if (currentMode === 'pickup') {
			return true;
		}
		
		const minimumAmount = parseFloat(foodord_checkout_params.minimum_order_amount);
		if (!minimumAmount || minimumAmount <= 0) {
			return true;
		}
		
		const cartTotal = this.getCurrentCartTotal();
		
		if (cartTotal < minimumAmount) {
			e.preventDefault();
			
			// Show alert
			const remaining = minimumAmount - cartTotal;
			const message = 'Please add ' + this.formatPrice(remaining) + ' more to meet the minimum order requirement.';
			alert(message);
			
			return false;
		}
		
		return true;
	},
		
	/**
	 * Format price with currency symbol
	 */
	formatPrice: function(amount) {
		const symbol = foodord_checkout_params.currency_symbol || '$';
		return symbol + parseFloat(amount).toFixed(2);
	},
	
	/**
	 * Get current order mode
	 */
	getCurrentMode: function() {
		// Fallback to hidden field value
		const hiddenField = $('input[name="foodord_order_mode"]');
		if (hiddenField.length && hiddenField.val()) {
			return hiddenField.val();
		}
		
		// Default to delivery
		return 'delivery';
	}
};
	
	/**
	 * Initialize when document is ready
	 */
	$(document).ready(function() {
		FoodordCheckoutValidation.init();
	});
	
})(jQuery);
