/**
 * @package    Ai_Try_N_Buy
 * @subpackage Ai_Try_N_Buy/public/assets/js
 * @author     Edu Brazeal <contact@edubrazeal.com>
 *
 * All JavaScript for the AI Style Assistant feature.
 */

(function ($) {
	'use strict';

	$(document).ready(function () {

		var section = $('.aitnb-style-assistant-section');
		var container = null;
		var allProductsData = [];
		var cartUrl = '';
		var variationModal = $('.aitnb-variation-modal');
		var variationModalBody = $('.aitnb-variation-modal-body');
		var confirmVariationsBtn = $('.aitnb-confirm-variations-btn');
		var productCardTemplateHtml = $('.aitnb-product-card-template').html();
		var variationProductTemplateHtml = $('.aitnb-variation-product-template').html();
		var notificationModal = $('.aitnb-notification-modal');
		var i18n = aitnb_style_params.i18n;

		if (section.length === 0) {
			return;
		}

		container = section.find('.aitnb-recommendations-container');

		function showNotification(message, type) {
			type = type || 'error';
			
			notificationModal.removeClass('success warning error').addClass(type);
			notificationModal.find('.aitnb-notification-message').text(message);
			notificationModal.removeClass('aitnb-hidden').addClass('is-visible');
		}

		function closeNotification() {
			notificationModal.removeClass('is-visible');
			setTimeout(function() {
				notificationModal.addClass('aitnb-hidden');
			}, 300);
		}

		function buildProductCard(product) {
			var card = $(productCardTemplateHtml);
			card.find('a').attr('href', product.link);
			card.find('.aitnb-card-image img').attr('src', product.image_url).attr('alt', product.name);
			card.find('.aitnb-card-title').text(product.name);
			card.find('.aitnb-card-price').html(product.price);
			return card;
		}
		
		function openVariationModal(productsToShow) {
			variationModalBody.empty();

			if (productsToShow.length === 0) {
				confirmVariationsBtn.prop('disabled', true);
			} else {
				confirmVariationsBtn.prop('disabled', false);
			}

			$.each(productsToShow, function(index, product) {
				var item = $(variationProductTemplateHtml);
				var selectorsContainer = null;

				item.attr('data-product-id', product.id);
				item.find('.aitnb-variation-product-image').attr('src', product.image_url).attr('alt', product.name);
				item.find('.aitnb-variation-product-title').text(product.name);
				item.find('.aitnb-variation-product-price').html(product.price);

				selectorsContainer = item.find('.aitnb-variation-selectors');

				if (product.type === 'variable' && product.attributes) {
					$.each(product.attributes, function(i, attribute) {
						var select = $('<select>').attr('data-attribute-name', attribute.slug);
						select.append($('<option>').val('').text('Choose ' + attribute.name));
						$.each(attribute.terms, function(j, term) {
							select.append($('<option>').val(term).text(term));
						});
						selectorsContainer.append(select);
					});
				}

				variationModalBody.append(item);
			});

			variationModal.addClass('is-visible');
		}

		function closeModal() {
			variationModal.removeClass('is-visible');
		}

		function addProductsToCart(productsToAdd) {
			var addAllBtn = $('.aitnb-add-all-to-cart-btn');

			if (productsToAdd.length === 0) {
				closeModal();
				return;
			}
			
			addAllBtn.prop('disabled', true).text(i18n.adding);

			$.ajax({
				url: aitnb_style_params.ajax_url,
				type: 'POST',
				data: {
					action: 'aitnb_add_style_products_to_cart',
					nonce: aitnb_style_params.nonce,
					products: productsToAdd
				},
				success: function(response) {
					if (response.success) {
						cartUrl = response.data.cart_url;
						addAllBtn.prop('disabled', false).text(i18n.viewCart).addClass('is-added');
						closeModal();
					} else {
						addAllBtn.prop('disabled', false).text(i18n.addAllToCart);
						showNotification(response.data && response.data.message ? response.data.message : i18n.errorOccurred, 'error');
					}
				},
				error: function() {
					addAllBtn.prop('disabled', false).text(i18n.addAllToCart);
					showNotification(i18n.requestFailed, 'error');
				}
			});
		}

		function fetchStyleRecommendations() {
			var addAllBtn = $('.aitnb-add-all-to-cart-btn');

			$.ajax({
				url: aitnb_style_params.ajax_url,
				type: 'POST',
				data: {
					action: 'aitnb_get_style_recommendations',
					nonce: aitnb_style_params.nonce,
					product_id: aitnb_style_params.product.id
				},
				success: function (response) {
					var originalProduct = null;
					var recommendedProducts = null;
					var fragment = null;

					if (!response.success) {
						section.hide();
						return;
					}

					originalProduct = response.data.original_product;
					recommendedProducts = response.data.products;

					if (!originalProduct && (!recommendedProducts || recommendedProducts.length === 0)) {
						section.hide();
						return;
					}

					allProductsData = [];
					if (originalProduct) {
						allProductsData.push(originalProduct);
					}
					if (recommendedProducts) {
						allProductsData = allProductsData.concat(recommendedProducts);
					}

					fragment = $(document.createDocumentFragment());
					$.each(allProductsData, function(index, productData) {
						var newCard = buildProductCard(productData);
						fragment.append(newCard);
					});

					container.empty().append(fragment);
					
					if (recommendedProducts && recommendedProducts.length > 0) {
						addAllBtn.removeClass('aitnb-hidden');
					}
				},
				error: function () {
					section.hide();
				}
			});
		}

		function findMatchingVariation(productData, selectedAttributes) {
			var matchedVariation = null;

			if (!productData.variations || !Array.isArray(productData.variations)) {
				return null;
			}

			matchedVariation = productData.variations.find(function(variation) {
				var variationAttributes = variation.attributes;
				var selectedKey = null;
				var selectedValue = null;
				var variationKey = null;

				if (!variationAttributes) {
					return false;
				}

				if (Object.keys(selectedAttributes).length !== Object.keys(variationAttributes).length) {
					return false;
				}

				for (selectedKey in selectedAttributes) {
					if (selectedAttributes.hasOwnProperty(selectedKey)) {
						selectedValue = selectedAttributes[selectedKey];
						variationKey = Object.keys(variationAttributes).find(function(vKey) {
							return vKey.replace(/[\s_-]/g, '').toLowerCase() === selectedKey.replace(/[\s_-]/g, '').toLowerCase();
						});

						if (!variationKey || (variationAttributes[variationKey] !== '' && String(variationAttributes[variationKey]).toLowerCase() !== String(selectedValue).toLowerCase())) {
							return false;
						}
					}
				}

				return true;
			});

			return matchedVariation;
		}

		function validateAndPrepareProducts() {
			var finalProductsToAdd = [];
			var errorFound = false;
			var errorMessage = '';
			var hasIncompleteSelection = false;

			variationModalBody.find('select').removeClass('aitnb-selection-error');
			
			variationModalBody.find('.aitnb-variation-product-item').each(function() {
				var item = $(this);
				var productId = item.data('product-id');
				var productData = allProductsData.find(function(p) { return p.id === productId; });
				var selectedAttributes = {};
				var matchedVariation = null;

				if (!productData) {
					return;
				}

				if (productData.type === 'variable') {
					hasIncompleteSelection = false;

					item.find('select').each(function() {
						var select = $(this);
						var attrName = select.data('attribute-name');
						var attrValue = select.val();
						if (attrValue) {
							selectedAttributes['attribute_' + attrName] = attrValue;
						} else {
							hasIncompleteSelection = true;
							select.addClass('aitnb-selection-error');
						}
					});

					if (hasIncompleteSelection) {
						errorFound = true;
						errorMessage = i18n.selectAllOptions;
						return false; 
					}

					matchedVariation = findMatchingVariation(productData, selectedAttributes);

					if (matchedVariation) {
						finalProductsToAdd.push({
							product_id: productId,
							variation_id: matchedVariation.id,
							attributes: selectedAttributes
						});
					} else {
						errorFound = true;
						errorMessage = i18n.combinationUnavailable;
						item.find('select').addClass('aitnb-selection-error');
						return false;
					}
				} else {
					finalProductsToAdd.push({ product_id: productId });
				}
			});

			return {
				success: !errorFound,
				errorMessage: errorMessage,
				products: finalProductsToAdd
			};
		}

		$(document).off('click', '.aitnb-add-all-to-cart-btn').on('click', '.aitnb-add-all-to-cart-btn', function(e) {
			e.preventDefault();
			var $this = $(this);

			if ($this.hasClass('is-added')) {
				if (cartUrl) {
					window.location.href = cartUrl;
				}
				return;
			}
			
			openVariationModal(allProductsData);
		});

		$(document).off('click', '.aitnb-confirm-variations-btn').on('click', '.aitnb-confirm-variations-btn', function() {
			var validationResult = validateAndPrepareProducts();

			if (validationResult.success) {
				addProductsToCart(validationResult.products);
			} else {
				showNotification(validationResult.errorMessage, 'error');
			}
		});

		variationModalBody.off('click', '.aitnb-remove-variation-item').on('click', '.aitnb-remove-variation-item', function() {
			var item = $(this).closest('.aitnb-variation-product-item');
			item.fadeOut(300, function() {
				$(this).remove();
				if (variationModalBody.find('.aitnb-variation-product-item').length === 0) {
					confirmVariationsBtn.prop('disabled', true);
				}
			});
		});
		
		$(document).off('click', '.aitnb-variation-modal .aitnb-fit-modal-close-btn').on('click', '.aitnb-variation-modal .aitnb-fit-modal-close-btn', closeModal);
		$(document).off('click', '.aitnb-variation-modal .aitnb-fit-modal-overlay').on('click', '.aitnb-variation-modal .aitnb-fit-modal-overlay', closeModal);

		$(document).off('click', '.aitnb-notification-btn').on('click', '.aitnb-notification-btn', closeNotification);
		$(document).off('click', '.aitnb-notification-overlay').on('click', '.aitnb-notification-overlay', closeNotification);

		fetchStyleRecommendations();
	});

})(jQuery);