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

	function setMessage($shell, type, message) {
		var $message = $shell.find('.sendy-ai-subject-message');
		if (!$message.length) return;

		if (!message) {
			$message.hide().removeClass('alert-error alert-success alert-info').text('');
			return;
		}

		$message
			.removeClass('alert-error alert-success alert-info')
			.addClass(type === 'success' ? 'alert-success' : type === 'info' ? 'alert-info' : 'alert-error')
			.text(message)
			.show();
	}

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

	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 generate a subject line right now.';
	}

	$(document).ready(function() {
		$('.sendy-ai-subject-shell').each(function() {
			var $shell = $(this);
			var $button = $shell.find('.sendy-ai-subject-btn');
			var $options = $shell.find('.sendy-ai-subject-option, .sendy-ai-subject-custom-option');

			if (!$button.length) return;

			function generateSubject(promptMode, customPrompt) {
				var endpoint = $button.data('endpoint');
				var subjectSelector = $button.data('subjectSelector');
				var plainSelector = $button.data('plainSelector') || '#plain';
				var htmlSelector = $button.data('htmlSelector') || '#html';
				var appId = $button.data('appId');
				var generatingLabel = $button.data('generatingLabel') || 'Generating...';
				var generatingText = $button.data('generatingText') || 'Generating subject line...';
				var emptyText = $button.data('emptyText') || 'Add some email content before generating a subject line.';
				var successText = $button.data('successText') || 'Subject line generated.';
				var genericErrorText = $button.data('genericErrorText') || 'Unable to generate a subject line right now.';
				var $subjectField = $(subjectSelector);
				var originalHtml = $button.html();

				if (!$subjectField.length) return;

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

				var html = getFieldValue(htmlSelector);
				var plain = getFieldValue(plainSelector);

				if ($.trim(html) === '' && $.trim(plain) === '') {
					setMessage($shell, 'error', emptyText);
					return;
				}

				setMessage($shell, 'info', generatingText);
				$button.prop('disabled', true).html('<i class="icon icon-refresh"></i> <span class="sendy-ai-rainbow-text">' + generatingLabel + '</span>');
				$options.addClass('disabled');

				$.ajax({
					url: endpoint,
					type: 'POST',
					dataType: 'json',
					timeout: 45000,
					data: {
						app: appId,
						html: html,
						plain: plain,
						current_subject: $subjectField.val() || '',
						prompt_mode: promptMode || 'compelling',
						custom_prompt: customPrompt || ''
					}
				})
				.done(function(response) {
					if (!response || !response.subject) {
						setMessage($shell, 'error', genericErrorText);
						return;
					}

					$subjectField.val(response.subject).trigger('change').focus().select();
					setMessage($shell, 'success', successText);
				})
				.fail(function(xhr) {
					setMessage($shell, 'error', parseError(xhr, genericErrorText));
				})
				.always(function() {
					$button.prop('disabled', false).html(originalHtml);
					$options.removeClass('disabled');
				});
			}

			$shell.find('.sendy-ai-subject-option').click(function(e) {
				e.preventDefault();
				if ($(this).hasClass('disabled')) return;

				generateSubject($(this).data('promptMode') || 'compelling', '');
			});

			$shell.find('.sendy-ai-subject-custom-option').click(function(e) {
				e.preventDefault();
				if ($(this).hasClass('disabled')) return;

				var modalSelector = $button.data('customModal');
				var $modal = modalSelector ? $(modalSelector) : $();
				if ($modal.length && typeof $modal.modal === 'function') {
					$modal.modal('show');
					$modal.find('.sendy-ai-subject-custom-prompt').focus();
				}
			});

			$shell.find('.sendy-ai-subject-custom-generate').click(function(e) {
				e.preventDefault();

				var $modal = $(this).closest('.sendy-ai-subject-custom-modal');
				var customPrompt = $modal.find('.sendy-ai-subject-custom-prompt').val() || '';

				if ($modal.length && typeof $modal.modal === 'function') $modal.modal('hide');
				generateSubject('custom', customPrompt);
			});
		});
	});
})(window, window.jQuery);
