/**
 * Handles the World Tracking (Model Viewer) Virtual Try-On experience.
 *
 * @package    Ai_Try_N_Buy
 * @subpackage Ai_Try_N_Buy/public/assets/js
 * @author     Edu Brazeal <contact@edubrazeal.com>
 */
(function ($) {
	'use strict';

	$(document).ready(function () {

		var startBtnSelector = '.aitnb-start-tryon-btn';
		if ($(startBtnSelector).length === 0) {
			return;
		}
		
		var startBtn = $(startBtnSelector);
		var mvContainer = $('.aitnb-mv-container');
		var mvCloseBtn = $('.aitnb-mv-close-btn');
		var modelViewerTag = $('.aitnb-model-viewer-tag');
		var tryEventTracked = false;
		var i18n = aitnb_params.i18n;
		var notificationModal = $('.aitnb-notification-modal');

		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 trackTryOnEvent() {
			if (tryEventTracked) {
				return;
			}
			$.ajax({
				url: aitnb_params.ajax_url,
				type: 'POST',
				data: {
					action: 'aitnb_track_try_on_event',
					nonce: aitnb_params.nonce,
					product_id: aitnb_params.product.id
				},
				success: function(response) {
					if (response.success) {
						tryEventTracked = true;
					}
				}
			});
		}

		function openModelViewerExperience() {
			var assetUrl = aitnb_params.product.asset_url;
			var assetUrlLower = assetUrl.toLowerCase();

			if (!assetUrl || !assetUrlLower.endsWith('.glb')) {
				showNotification(i18n.noGlbModel, 'error');
				return;
			}

			mvContainer.addClass('is-visible');

			setTimeout(function() {
				modelViewerTag.attr('src', assetUrl);
				modelViewerTag.attr('alt', 'A 3D model of ' + aitnb_params.product.name);
				modelViewerTag.attr('scale', aitnb_params.product.scale + ' ' + aitnb_params.product.scale + ' ' + aitnb_params.product.scale);
				trackTryOnEvent();
			}, 100);
		}

		function closeModelViewerExperience() {
			mvContainer.removeClass('is-visible');
			setTimeout(function() {
				modelViewerTag.attr('src', null);
			}, 300);
		}

		startBtn.on('click', openModelViewerExperience);
		mvCloseBtn.on('click', closeModelViewerExperience);
		
		$(document).off('click', '.aitnb-notification-btn').on('click', '.aitnb-notification-btn', closeNotification);
		$(document).off('click', '.aitnb-notification-overlay').on('click', '.aitnb-notification-overlay', closeNotification);
	});

})(jQuery);
