/**
 * FoodOrd Block Checkout Validation Script
 * Handles minimum order validation for WooCommerce block-based checkout
 */

(function() {
	'use strict';

	// Early exit if params not defined
	if (typeof foodord_block_checkout_params === 'undefined') {
		return;
	}

	const minimumAmount = parseFloat(foodord_block_checkout_params.minimum_order_amount);
	const cartTotal = parseFloat(foodord_block_checkout_params.cart_total);
	
	// Exit if no minimum is set
	if (!minimumAmount || minimumAmount <= 0) {
		return;
	}

	/**
	 * Simple price formatter
	 */
	function formatPrice(amount) {
		const symbol = foodord_block_checkout_params.currency_symbol || '$';
		return symbol + parseFloat(amount).toFixed(2);
	}

	/**
	 * Add validation notice and handle button state
	 */
	function checkAndUpdateValidation() {
		// Wait a bit for DOM to be ready
		setTimeout(function() {
			const checkoutForm = document.querySelector('.wc-block-checkout__main');
			if (!checkoutForm) return;
			
			// Remove existing notice
			const existingNotice = document.querySelector('.foodord-block-minimum-notice');
			if (existingNotice) {
				existingNotice.remove();
			}
			
			if (cartTotal < minimumAmount) {
				const remaining = minimumAmount - cartTotal;
				const message = foodord_block_checkout_params.add_more_message.replace('%s', formatPrice(remaining));
				
				// Create and add notice
				const notice = document.createElement('div');
				notice.className = 'wc-block-components-notice-banner is-warning foodord-block-minimum-notice';
				notice.style.marginBottom = '20px';
				notice.innerHTML = `
					<svg class="wc-block-components-notice-banner__icon" viewBox="0 0 24 24" style="width:24px;height:24px;">
						<path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-2h2v2zm0-4h-2V7h2v6z"></path>
					</svg>
					<div class="wc-block-components-notice-banner__content">
						${message}
					</div>
				`;
				checkoutForm.insertBefore(notice, checkoutForm.firstChild);
				
				// Disable button
				const button = document.querySelector('.wc-block-components-checkout-place-order-button');
				if (button) {
					button.disabled = true;
					button.style.opacity = '0.5';
					button.style.cursor = 'not-allowed';
					
					if (!button.dataset.originalText) {
						button.dataset.originalText = button.textContent;
					}
					button.textContent = foodord_block_checkout_params.message_template.replace('%s', formatPrice(minimumAmount));
				}
			} else {
				// Enable button if minimum is met
				const button = document.querySelector('.wc-block-components-checkout-place-order-button');
				if (button && button.disabled) {
					button.disabled = false;
					button.style.opacity = '';
					button.style.cursor = '';
					
					if (button.dataset.originalText) {
						button.textContent = button.dataset.originalText;
					}
				}
			}
		}, 500);
	}


	/**
	 * Initialize validation when DOM is ready
	 */
	function init() {
		// Initial check
		checkAndUpdateValidation();
		
		// Watch for changes in order summary which indicates cart update
		let observerTimeout;
		const targetNode = document.querySelector('.wc-block-components-order-summary') || document.querySelector('.wc-block-checkout');
		
		if (targetNode) {
			const observer = new MutationObserver(function() {
				// Debounce the check
				clearTimeout(observerTimeout);
				observerTimeout = setTimeout(checkAndUpdateValidation, 1000);
			});
			
			observer.observe(targetNode, {
				childList: true,
				subtree: true,
				attributes: false,
				characterData: false
			});
		}
	}

	// Wait for DOM to be ready
	if (document.readyState === 'loading') {
		document.addEventListener('DOMContentLoaded', function() {
			setTimeout(init, 1500);
		});
	} else {
		// Give time for block checkout to load
		setTimeout(init, 1500);
	}

})();
