(function ($) {
	'use strict';

	function editorIdFromButton($button) {
		var $scope = $button.closest('.wp-editor-wrap, .rsmspark-rt-block-editor-wrap, .so-tinymce-field');
		var $textarea = $scope.find('textarea[id]').first();
		var textareaId = $textarea.attr('id') || '';

		if (textareaId && window.tinymce && tinymce.get(textareaId)) {
			return textareaId;
		}

		var declared =
			$button.attr('data-editor-id') ||
			$button.attr('data-editor') ||
			$button.data('editorId') ||
			$button.data('editor') ||
			'';

		if (declared && window.tinymce && tinymce.get(declared)) {
			return declared;
		}

		return textareaId || declared || 'content';
	}

	function insertImageHtml(editorId, attachment) {
		if (!attachment || !attachment.url) {
			return;
		}

		var alt = attachment.alt ? String(attachment.alt) : '';
		var title = attachment.title ? String(attachment.title) : '';
		var html =
			'<img src="' +
			attachment.url +
			'" alt="' +
			alt.replace(/"/g, '&quot;') +
			'"' +
			(title ? ' title="' + title.replace(/"/g, '&quot;') + '"' : '') +
			' class="alignnone size-medium" />';

		if (window.tinymce && tinymce.get(editorId)) {
			tinymce.get(editorId).insertContent(html);
			return;
		}

		if (window.send_to_editor) {
			window.send_to_editor(html);
		}
	}

	$(document).on('click', '.rsmspark-rt-insert-media:not(.rsmspark-rt-block-media-button)', function (event) {
		event.preventDefault();

		var editorId = editorIdFromButton($(this));
		var mediaOpts = {
			title: 'Insert image',
			button: { text: 'Insert into content' },
			library: { type: 'image' },
			multiple: false,
		};

		if (typeof window.rsmMediaOpenFrame === 'function') {
			window.rsmMediaOpenFrame(mediaOpts, function (attachments) {
				if (attachments && attachments[0]) {
					insertImageHtml(editorId, attachments[0]);
				}
			});
			return;
		}

		if (typeof wp !== 'undefined' && wp.media) {
			var frame = wp.media(mediaOpts);
			frame.on('select', function () {
				var model = frame.state().get('selection').first();
				if (model) {
					insertImageHtml(editorId, model.toJSON());
				}
			});
			frame.open();
		}
	});
})(jQuery);
