/**
 * SmartyPress AI TinyMCE Plugin
 * 
 * Adds Magic Wand button to Classic Editor toolbar
 */
(function() {
	'use strict';

	var __ = wp.i18n.__;

	/**
	 * Get selected content as both HTML and plain text
	 * Captures parent block element (h1-h6, p, etc.) if entire content is selected
	 */
	function stripSmartyPressInternalClasses(html) {
		if (!html) {
			return '';
		}

		var wrapper = document.createElement('div');
		wrapper.innerHTML = html;
		wrapper.querySelectorAll('[class]').forEach(function(node) {
			var classes = (node.getAttribute('class') || '').split(/\s+/).filter(function(className) {
				return className && className.indexOf('smartypress-') !== 0;
			});

			if (classes.length) {
				node.setAttribute('class', classes.join(' '));
			} else {
				node.removeAttribute('class');
			}
		});

		return wrapper.innerHTML;
	}

	function getSelectedContent(editor) {
		var htmlContent = editor.selection.getContent({format: 'html'}) || '';
		var textContent = editor.selection.getContent({format: 'text'}) || '';
		
		// If HTML is empty or equals plain text, check parent element
		if (!htmlContent || htmlContent === textContent) {
			var node = editor.selection.getNode();
			// Preserve structural blocks, but do not promote plain paragraph selections to <p> wrappers.
			var blockTags = ['H1','H2','H3','H4','H5','H6','BLOCKQUOTE','LI','TD','TH'];
			
			if (node && blockTags.indexOf(node.nodeName) !== -1) {
				// Check if entire text inside element is selected
				var nodeText = (node.textContent || node.innerText || '').trim();
				if (nodeText === textContent.trim()) {
					// Entire element content is selected - include the element itself
					htmlContent = node.outerHTML;
				}
			}
		}
		
		htmlContent = stripSmartyPressInternalClasses(htmlContent);
		
		return { html: htmlContent, text: textContent };
	}

	tinymce.PluginManager.add('smartypress_ai', function(editor) {
		var pluginUrl = (window.smartypressAI || {}).pluginUrl || '';

		/**
		 * Magic Wand button (icon-only, dropdown menu)
		 */
		editor.addButton('smartypress_wand', {
			type: 'menubutton',
			tooltip: __('Magic Wand', 'smartypress-ai-engine'),
			image: pluginUrl + 'assets/images/wand.png',
			classes: 'smartypress-ai-classic-wand-btn',
			menu: [
				{
					text: __('Rewrite', 'smartypress-ai-engine'),
					onclick: function() {
						var sel = getSelectedContent(editor);
						if (!sel.text) {
							window.SmartyPressClassicEditor.showNotice(__('Please select some text first.', 'smartypress-ai-engine'));
							return;
						}
						window.SmartyPressClassicEditor.openWandModal('rewrite', {
							text: sel.text,
							htmlContent: sel.html,
							editor: editor,
							action: 'enhanceText',
							wandTemplateId: 'rewrite'
						});
					}
				},
				{
					text: __('Expand', 'smartypress-ai-engine'),
					onclick: function() {
						var sel = getSelectedContent(editor);
						if (!sel.text) {
							window.SmartyPressClassicEditor.showNotice(__('Please select some text first.', 'smartypress-ai-engine'));
							return;
						}
						window.SmartyPressClassicEditor.openWandModal('expand', {
							text: sel.text,
							htmlContent: sel.html,
							editor: editor,
							action: 'longerText',
							wandTemplateId: 'expand'
						});
					}
				},
				{
					text: __('Fix Grammar & Spelling', 'smartypress-ai-engine'),
					onclick: function() {
						var sel = getSelectedContent(editor);
						if (!sel.text) {
							window.SmartyPressClassicEditor.showNotice(__('Please select some text first.', 'smartypress-ai-engine'));
							return;
						}
						window.SmartyPressClassicEditor.openWandModal('fix_grammar', {
							text: sel.text,
							htmlContent: sel.html,
							editor: editor,
							action: 'correctText',
							wandTemplateId: 'fix_grammar'
						});
					}
				},
				{
					text: __('Summarize', 'smartypress-ai-engine'),
					onclick: function() {
						var sel = getSelectedContent(editor);
						if (!sel.text) {
							window.SmartyPressClassicEditor.showNotice(__('Please select some text first.', 'smartypress-ai-engine'));
							return;
						}
						window.SmartyPressClassicEditor.openWandModal('summarize', {
							text: sel.text,
							htmlContent: sel.html,
							editor: editor,
							action: 'shorterText',
							wandTemplateId: 'summarize'
						});
					}
				},
				{
					text: __('Simplify Tone', 'smartypress-ai-engine'),
					onclick: function() {
						var sel = getSelectedContent(editor);
						if (!sel.text) {
							window.SmartyPressClassicEditor.showNotice(__('Please select some text first.', 'smartypress-ai-engine'));
							return;
						}
						window.SmartyPressClassicEditor.openWandModal('simplify', {
							text: sel.text,
							htmlContent: sel.html,
							editor: editor,
							action: 'enhanceText',
							wandTemplateId: 'simplify'
						});
					}
				},
				{
					text: __('Translate', 'smartypress-ai-engine'),
					onclick: function() {
						var sel = getSelectedContent(editor);
						if (!sel.text) {
							window.SmartyPressClassicEditor.showNotice(__('Please select some text first.', 'smartypress-ai-engine'));
							return;
						}
						window.SmartyPressClassicEditor.openWandModal('translate', {
							text: sel.text,
							htmlContent: sel.html,
							editor: editor,
							action: 'translateText',
							wandTemplateId: 'translate',
							showLanguageField: true
						});
					}
				}
			]
		});
	});
})();
