/**
 * Handles rendering charts and data on the analytics dashboard.
 *
 * @package    Ai_Try_N_Buy
 * @subpackage Ai_Try_N_Buy/analytics/assets/js
 * @author     Edu Brazeal <contact@edubrazeal.com>
 */
(function ($) {
	'use strict';

	$(document).ready(function () {
		if ($('#aitnbConversionChart').length === 0) {
			return;
		}

		var conversionChart = null;
		var noDataTemplate = $('#aitnb-no-data-template').html();
		var errorTemplateHtml = $('#aitnb-error-template').html();
		var productListItemTemplate = $('#aitnb-product-list-item-template').html();
		var listPlaceholderTemplate = $('#aitnb-product-list-placeholder-template').html();
		var i18n = aitnb_analytics_params.i18n;

		function fetchAndRenderData(period) {
			var $loader = $('#aitnb-dashboard-loader');
			$loader.show();
			$('#aitnb-dashboard-widgets').hide();
			$loader.html('<p>' + escapeHtml(i18n.loadingData) + '</p>');

			$.ajax({
				url: aitnb_analytics_params.ajax_url,
				type: 'POST',
				data: {
					action: 'aitnb_get_analytics_data',
					nonce: aitnb_analytics_params.nonce,
					period: period
				},
				success: function (response) {
					if (response.success === true) {
						var data = response.data;
						
						var hasData = (data.conversion_overview.tries > 0 || 
									   data.conversion_overview.purchases > 0 ||
									   data.top_tried_products.length > 0 ||
									   data.top_purchased_products.length > 0);
						
						if (!hasData) {
							showNoDataMessage();
						} else {
							renderOverview(data.conversion_overview);
							renderTopProductsLists(data.top_tried_products, data.top_purchased_products);
							$loader.hide();
							$('#aitnb-dashboard-widgets').show();
						}
					} else {
						var errorMsg = response.data && response.data.message 
							? response.data.message 
							: i18n.couldNotLoad;
						showErrorMessage(errorMsg);
					}
				},
				error: function (jqXHR, textStatus, errorThrown) {
					var errorMsg = i18n.requestFailed + ' ';
					if (jqXHR.status === 403) {
						errorMsg += i18n.permissionDenied;
					} else if (jqXHR.status === 0) {
						errorMsg += i18n.networkError;
					} else if (jqXHR.responseText === '-1') {
						errorMsg += i18n.securityCheckFailed;
					} else {
						errorMsg += i18n.statusPrefix + jqXHR.status + ' - ' + escapeHtml(textStatus);
					}
					
					showErrorMessage(errorMsg);
				}
			});
		}

		function showNoDataMessage() {
			$('#aitnb-dashboard-loader').html(noDataTemplate);
		}

		function showErrorMessage(message) {
			var $errorHtml = $(errorTemplateHtml);
			$errorHtml.find('.aitnb-error-message').text(message);
			$('#aitnb-dashboard-loader').html($errorHtml);
			
			$(document).off('click', '#aitnb-retry-load').on('click', '#aitnb-retry-load', function() {
				fetchAndRenderData($('#aitnb-period-filter').val());
			});
		}

		function renderOverview(overviewData) {
			var tries = overviewData.tries || 0;
			var purchases = overviewData.purchases || 0;
			var conversionRate = (tries > 0) ? ((purchases / tries) * 100).toFixed(2) + '%' : '0.00%';

			$('#aitnbTotalTries').text(tries);
			$('#aitnbTotalPurchases').text(purchases);
			$('#aitnbConversionRate').text(conversionRate);

			var ctx = document.getElementById('aitnbConversionChart');
			if (!ctx) {
				return;
			}
			
			var chartContext = ctx.getContext('2d');
			
			if (conversionChart) {
				conversionChart.destroy();
				conversionChart = null;
			}

			if (tries === 0 && purchases === 0) {
				conversionChart = new Chart(chartContext, {
					type: 'doughnut',
					data: {
						labels: [i18n.noDataYet],
						datasets: [{
							label: i18n.eventCount,
							data: [1],
							backgroundColor: ['rgba(200, 200, 200, 0.5)'],
							borderColor: ['rgba(200, 200, 200, 1)'],
							borderWidth: 1
						}]
					},
					options: {
						responsive: true,
						maintainAspectRatio: false,
						plugins: {
							legend: {
								position: 'top'
							},
							tooltip: {
								enabled: false
							}
						}
					}
				});
			} else {
				conversionChart = new Chart(chartContext, {
					type: 'doughnut',
					data: {
						labels: [i18n.tryEvents, i18n.purchasesFromTries],
						datasets: [{
							label: i18n.eventCount,
							data: [tries, purchases],
							backgroundColor: [
								'rgba(54, 162, 235, 0.8)',
								'rgba(75, 192, 192, 0.8)'
							],
							borderColor: [
								'rgba(54, 162, 235, 1)',
								'rgba(75, 192, 192, 1)'
							],
							borderWidth: 1
						}]
					},
					options: {
						responsive: true,
						maintainAspectRatio: false,
						plugins: {
							legend: {
								position: 'top'
							}
						}
					}
				});
			}
		}

		function renderTopProductsLists(topTried, topPurchased) {
			var triedList = $('#aitnbTopTriedProducts');
			var purchasedList = $('#aitnbTopPurchasedProducts');

			triedList.empty();
			purchasedList.empty();

			if (topTried.length > 0) {
				$.each(topTried, function(index, product) {
					var $listItem = $(productListItemTemplate);
					$listItem.find('.aitnb-product-name').text(product.product_name);
					$listItem.find('.aitnb-event-count').text(product.event_count);
					triedList.append($listItem);
				});
			} else {
				var $placeholder = $(listPlaceholderTemplate);
				$placeholder.text(i18n.noTryOnData);
				triedList.append($placeholder);
			}

			if (topPurchased.length > 0) {
				$.each(topPurchased, function(index, product) {
					var $listItem = $(productListItemTemplate);
					$listItem.find('.aitnb-product-name').text(product.product_name);
					$listItem.find('.aitnb-event-count').text(product.event_count);
					purchasedList.append($listItem);
				});
			} else {
				var $placeholder = $(listPlaceholderTemplate);
				$placeholder.text(i18n.noPurchaseData);
				purchasedList.append($placeholder);
			}
		}

		function escapeHtml(text) {
			var map = {
				'&': '&amp;',
				'<': '&lt;',
				'>': '&gt;',
				'"': '&quot;',
				"'": '&#039;'
			};
			return String(text).replace(/[&<>"']/g, function(m) { return map[m]; });
		}

		$('#aitnb-period-filter').on('change', function () {
			fetchAndRenderData($(this).val());
		});

		fetchAndRenderData($('#aitnb-period-filter').val());

	});

})(jQuery);