(function ($) {
	'use strict';

	function config() {
		return window.rsmRichTextEditor && window.rsmRichTextEditor.editorUi
			? window.rsmRichTextEditor.editorUi
			: {
					mediaRow: false,
					useRsmMedia: true,
			  };
	}

	function editorConfig() {
		return window.rsmRichTextEditor || {};
	}

	/**
	 * Mirror PHP resolve_profile() for SiteOrigin textarea / TinyMCE ids.
	 *
	 * @param {string} editorId
	 * @return {string}
	 */
	function resolveProfileFromEditorId(editorId) {
		var id = String(editorId || '');

		if (!id) {
			return '';
		}

		if (/widget-headline-/i.test(id)) {
			return /-(overline|headline|subheadline)$/i.test(id) ? 'headline' : '';
		}

		if (/widget-features-/i.test(id)) {
			if (/(?:description|popout_content)/i.test(id)) {
				return 'body';
			}
			if (/(?:^|-)title(?:-|_|$|\d)/i.test(id)) {
				return 'headline';
			}
			return '';
		}

		if (/widget-(tabs|accordion)-/i.test(id)) {
			return /(?:items[-_]?content|[-_]content(?:-|_|$|\d))/i.test(id) ? 'body' : '';
		}

		return '';
	}

	function editorIdFromInit(init) {
		if (!init) {
			return '';
		}

		if (init.id) {
			return String(init.id);
		}

		if (init.selector) {
			return String(init.selector).replace(/^#/, '');
		}

		return '';
	}

	function parseExternalPlugins(value) {
		if (!value) {
			return {};
		}

		if (typeof value === 'object') {
			return value;
		}

		if (typeof value === 'string') {
			try {
				var parsed = JSON.parse(value);
				if (typeof parsed === 'string') {
					parsed = JSON.parse(parsed);
				}
				return parsed && typeof parsed === 'object' ? parsed : {};
			} catch (error) {
				return {};
			}
		}

		return {};
	}

	function mergeExternalPlugins(init, profileInit) {
		var external = parseExternalPlugins(init.external_plugins);
		var fromProfile = parseExternalPlugins(profileInit.external_plugins);
		var config = editorConfig();

		Object.keys(fromProfile).forEach(function (key) {
			external[key] = fromProfile[key];
		});

		// Always prefer the versioned URL from inline config (cache-busted on deploy).
		if (config.pluginUrl) {
			external.rsm_rich_text = config.pluginUrl;
		}

		if (Object.keys(external).length) {
			// SiteOrigin passes init straight to tinymce.init(); keep a plain object.
			init.external_plugins = external;
		}
	}

	function ensureRsmRichTextPlugin(init, profileInit) {
		var plugins = String(init.plugins || profileInit.plugins || '');

		if (plugins.indexOf('rsm_rich_text') === -1) {
			init.plugins = plugins ? plugins + ',rsm_rich_text' : 'rsm_rich_text';
		}
	}

	function patchSiteOriginTinyMceInit(init) {
		var editorId = editorIdFromInit(init);
		var profile = resolveProfileFromEditorId(editorId);
		var tinymceInit = editorConfig().tinymceInit || {};
		var profileInit = tinymceInit[profile];

		if (!profile) {
			return;
		}

		if (profileInit) {
			Object.keys(profileInit).forEach(function (key) {
				if (key === 'external_plugins') {
					return;
				}

				if (profileInit[key] !== undefined && profileInit[key] !== null && profileInit[key] !== '') {
					init[key] = profileInit[key];
				}
			});

			mergeExternalPlugins(init, profileInit);
			ensureRsmRichTextPlugin(init, profileInit);
		}

		var contentCssMap = editorConfig().contentCss || {};
		if (contentCssMap[profile]) {
			init.content_css = contentCssMap[profile];
		}

		if (!init.body_class) {
			init.body_class = 'rsmspark-rt-editor rsmspark-rt-root rsmspark-rt-profile-' + profile;
		}

		if (!init.rsm_rt_profile) {
			init.rsm_rt_profile = profile;
		}
	}

	function isRsmProfileTextarea($textarea) {
		var id = $textarea.attr('id') || '';

		if ($textarea.hasClass('rsmspark-rt-editor')) {
			return true;
		}

		if (/^rsmspark-rt-block-(body|headline)-/i.test(id)) {
			return true;
		}

		return resolveProfileFromEditorId(id) !== '';
	}

	function isSocialProfileWrap($wrap) {
		if ($wrap.find('textarea.rsmspark-rt-editor, textarea.rsmspark-rt-profile-headline, textarea.rsmspark-rt-profile-body').length > 0) {
			return true;
		}

		if ($wrap.find('textarea[id^="rsmspark-rt-block-"]').length > 0) {
			return true;
		}

		return $wrap.find('textarea.wp-editor-area, textarea.siteorigin-widget-input').filter(function () {
			return isRsmProfileTextarea($(this));
		}).length > 0;
	}

	function ensureRsmMediaButton($wrap, editorId) {
		var ui = config();

		if (!ui.useRsmMedia || typeof mediaHostWindow().rsmMediaOpenFrame !== 'function') {
			return;
		}

		var $existing = $wrap.find('.rsmspark-rt-insert-media').first();

		if ($existing.length) {
			if (editorId) {
				$existing.attr('data-editor-id', editorId);
			}
			return;
		}

		var $media = $wrap.find('.wp-media-buttons').first();

		if (!$media.length) {
			var $tools = $wrap.find('.wp-editor-tools').first();
			if (!$tools.length) {
				return;
			}
			$media = $('<div class="wp-media-buttons"></div>');
			$tools.prepend($media);
		}

		var label = 'Add Media';
		var profiles = editorConfig().profiles || {};

		Object.keys(profiles).some(function (key) {
			if (profiles[key] && profiles[key].i18n && profiles[key].i18n.insertMedia) {
				label = profiles[key].i18n.insertMedia;
				return true;
			}
			return false;
		});

		$(
			'<button type="button" class="button rsmspark-rt-insert-media rsmspark-cw-button--brand"></button>'
		)
			.attr('data-editor-id', editorId || '')
			.text(label)
			.appendTo($media);
	}

	function syncMediaRow($context) {
		var ui = config();

		$context.find('.wp-editor-wrap, .so-tinymce-field, .rsmspark-rt-block-editor-wrap').each(function () {
			var $wrap = $(this);

			if (!isSocialProfileWrap($wrap)) {
				return;
			}

			var $media = $wrap.find('.wp-media-buttons').first();
			var editorId = $wrap.find('textarea[id]').first().attr('id') || '';

			if (!ui.mediaRow && !ui.useRsmMedia) {
				$media.hide();
				$wrap.find('.insert-media, #content-add_media').remove();
				return;
			}

			if (ui.useRsmMedia) {
				$wrap.find('.insert-media, #content-add_media').hide();

				if (editorId) {
					ensureRsmMediaButton($wrap, editorId);
				}

				$media.show();
				return;
			}

			$media.show();
		});
	}

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

		var alt = attachment.alt ? String(attachment.alt) : '';
		var html =
			'<img src="' +
			attachment.url +
			'" alt="' +
			alt.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);
		}
	}

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

		var host = mediaHostWindow();

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

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

	function mediaHostWindow() {
		var candidates = [window];

		try {
			if (window.top && window.top !== window) {
				candidates.unshift(window.top);
			}
			if (window.parent && window.parent !== window) {
				candidates.push(window.parent);
			}
		} catch (error) {
			/* Cross-origin frame — ignore. */
		}

		for (var i = 0; i < candidates.length; i++) {
			if (
				candidates[i] &&
				typeof candidates[i].rsmMediaOpenFrame === 'function'
			) {
				return candidates[i];
			}
		}

		return window;
	}

	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 bindEvents() {
		$(document).on('wp-before-tinymce-init', function (event, init) {
			patchSiteOriginTinyMceInit(init || {});
		});

		$(document).on('rsmspark-rt-block-editor-init', function () {
			syncMediaRow($(document));
		});

		$(document).on('click', '.rsmspark-rt-insert-media', function (event) {
			event.preventDefault();
			openRsmMedia(editorIdFromButton($(this)));
		});

		$(document).on(
			'click',
			'.wp-editor-wrap:has(textarea.rsmspark-rt-editor) .insert-media, .so-tinymce-field:has(textarea.rsmspark-rt-editor) .insert-media',
			function (event) {
				if (!config().useRsmMedia) {
					return;
				}

				if (typeof mediaHostWindow().rsmMediaOpenFrame !== 'function') {
					return;
				}

				event.preventDefault();
				event.stopImmediatePropagation();
				openRsmMedia(editorIdFromButton($(this)));
			}
		);
	}

	function observeDom() {
		syncMediaRow($(document));

		if (typeof MutationObserver === 'undefined') {
			return;
		}

		var pending = null;
		var observer = new MutationObserver(function () {
			if (pending) {
				window.clearTimeout(pending);
			}

			pending = window.setTimeout(function () {
				pending = null;
				syncMediaRow($(document));
			}, 120);
		});

		var roots = document.querySelectorAll(
			'.so-panels-dialog, .widget-panel, .wp-editor-wrap, .rsmspark-rt-block-modal, #poststuff'
		);

		if (!roots.length) {
			observer.observe(document.body, { childList: true, subtree: true });
			return;
		}

		roots.forEach(function (root) {
			observer.observe(root, { childList: true, subtree: true });
		});
	}

	$(function () {
		bindEvents();
		observeDom();
		setTimeout(function () {
			syncMediaRow($(document));
		}, 500);
	});
})(jQuery);
