/**
 * Handles the Face Tracking (MindAR) 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';
		var arContainer = $('.aitnb-ar-container');
		var arCloseBtn = $('.aitnb-close-btn');
		var scenePlaceholder = $('.aitnb-ar-scene-placeholder');
		var loader = $('.aitnb-loader');
		var tryEventTracked = false;
		var i18n = aitnb_params.i18n;

		if ($(startBtnSelector).length === 0) {
			return;
		}

		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 openMindArExperience() {
			loader.show().find('p').text(i18n.initializingCamera);
			arContainer.addClass('is-visible');
			setTimeout(initializeArScene, 50);
		}

		function closeMindArExperience() {
			arContainer.removeClass('is-visible');
			setTimeout(destroyArScene, 300);
		}

		function initializeArScene() {
			var assetUrl = aitnb_params.product.asset_url;
			var pos = aitnb_params.product.position;
			var scale = aitnb_params.product.scale;
			var positionStr = pos.x + ' ' + pos.y + ' ' + pos.z;
			var scaleStr = scale + ' ' + scale + ' ' + scale;
			var assetEntity = '';
			var assetUrlLower = assetUrl.toLowerCase();
			var sceneHtml = '';
			var sceneEl = null;

			if (!assetUrl) {
				scenePlaceholder.html('<p>' + i18n.noAssetDefined + '</p>');
				loader.hide();
				return;
			}

			if (assetUrlLower.endsWith('.glb')) {
				assetEntity = '<a-entity id="tryon-asset" gltf-model="' + assetUrl + '" position="' + positionStr + '" scale="' + scaleStr + '"></a-entity>';
			} else {
				assetEntity = '<a-image id="tryon-asset" src="' + assetUrl + '" position="' + positionStr + '" scale="' + scaleStr + '" material="transparent: true"></a-image>';
			}
			
			sceneHtml = '<a-scene ' +
				'mindar-face="filterMinCF: 0.0001; filterBeta: 200;" ' +
				'embedded ' +
				'vr-mode-ui="enabled: false" ' +
				'device-orientation-permission-ui="enabled: false" ' +
				'renderer="colorManagement: true; alpha: true;">' +
				'<a-camera active="false" position="0 0 0"></a-camera>' +
				'<a-entity mindar-face-target="anchorIndex: 0">' +
				assetEntity +
				'</a-entity>' +
				'</a-scene>';

			scenePlaceholder.html(sceneHtml);
			
			sceneEl = scenePlaceholder.find('a-scene');
			if (sceneEl.length > 0) {
				sceneEl.on('arReady', function() {
					var mindarSystem = sceneEl[0].systems['mindar-face-system'];
					var video = null;
					var canvas = null;
					var assetEntityEl = null;
					var sceneCanvas = null;

					if (mindarSystem && mindarSystem.video) {
						video = mindarSystem.video;
						video.style.position = 'absolute';
						video.style.top = '0';
						video.style.left = '0';
						video.style.width = '100%';
						video.style.height = '100%';
						video.style.objectFit = 'cover';
						video.style.zIndex = '1';
						video.style.transform = 'scaleX(-1)';
					}
					
					canvas = sceneEl.find('canvas').get(0);
					if (canvas) {
						canvas.style.position = 'relative';
						canvas.style.zIndex = '2';
						canvas.style.background = 'transparent';
					}

					loader.fadeOut(300);
					trackTryOnEvent();

					assetEntityEl = sceneEl[0].querySelector('#tryon-asset');
					sceneCanvas = sceneEl[0].querySelector('canvas');

					if (assetEntityEl && sceneCanvas) {
						setupDragControls(assetEntityEl, sceneCanvas);
					}
				});
				sceneEl.on('arError', function() {
					loader.find('p').text(i18n.cameraError);
				});
			}
		}

		function setupDragControls(assetEntityEl, sceneCanvas) {
			var isDragging = false;
			var previousY = 0;

			var startDrag = function(e) {
				isDragging = true;
				var clientY = e.clientY || (e.touches && e.touches[0] && e.touches[0].clientY);
				previousY = clientY || 0;
			};

			var doDrag = function(e) {
				if (!isDragging) {
					return;
				}

				e.preventDefault();

				var clientY = e.clientY || (e.touches && e.touches[0] && e.touches[0].clientY);
				if (typeof clientY === 'undefined') {
					return;
				}

				var deltaY = clientY - previousY;
				previousY = clientY;

				var moveSpeed = 0.001;
				var position = assetEntityEl.getAttribute('position');
				position.y -= deltaY * moveSpeed;
				assetEntityEl.setAttribute('position', position);
			};

			var endDrag = function() {
				isDragging = false;
			};

			sceneCanvas.removeEventListener('mousedown', startDrag);
			sceneCanvas.removeEventListener('mousemove', doDrag);
			sceneCanvas.removeEventListener('mouseup', endDrag);
			sceneCanvas.removeEventListener('mouseleave', endDrag);
			sceneCanvas.removeEventListener('touchstart', startDrag);
			sceneCanvas.removeEventListener('touchmove', doDrag);
			sceneCanvas.removeEventListener('touchend', endDrag);

			sceneCanvas.addEventListener('mousedown', startDrag);
			sceneCanvas.addEventListener('mousemove', doDrag);
			sceneCanvas.addEventListener('mouseup', endDrag);
			sceneCanvas.addEventListener('mouseleave', endDrag);

			sceneCanvas.addEventListener('touchstart', startDrag);
			sceneCanvas.addEventListener('touchmove', doDrag);
			sceneCanvas.addEventListener('touchend', endDrag);
		}

		function destroyArScene() {
			var sceneEl = arContainer.find('a-scene');
			var video = null;
			var tracks = null;

			if (sceneEl.length > 0) {
				try {
					sceneEl[0].pause();
					if (sceneEl[0].systems && sceneEl[0].systems['mindar-face-system']) {
						var system = sceneEl[0].systems['mindar-face-system'];
						if (system && system.stop) {
							system.stop();
						}
					}
					video = sceneEl[0].querySelector('video');
					if (video && video.srcObject) {
						tracks = video.srcObject.getTracks();
						tracks.forEach(function(track) {
							track.stop();
						});
					}
				} catch (e) {
				}
			}
			scenePlaceholder.html('');
		}

		function handlePositionControls(action, assetEntity) {
			var moveStep = 0.01;
			var scaleStep = 0.01;
			var position = null;
			var scale = null;
			var newScale = 0;

			if (action === 'position-up' || action === 'position-down') {
				position = assetEntity.getAttribute('position');
				position.y += (action === 'position-up') ? moveStep : -moveStep;
				assetEntity.setAttribute('position', position);
			}

			if (action === 'scale-up' || action === 'scale-down') {
				scale = assetEntity.getAttribute('scale');
				newScale = scale.x + ((action === 'scale-up') ? scaleStep : -scaleStep);

				if (newScale < 0.01) {
					newScale = 0.01;
				}
				
				assetEntity.setAttribute('scale', { x: newScale, y: newScale, z: newScale });
			}
		}

		$(document).off('click', startBtnSelector).on('click', startBtnSelector, openMindArExperience);
		arCloseBtn.off('click').on('click', closeMindArExperience);
		
		$(document).off('click', '.aitnb-position-controls .aitnb-control-btn').on('click', '.aitnb-position-controls .aitnb-control-btn', function() {
			var action = $(this).data('action');
			var sceneEl = arContainer.find('a-scene');
			var assetEntity = sceneEl.length > 0 ? sceneEl[0].querySelector('#tryon-asset') : null;

			if (assetEntity) {
				handlePositionControls(action, assetEntity);
			}
		});
	});

})(jQuery);
