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

(function ($) {
	'use strict';

	$(document).ready(function () {

		var openBtn = $('.aitnb-open-fit-recommender');
		var modal = $('.aitnb-fit-recommender-modal');
		var closeBtn = $('.aitnb-fit-close-btn');
		var overlay = $('.aitnb-fit-modal-overlay');
		var resultDiv = $('.aitnb-fit-recommender-result');
		var i18n = aitnb_fit_params.i18n;

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

		function openModal() {
			modal.addClass('is-visible');
		}

		function closeModal() {
			modal.removeClass('is-visible');
			setTimeout(function() {
				$('.aitnb-height').val('');
				$('.aitnb-weight').val('');
				$('.aitnb-fit-preference').val('regular');
				resultDiv.html('').removeClass('loading success error');
			}, 300);
		}

		function validateFormInputs() {
			var height = $('.aitnb-height').val();
			var weight = $('.aitnb-weight').val();
			var fitPreference = $('.aitnb-fit-preference').val();

			if (!height || !weight || !fitPreference) {
				return false;
			}

			if (isNaN(height) || isNaN(weight)) {
				return false;
			}

			if (parseFloat(height) <= 0 || parseFloat(weight) <= 0) {
				return false;
			}

			return true;
		}

		function handleGetRecommendation() {
			if (!validateFormInputs()) {
				resultDiv.html(i18n.analyzing).removeClass('success error').addClass('loading');
				setTimeout(function() {
					resultDiv.html('Please provide valid measurements.').removeClass('loading').addClass('error');
				}, 100);
				return;
			}

			resultDiv.html(i18n.analyzing).removeClass('success error').addClass('loading');

			var ajaxData = {
				action: 'aitnb_get_fit_recommendation',
				nonce: aitnb_fit_params.nonce,
				product_id: aitnb_fit_params.product.id,
				user_data: {
					height: $('.aitnb-height').val(),
					weight: $('.aitnb-weight').val(),
					fit_preference: $('.aitnb-fit-preference').val()
				}
			};

			$.ajax({
				url: aitnb_fit_params.ajax_url,
				type: 'POST',
				data: ajaxData,
				success: function (response) {
					if (response.success) {
						resultDiv.html(response.data.recommendation).removeClass('loading').addClass('success');
					} else {
						var message = response.data && response.data.message ? response.data.message : i18n.errorOccurred;
						resultDiv.html(message).removeClass('loading').addClass('error');
					}
				},
				error: function () {
					resultDiv.html(i18n.requestFailed).removeClass('loading').addClass('error');
				}
			});
		}

		openBtn.on('click', openModal);
		closeBtn.on('click', closeModal);
		overlay.on('click', closeModal);

		$(document).off('click', '.aitnb-get-recommendation-btn').on('click', '.aitnb-get-recommendation-btn', function (e) {
			e.preventDefault();
			handleGetRecommendation();
		});
	});

})(jQuery);