(function ($, wp) {
	'use strict';

	if (!wp || !wp.editor || typeof wp.editor.initialize !== 'function') {
		return;
	}

	var initEditor = function ($textarea) {
		if (!$textarea.length || $textarea.data('gutenbergReady')) {
			return;
		}

		var id = 'cartcue-editor-' + Math.random().toString(36).slice(2, 10);
		var label = $textarea.attr('data-gutenberg-label') || 'Content';

		$textarea.attr('id', id);
		$textarea.data('gutenbergReady', true);

		wp.editor.initialize(id, {
			mediaButtons: false,
			tinymce: {
				wpautop: true,
				branding: false,
				block_formats: 'Paragraph=p;Heading 2=h2;Heading 3=h3;Heading 4=h4',
			},
			quicktags: true,
		});

		var $wrap = $('#wp-' + id + '-wrap');
		if ($wrap.length) {
			$wrap.attr('data-cartcue-gutenberg', '1');
			$wrap.prepend('<div class="ap-field-label" style="margin-bottom:8px;">' + label + '</div>');
		}
	};

	var initAll = function () {
		$('.ap-gutenberg-source').each(function () {
			initEditor($(this));
		});
	};

	$(initAll);

	var observer = new MutationObserver(function () {
		initAll();
	});

	observer.observe(document.body, { childList: true, subtree: true });
})(window.jQuery, window.wp);
