(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 suggest improvements right now.';
	}

	function getFieldValue(selector) {
		var $field = $(selector);
		return $field.length ? $field.val() : '';
	}

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

	$(document).ready(function() {
		$('.sendy-content-improvements-shell').each(function() {
			var $shell = $(this);
			var $button = $shell.find('.sendy-content-improvements-btn');
			var $reopenButton = $shell.find('.sendy-content-improvements-reopen-btn');
			var $panel = $shell.next('.sendy-content-improvements-panel');
			var $content = $panel.find('.sendy-content-improvements-content');
			var $close = $panel.find('.sendy-content-improvements-close');
			var originalButtonHtml = $button.html();
			var endpoint = $shell.data('endpoint');
			var stateEndpoint = $shell.data('stateEndpoint');
			var appId = $shell.data('appId');
			var contentType = $shell.data('contentType');
			var contentId = $shell.data('contentId') || 0;
			var parentId = $shell.data('parentId') || 0;
			var loadingText = $button.data('loadingText') || 'Analyzing...';
			var errorText = $button.data('errorText') || 'Unable to suggest improvements right now.';
			var resuggestLabel = $button.attr('data-label-resuggest') || 'Resuggest improvements';
			var openLastAnalysisLabel = $reopenButton.attr('data-open-label') || 'Open last analysis';
			var closeAnalysisLabel = $reopenButton.attr('data-close-label') || 'Close analysis';

			if (!$button.length || !$panel.length) return;

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

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

			function setOpen(isOpen) {
				if (isOpen) {
					if ($panel.data('closeTimer')) {
						window.clearTimeout($panel.data('closeTimer'));
						$panel.removeData('closeTimer');
					}
					$panel.show();
					window.setTimeout(function() {
						$panel.addClass('sendy-content-improvements-panel-open');
					}, 20);
				} else {
					$panel.removeClass('sendy-content-improvements-panel-open');
					$panel.data('closeTimer', window.setTimeout(function() {
						if (!$panel.hasClass('sendy-content-improvements-panel-open')) $panel.hide();
						$panel.removeData('closeTimer');
					}, 220));
				}
				setReopenButtonLabel(isOpen);
			}

			function saveState(isOpen) {
				if (!stateEndpoint) return;
				$.post(stateEndpoint, {
					app: appId,
					content_type: contentType,
					content_id: contentId,
					parent_id: parentId,
					is_open: isOpen ? 1 : 0
				});
			}

			$button.click(function(e) {
				e.preventDefault();

				if (window.SendyEditorModes && typeof window.SendyEditorModes.syncActiveEditor === 'function') {
					window.SendyEditorModes.syncActiveEditor();
				}

				var html = getFieldValue('#html');
				var plain = getFieldValue('#plain');
				var subject = getFieldValue('#subject');

				setOpen(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: endpoint,
					type: 'POST',
					dataType: 'json',
					timeout: 90000,
					data: {
						app: appId,
						content_type: contentType,
						content_id: contentId,
						parent_id: parentId,
						html: html,
						plain: plain,
						current_subject: subject
					}
				})
				.done(function(response) {
					if (!response || !response.analysis) {
						$content.addClass('alert alert-error').text(errorText);
						return;
					}
					$content.html(response.analysis);
					$reopenButton.show();
					setReopenButtonLabel(true);
					originalButtonHtml = magicButtonHtml(resuggestLabel);
					$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(false);
				saveState(false);
			});

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