/**
 * Amazon Shipment Sync JavaScript
 *
 * Handles shipment confirmation UI interactions and AJAX calls.
 *
 * @package MOMCS_Sync
 */

(function ($) {
	'use strict';

	let packageCount = 0;
	const usedItems = new Set(); // Track which items are used in packages

	/**
	 * Initialize shipment confirmation functionality
	 */
	function init() {
		// Add first package on load
		addPackage();

		// Handle add package button
		$(document).on('click', '.momcs-add-package-btn', function (e) {
			e.preventDefault();
			addPackage();
		});

		// Handle remove package button
		$(document).on('click', '.momcs-remove-package-btn', function (e) {
			e.preventDefault();
			removePackage($(this).closest('.momcs-package'));
		});

		// Handle item checkbox changes
		$(document).on('change', '.item-checkbox', function () {
			handleItemSelection($(this));
		});

		// Handle confirm shipment button
		$(document).on('click', '.momcs-confirm-shipment-btn', function (e) {
			e.preventDefault();
			confirmShipment();
		});
	}

	/**
	 * Add a new package
	 */
	function addPackage() {
		packageCount++;
		const template = $('#momcs-package-template').html();
		const packageHtml = template
			.replace(/\{\{index\}\}/g, packageCount)
			.replace(/\{\{number\}\}/g, packageCount);

		$('.momcs-packages-container').append(packageHtml);
		updatePackageNumbers();
	}

	/**
	 * Remove a package
	 *
	 * @param {jQuery} $package - Package element to remove
	 */
	function removePackage($package) {
		if ($('.momcs-package').length <= 1) {
			showMessage(
				momcsShipmentSync.strings.min_one_package,
				'error'
			);
			return;
		}

		// Free up items used by this package
		$package.find('.item-checkbox:checked').each(function () {
			const itemId = $(this).data('order-item-id');
			usedItems.delete(itemId);
		});

		$package.remove();
		updatePackageNumbers();
		updateItemAvailability();
	}

	/**
	 * Update package numbers after add/remove
	 */
	function updatePackageNumbers() {
		$('.momcs-package').each(function (index) {
			$(this).find('.package-number').text(index + 1);
		});
	}

	/**
	 * Handle item selection to prevent duplicates
	 *
	 * @param {jQuery} $checkbox - Checkbox element
	 */
	function handleItemSelection($checkbox) {
		const itemId = $checkbox.data('order-item-id');
		const $quantityInput = $checkbox.siblings('.item-quantity-input');

		if ($checkbox.is(':checked')) {
			usedItems.add(itemId);
			$quantityInput.show();
		} else {
			usedItems.delete(itemId);
			$quantityInput.hide();
		}

		updateItemAvailability();
	}

	/**
	 * Update item availability across all packages
	 */
	function updateItemAvailability() {
		$('.momcs-package').each(function () {
			const $package = $(this);

			$package.find('.item-checkbox').each(function () {
				const $checkbox = $(this);
				const itemId = $checkbox.data('order-item-id');

				// If item is used in another package, disable it
				if (usedItems.has(itemId) && !$checkbox.is(':checked')) {
					$checkbox.prop('disabled', true);
					$checkbox.closest('.momcs-order-item').addClass('disabled');
				} else if (!usedItems.has(itemId)) {
					$checkbox.prop('disabled', false);
					$checkbox.closest('.momcs-order-item').removeClass('disabled');
				}
			});
		});
	}

	/**
	 * Validate package data
	 *
	 * @returns {Object} Validation result with 'valid' boolean and 'message' string
	 */
	function validatePackages() {
		const packages = [];
		let isValid = true;
		let errorMessage = '';

		$('.momcs-package').each(function () {
			const $package = $(this);
			const packageNumber = $package.find('.package-number').text();

			// Check required fields
			const referenceId = $package.find('.package-reference-id').val().trim();
			const carrierCode = $package.find('.carrier-code').val().trim();
			const carrierName = $package.find('.carrier-name').val().trim();
			const shippingMethod = $package.find('.shipping-method').val().trim();
			const trackingNumber = $package.find('.tracking-number').val().trim();
			const shipDate = $package.find('.ship-date').val().trim();

			if (!referenceId || !carrierCode || !carrierName || !shippingMethod || !trackingNumber || !shipDate) {
				isValid = false;
				errorMessage = momcsShipmentSync.strings.required_fields.replace('%d', packageNumber);
				return false; // Break loop
			}

			// Check at least one item is selected
			const selectedItems = $package.find('.item-checkbox:checked');
			if (selectedItems.length === 0) {
				isValid = false;
				errorMessage = momcsShipmentSync.strings.no_items_selected.replace('%d', packageNumber);
				return false; // Break loop
			}

			// Build order items array
			const orderItems = [];
			selectedItems.each(function () {
				const $checkbox = $(this);
				const $quantityInput = $checkbox.siblings('.item-quantity-input');
				const quantity = parseInt($quantityInput.val()) || 1;

				orderItems.push({
					orderItemId: $checkbox.data('order-item-id'),
					quantity: quantity
				});
			});

			// Convert ship date to ISO 8601 format
			const shipDateISO = new Date(shipDate).toISOString();

			packages.push({
				packageReferenceId: referenceId,
				carrierCode: carrierCode,
				carrierName: carrierName,
				shippingMethod: shippingMethod,
				trackingNumber: trackingNumber,
				shipDate: shipDateISO,
				orderItems: orderItems
			});
		});

		return {
			valid: isValid,
			message: errorMessage,
			packages: packages
		};
	}

	/**
	 * Confirm shipment via AJAX
	 */
	function confirmShipment() {
		// Validate
		const validation = validatePackages();
		if (!validation.valid) {
			showMessage(validation.message, 'error');
			return;
		}

		// Get order ID and nonce
		const orderId = $('#momcs-order-id').val();
		const nonce = $('#momcs-shipment-nonce').val();

		// Show loading state
		const $button = $('.momcs-confirm-shipment-btn');
		const $spinner = $('.momcs-shipment-actions .spinner');
		$button.prop('disabled', true);
		$spinner.addClass('is-active');
		hideMessage();

		// Make AJAX request
		$.ajax({
			url: momcsShipmentSync.ajaxUrl,
			type: 'POST',
			data: {
				action: 'momcs_confirm_amazon_shipment',
				nonce: nonce,
				order_id: orderId,
				packages: validation.packages
			},
			success: function (response) {
				if (response.success) {
					showMessage(response.data.message, 'success');
					// Clear packages and reset
					$('.momcs-packages-container').empty();
					packageCount = 0;
					usedItems.clear();
					addPackage();
					// Reload page after 2 seconds to show updated order
					setTimeout(function () {
						location.reload();
					}, 2000);
				} else {
					showMessage(response.data.message, 'error');
				}
			},
			error: function (xhr, status, error) {
				showMessage(
					momcsShipmentSync.strings.ajax_error + ': ' + error,
					'error'
				);
			},
			complete: function () {
				$button.prop('disabled', false);
				$spinner.removeClass('is-active');
			}
		});
	}

	/**
	 * Show message
	 *
	 * @param {string} message - Message text
	 * @param {string} type - Message type (success, error, warning)
	 */
	function showMessage(message, type) {
		const $messageDiv = $('.momcs-shipment-message');
		$messageDiv
			.removeClass('notice-success notice-error notice-warning')
			.addClass('notice notice-' + type)
			.html('<p>' + message + '</p>')
			.show();

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

	/**
	 * Hide message
	 */
	function hideMessage() {
		$('.momcs-shipment-message').hide();
	}

	// Initialize on document ready
	$(document).ready(init);

})(jQuery);




