(function(window, $) {
	if (!$) return;

	function parseError(xhr, fallback) {
		if (xhr && xhr.responseJSON && xhr.responseJSON.error) return xhr.responseJSON.error;
		if (xhr && xhr.responseText) {
			try {
				var data = JSON.parse(xhr.responseText);
				if (data && data.error) return data.error;
			} catch (err) {}
		}
		return fallback || 'Unable to analyze this report right now.';
	}

	function setOpen($main, $panel, isOpen) {
		if (isOpen) {
			if ($panel.data('closeTimer')) {
				window.clearTimeout($panel.data('closeTimer'));
				$panel.removeData('closeTimer');
			}
			$main.removeClass('span10 sendy-report-card-wide').addClass('span6 sendy-report-card-split');
			$panel.show();
			window.setTimeout(function() {
				$panel.addClass('sendy-report-analysis-panel-open');
			}, 20);
		} else {
			$panel.removeClass('sendy-report-analysis-panel-open');
			$main.removeClass('span6 sendy-report-card-split').addClass('span10 sendy-report-card-wide');
			$panel.data('closeTimer', window.setTimeout(function() {
				if (!$panel.hasClass('sendy-report-analysis-panel-open')) $panel.hide();
				$panel.removeData('closeTimer');
			}, 220));
		}
	}

	function magicButtonHtml(label) {
		return '<i class="icon icon-magic"></i> <span class="sendy-ai-rainbow-text">' + label + '</span>';
	}

	$(document).ready(function() {
		var $shell = $('.sendy-report-analysis-shell');
		if (!$shell.length) return;

		var $main = $('#sendy-report-main');
		var $panel = $('#sendy-report-analysis-panel');
		var $content = $('#sendy-report-analysis-content');
		var $button = $('#sendy-report-analysis-btn');
		var $reopenButton = $('#sendy-report-reopen-analysis-btn');
		var $score = $('#sendy-report-score');
		var $scoreValue = $('#sendy-report-score-value');
		var $scoreBar = $('#sendy-report-score-bar');
		var $close = $('#sendy-report-analysis-close');
		var analyzeEndpoint = $shell.data('analyzeEndpoint');
		var stateEndpoint = $shell.data('stateEndpoint');
		var appId = $shell.data('appId');
		var reportType = $shell.data('reportType');
		var reportId = $shell.data('reportId');
		var originalButtonHtml = $button.html();
		var reanalyzeLabel = $button.attr('data-label-reanalyze') || 'Re-analyse report';
		var openLastAnalysisLabel = $reopenButton.attr('data-open-label') || 'Open last analysis';
		var closeAnalysisLabel = $reopenButton.attr('data-close-label') || 'Close analysis';
		var loadingText = $button.data('loadingText') || 'Analyzing...';
		var errorText = $button.data('errorText') || 'Unable to analyze this report right now.';

		if ($panel.is(':visible')) {
			window.setTimeout(function() {
				$panel.addClass('sendy-report-analysis-panel-open');
			}, 20);
		}

		function setReopenButtonLabel(isOpen) {
			if (!$reopenButton.length) return;
			$reopenButton.html('<i class="icon icon-folder-open"></i> ' + (isOpen ? closeAnalysisLabel : openLastAnalysisLabel));
		}

		function saveState(isOpen) {
			$.post(stateEndpoint, {
				app: appId,
				report_type: reportType,
				report_id: reportId,
				is_open: isOpen ? 1 : 0
			});
		}

		function updateScore(score) {
			score = parseInt(score, 10);
			if (isNaN(score)) return;
			score = Math.max(0, Math.min(100, score));
			$scoreValue.text(score);
			$scoreBar.css('width', score + '%');
			$score.fadeIn(150);
		}

		$button.click(function(e) {
			e.preventDefault();
			setOpen($main, $panel, true);
			setReopenButtonLabel(true);
			saveState(true);

			$content.removeClass('alert alert-error').text(loadingText);
			$button.prop('disabled', true).html('<i class="icon icon-refresh"></i> <span class="sendy-ai-rainbow-text">' + loadingText + '</span>');

			$.ajax({
				url: analyzeEndpoint,
				type: 'POST',
				dataType: 'json',
				timeout: 120000,
				data: {
					app: appId,
					report_type: reportType,
					report_id: reportId
				}
			})
			.done(function(response) {
				if (!response || !response.analysis) {
					$content.addClass('alert alert-error').text(errorText);
					return;
				}
				$content.html(response.analysis);
				updateScore(response.score);
				$reopenButton.show();
				setReopenButtonLabel(true);
				originalButtonHtml = magicButtonHtml(reanalyzeLabel);
				$button.html(originalButtonHtml);
				})
			.fail(function(xhr) {
				$content.addClass('alert alert-error').text(parseError(xhr, errorText));
			})
			.always(function() {
				$button.prop('disabled', false).html(originalButtonHtml);
			});
		});

		$close.click(function(e) {
			e.preventDefault();
			setOpen($main, $panel, false);
			setReopenButtonLabel(false);
			saveState(false);
		});

		$reopenButton.click(function(e) {
			e.preventDefault();
			if (!$content.html()) return;
			var isOpen = $panel.is(':visible');
			setOpen($main, $panel, !isOpen);
			setReopenButtonLabel(!isOpen);
			saveState(!isOpen);
		});
	});
})(window, window.jQuery);
