/**
 * SmartyPress AI Classic Editor Modal
 * 
 * Replicates Gutenberg modal styling for Classic Editor
 */
(function() {
	'use strict';

	var apiFetch = wp.apiFetch;
	var __ = wp.i18n.__;

	window.SmartyPressClassicEditor = window.SmartyPressClassicEditor || {};

	/**
	 * Get default prompts (with translations)
	 */
	function getDefaultPrompts() {
		return {
			title: __("Generate a compelling and SEO-optimized title for the blog post based on the content below. The title must be in {LANGUAGE}. Return ONLY the title text.\n\nPost content:\n{CONTEXT}", 'smartypress-ai-engine'),
			content: __("Write a comprehensive blog post with the title: '{TITLE}'. The content must be in {LANGUAGE}. Use Markdown formatting (## for headings, **bold**, *italic*, lists). Do NOT use HTML tags. {CONTEXT}", 'smartypress-ai-engine'),
			excerpt: __("Create a concise summary (1-2 sentences) of the following content. Write in {LANGUAGE}:\n\n{CONTENT}", 'smartypress-ai-engine'),
			rewrite: __("Rewrite this to improve clarity and engagement. Write in {LANGUAGE}. Return ONLY the rewritten text.\n\n{TEXT}", 'smartypress-ai-engine'),
			expand: __("Expand on the following point with more details and examples. Write in {LANGUAGE}. Return ONLY the expanded text.\n\n{TEXT}", 'smartypress-ai-engine'),
			fix_grammar: __("Correct any spelling and grammar mistakes in the following text. Write in {LANGUAGE}. Return ONLY the corrected text.\n\n{TEXT}", 'smartypress-ai-engine'),
			summarize: __("Summarize the following text in 3-5 concise sentences while preserving key facts and tone. Write in {LANGUAGE}.\n\n{TEXT}", 'smartypress-ai-engine'),
			simplify: __("Rewrite the following in a friendly, simple tone while preserving meaning and structure. Write in {LANGUAGE}. Return ONLY the rewritten text.\n\n{TEXT}", 'smartypress-ai-engine'),
			translate: __("Translate to {LANGUAGE}: {TEXT}", 'smartypress-ai-engine')
		};
	}

	/**
	 * Get wand template options (with translations)
	 */
	function getWandTemplates() {
		return [
			{ id: 'rewrite', label: __('Rewrite', 'smartypress-ai-engine'), action: 'enhanceText' },
			{ id: 'expand', label: __('Expand', 'smartypress-ai-engine'), action: 'longerText' },
			{ id: 'fix_grammar', label: __('Fix Grammar & Spelling', 'smartypress-ai-engine'), action: 'correctText' },
			{ id: 'summarize', label: __('Summarize', 'smartypress-ai-engine'), action: 'shorterText' },
			{ id: 'simplify', label: __('Simplify Tone', 'smartypress-ai-engine'), action: 'enhanceText' },
			{ id: 'translate', label: __('Translate', 'smartypress-ai-engine'), action: 'translateText' }
		];
	}

	/**
	 * Get modal titles (with translations)
	 */
	function getModalTitles() {
		return {
			title: __('Generate Title', 'smartypress-ai-engine'),
			content: __('Generate Content', 'smartypress-ai-engine'),
			excerpt: __('Generate Excerpt', 'smartypress-ai-engine'),
			categories: __('Suggest Categories', 'smartypress-ai-engine'),
			rewrite: __('Rewrite Text', 'smartypress-ai-engine'),
			expand: __('Expand Text', 'smartypress-ai-engine'),
			fix_grammar: __('Fix Grammar & Spelling', 'smartypress-ai-engine'),
			summarize: __('Summarize Text', 'smartypress-ai-engine'),
			simplify: __('Simplify Tone', 'smartypress-ai-engine'),
			translate: __('Translate Text', 'smartypress-ai-engine')
		};
	}

	/**
	 * Escape HTML
	 */
	function esc(text) {
		var d = document.createElement('div');
		d.textContent = text;
		return d.innerHTML;
	}

	/**
	 * Get config values
	 */
	function getConfig() {
		var config = window.smartypressAI || {};
		var settings = config.settings || {};
		var defaultProvider = settings.default_provider || (config.providers || [])[0] || 'openai';
		return {
			providers: config.providers || ['openai', 'deepseek'],
			providerModels: config.providerModels || {},
			defaultProvider: defaultProvider,
			defaultModel: settings.default_model || settings[defaultProvider + '_model'] || '',
			defaultLanguage: settings.default_language || (config.localeDefaultLanguage || 'English'),
			defaultTemperature: parseFloat(settings.temperature) || 0.7
		};
	}

	/**
	 * Build model options HTML
	 */
	function buildModelOptions(provider, providerModels, defaultModel) {
		var models = providerModels[provider] || {};
		var html = '';
		Object.keys(models).forEach(function(key) {
			var data = models[key];
			var name = typeof data === 'string' ? data : (data.name || key);
			var sel = (defaultModel && key === defaultModel) ? ' selected' : '';
			html += '<option value="' + esc(key) + '"' + sel + '>' + esc(name) + '</option>';
		});
		return html;
	}

	/**
	 * Build template options HTML for wand
	 */
	function buildTemplateOptions() {
		var html = '<option value="">' + esc(__('-- Custom prompt --', 'smartypress-ai-engine')) + '</option>';
		var templates = getWandTemplates();
		templates.forEach(function(t) {
			html += '<option value="' + t.id + '">' + esc(t.label) + '</option>';
		});
		return html;
	}

	/**
	 * Create and show modal
	 */
	function createModal(action, data, isWand) {
		var cfg = getConfig();
		var defaultPrompts = getDefaultPrompts();
		var prompt = defaultPrompts[action] || '';
		var showPrompt = action !== 'categories';
		var modalTitles = getModalTitles();
		var title = modalTitles[action] || __('AI Generation', 'smartypress-ai-engine');

		// Build provider options
		var providerOpts = '';
		cfg.providers.forEach(function(p) {
			var sel = p === cfg.defaultProvider ? ' selected' : '';
			providerOpts += '<option value="' + p + '"' + sel + '>' + p.charAt(0).toUpperCase() + p.slice(1) + '</option>';
		});

		var overlay = document.createElement('div');
		overlay.className = 'smartypress-ce-overlay';
		overlay.innerHTML =
			'<div class="smartypress-ce-modal">' +
				'<div class="smartypress-ce-header">' +
					'<h2>' + esc(title) + '</h2>' +
					'<button class="smartypress-ce-close" type="button"><span class="dashicons dashicons-no-alt"></span></button>' +
				'</div>' +
				'<div class="smartypress-ce-body">' +
					(isWand ? '<div class="smartypress-ce-field"><label>' + esc(__('Template', 'smartypress-ai-engine')) + '</label><select id="sp-ce-template">' + buildTemplateOptions() + '</select></div>' : '') +
					(showPrompt ?
						'<div class="smartypress-ce-field smartypress-ce-prompt-section">' +
							'<label>' + esc(__('Prompt', 'smartypress-ai-engine')) + '</label>' +
							'<textarea id="sp-ce-prompt" rows="5">' + esc(prompt) + '</textarea>' +
							'<div class="smartypress-ce-variables">' +
								(isWand ?
									'<span class="smartypress-ce-var" data-var="{TEXT}">{TEXT}</span>' +
									'<span class="smartypress-ce-var" data-var="{LANGUAGE}">{LANGUAGE}</span>' +
									'<span class="smartypress-ce-var" data-var="{CONTEXT}">{CONTEXT}</span>'
								:
									(action === 'title' ? '<span class="smartypress-ce-var" data-var="{CONTEXT}">{CONTEXT}</span><span class="smartypress-ce-var" data-var="{LANGUAGE}">{LANGUAGE}</span>' :
									 action === 'content' ? '<span class="smartypress-ce-var" data-var="{TITLE}">{TITLE}</span><span class="smartypress-ce-var" data-var="{CONTEXT}">{CONTEXT}</span><span class="smartypress-ce-var" data-var="{LANGUAGE}">{LANGUAGE}</span>' :
									 action === 'excerpt' ? '<span class="smartypress-ce-var" data-var="{CONTENT}">{CONTENT}</span><span class="smartypress-ce-var" data-var="{TITLE}">{TITLE}</span><span class="smartypress-ce-var" data-var="{LANGUAGE}">{LANGUAGE}</span>' : '')
								) +
							'</div>' +
							'<p class="smartypress-ce-help">' + esc(__('Edit the prompt or insert dynamic variables. Ctrl+Enter to generate.', 'smartypress-ai-engine')) + '</p>' +
						'</div>'
					: '<p class="smartypress-ce-description">' + esc(__('AI will analyze your post title and content to suggest the most relevant categories.', 'smartypress-ai-engine')) + '</p>') +
					(data.showLanguageField ?
						'<div class="smartypress-ce-field"><label>' + esc(__('Target Language', 'smartypress-ai-engine')) + '</label><input type="text" id="sp-ce-target-lang" value="" placeholder="' + esc(__('e.g. Russian, German, French', 'smartypress-ai-engine')) + '" /></div>' : '') +
					'<div class="smartypress-ce-accordion">' +
						'<button type="button" class="smartypress-ce-accordion-toggle"><span class="dashicons dashicons-arrow-down-alt2"></span> ' + esc(__('Advanced Settings', 'smartypress-ai-engine')) + '</button>' +
						'<div class="smartypress-ce-accordion-body" style="display:none;">' +
							'<div class="smartypress-ce-settings-grid">' +
								'<div class="smartypress-ce-field"><label>' + esc(__('Provider', 'smartypress-ai-engine')) + '</label><select id="sp-ce-provider">' + providerOpts + '</select></div>' +
								'<div class="smartypress-ce-field"><label>' + esc(__('Model', 'smartypress-ai-engine')) + '</label><select id="sp-ce-model">' + buildModelOptions(cfg.defaultProvider, cfg.providerModels, cfg.defaultModel) + '</select></div>' +
								'<div class="smartypress-ce-field smartypress-ce-temp-field"><label>' + esc(__('Temperature', 'smartypress-ai-engine')) + ' <span id="sp-ce-temp-val">' + cfg.defaultTemperature + '</span></label><input type="range" id="sp-ce-temp" min="0" max="2" step="0.1" value="' + cfg.defaultTemperature + '" /><p class="smartypress-ce-help">' + esc(__('Lower = more focused, Higher = more creative', 'smartypress-ai-engine')) + '</p></div>' +
							'</div>' +
						'</div>' +
					'</div>' +
				'<div class="smartypress-ce-error" style="display:none;"></div>' +
				'<div class="smartypress-ce-loading" style="display:none;"><span class="spinner is-active"></span> ' + esc(__('Generating...', 'smartypress-ai-engine')) + '</div>' +
				'<div class="smartypress-ce-result" style="display:none;">' +
					'<div class="smartypress-ce-diff-view">' +
						'<label><span class="dashicons dashicons-visibility"></span> ' + esc(__('Changes', 'smartypress-ai-engine')) + '</label>' +
						'<div class="smartypress-ce-diff-legend">' +
							'<span class="smartypress-ce-diff-legend-remove">' + esc(__('Removed', 'smartypress-ai-engine')) + '</span>' +
							'<span class="smartypress-ce-diff-legend-add">' + esc(__('Added', 'smartypress-ai-engine')) + '</span>' +
						'</div>' +
						'<div class="smartypress-ce-diff-content"></div>' +
					'</div>' +
				'</div>' +
				'</div>' +
				'<div class="smartypress-ce-footer">' +
					'<button type="button" class="smartypress-ce-btn smartypress-ce-btn-secondary smartypress-ce-cancel">' + esc(__('Cancel', 'smartypress-ai-engine')) + '</button>' +
					'<button type="button" class="smartypress-ce-btn smartypress-ce-btn-primary smartypress-ce-generate">' + esc(__('Generate', 'smartypress-ai-engine')) + '</button>' +
					'<button type="button" class="smartypress-ce-btn smartypress-ce-btn-primary smartypress-ce-apply" style="display:none;">' + esc(__('Apply', 'smartypress-ai-engine')) + '</button>' +
				'</div>' +
			'</div>';

		document.body.appendChild(overlay);

		// --- Bindings ---

		var providerEl = overlay.querySelector('#sp-ce-provider');
		var modelEl = overlay.querySelector('#sp-ce-model');
		var tempEl = overlay.querySelector('#sp-ce-temp');
		var tempVal = overlay.querySelector('#sp-ce-temp-val');
		var promptEl = overlay.querySelector('#sp-ce-prompt');
		var templateEl = overlay.querySelector('#sp-ce-template');
		var targetLangEl = overlay.querySelector('#sp-ce-target-lang');

		// Provider change -> update models
		if (providerEl) {
			providerEl.addEventListener('change', function() {
				// Only apply default model if switching back to default provider
				var selectedModel = (this.value === cfg.defaultProvider) ? cfg.defaultModel : '';
				modelEl.innerHTML = buildModelOptions(this.value, cfg.providerModels, selectedModel);
			});
		}

		// Temperature display
		if (tempEl) {
			tempEl.addEventListener('input', function() {
				tempVal.textContent = this.value;
			});
		}

		// Template change -> update prompt
		if (templateEl) {
			templateEl.addEventListener('change', function() {
				var id = this.value;
				var prompts = getDefaultPrompts();
				if (id && prompts[id]) {
					promptEl.value = prompts[id];
				}
			});

			// Auto-select template if wandTemplateId is provided
			if (isWand && data.wandTemplateId) {
				templateEl.value = data.wandTemplateId;
				if (defaultPrompts[data.wandTemplateId]) {
					promptEl.value = defaultPrompts[data.wandTemplateId];
				}
			}
		}

		// Variable tags
		overlay.querySelectorAll('.smartypress-ce-var').forEach(function(el) {
			el.addEventListener('click', function() {
				if (!promptEl) return;
				var v = this.getAttribute('data-var');
				var start = promptEl.selectionStart || promptEl.value.length;
				var end = promptEl.selectionEnd || promptEl.value.length;
				promptEl.value = promptEl.value.substring(0, start) + v + promptEl.value.substring(end);
				promptEl.focus();
				var pos = start + v.length;
				promptEl.setSelectionRange(pos, pos);
			});
		});

		// Accordion toggle
		var accToggle = overlay.querySelector('.smartypress-ce-accordion-toggle');
		var accBody = overlay.querySelector('.smartypress-ce-accordion-body');
		if (accToggle) {
			accToggle.addEventListener('click', function() {
				var open = accBody.style.display !== 'none';
				accBody.style.display = open ? 'none' : 'block';
				var icon = this.querySelector('.dashicons');
				icon.className = open ? 'dashicons dashicons-arrow-down-alt2' : 'dashicons dashicons-arrow-up-alt2';
			});
		}

		// Ctrl+Enter
		if (promptEl) {
			promptEl.addEventListener('keydown', function(e) {
				if (e.key === 'Enter' && e.ctrlKey) {
					e.preventDefault();
					overlay.querySelector('.smartypress-ce-generate').click();
				}
			});
		}

		// Close handlers
		function closeModal() { overlay.remove(); }
		overlay.querySelector('.smartypress-ce-close').addEventListener('click', closeModal);
		overlay.querySelector('.smartypress-ce-cancel').addEventListener('click', closeModal);
		overlay.addEventListener('click', function(e) { if (e.target === overlay) closeModal(); });

		// Generate handler
		overlay.querySelector('.smartypress-ce-generate').addEventListener('click', function() {
			if (isWand) {
				doWandGenerate(overlay, action, data);
			} else {
				doGenerate(overlay, action, data);
			}
		});

		// Focus prompt
		if (promptEl) {
			setTimeout(function() { promptEl.focus(); }, 100);
		}

		return overlay;
	}

	/**
	 * AI Writer generation
	 */
	function doGenerate(overlay, action, data) {
		var cfg = getConfig();
		var promptEl = overlay.querySelector('#sp-ce-prompt');
		var provider = overlay.querySelector('#sp-ce-provider').value;
		var model = overlay.querySelector('#sp-ce-model').value;
		var temp = parseFloat(overlay.querySelector('#sp-ce-temp').value);

		showLoading(overlay, true);

		var reqData = {};

		var titleEl = document.getElementById('title');
		var excerptEl = document.getElementById('excerpt');

		switch (action) {
			case 'title':
				reqData = { context: data.context, provider: provider, model: model, temperature: temp, prompt_template: promptEl ? promptEl.value : '', language: cfg.defaultLanguage, current_title: titleEl ? titleEl.value : '' };
				break;
			case 'content':
				reqData = { title: data.title, context: data.context, provider: provider, model: model, temperature: temp, prompt_template: promptEl ? promptEl.value : '', language: cfg.defaultLanguage };
				break;
			case 'excerpt':
				reqData = { content: data.content, provider: provider, model: model, temperature: temp, prompt_template: promptEl ? promptEl.value : '', language: cfg.defaultLanguage, current_excerpt: excerptEl ? excerptEl.value : '' };
				break;
			case 'categories':
				reqData = { title: data.title, content: data.content, provider: provider, language: cfg.defaultLanguage };
				break;
		}

		var endpoint = action === 'categories' ? '/smartypress/v1/generate-categories' :
					   action === 'title' ? '/smartypress/v1/generate-title' :
					   action === 'content' ? '/smartypress/v1/generate-content' :
					   '/smartypress/v1/generate-excerpt';

			// Capture original text for compare view
		var originalText = '';
		if (action === 'title') {
			originalText = titleEl ? titleEl.value : '';
		} else if (action === 'excerpt') {
			originalText = excerptEl ? excerptEl.value : '';
		}
		// For 'content' and 'categories', originalText stays empty (new content mode)

		apiFetch({ path: endpoint, method: 'POST', data: reqData })
			.then(function(result) {
				showLoading(overlay, false);
				if (result && result.success) {
					var text = action === 'title' ? result.title :
							   action === 'content' ? result.content :
							   action === 'excerpt' ? result.excerpt :
							   action === 'categories' ? result.categories.join(', ') : '';

					showResult(overlay, text, originalText);

					overlay.querySelector('.smartypress-ce-apply').onclick = function() {
						applyResult(action, result, data.editor);
						overlay.remove();
					};
				} else {
					showError(overlay, result.error || __('Generation failed', 'smartypress-ai-engine'));
				}
			})
			.catch(function(err) {
				showLoading(overlay, false);
				showError(overlay, err.message || __('An error occurred', 'smartypress-ai-engine'));
			});
	}

	/**
	 * Wand generation
	 */
	function doWandGenerate(overlay, wandAction, data) {
		var cfg = getConfig();
		var promptEl = overlay.querySelector('#sp-ce-prompt');
		var provider = overlay.querySelector('#sp-ce-provider').value;
		var model = overlay.querySelector('#sp-ce-model').value;
		var temp = parseFloat(overlay.querySelector('#sp-ce-temp').value);
		var targetLangEl = overlay.querySelector('#sp-ce-target-lang');

		// Determine API action from template selection or data
		var templateEl = overlay.querySelector('#sp-ce-template');
		var apiAction = data.action;
		if (templateEl && templateEl.value) {
			var templates = getWandTemplates();
			var tpl = templates.find(function(t) { return t.id === templateEl.value; });
			if (tpl) apiAction = tpl.action;
		}

		var language = cfg.defaultLanguage;
		if (targetLangEl && targetLangEl.value) {
			language = targetLangEl.value;
		} else if (data.language) {
			language = data.language;
		}

		showLoading(overlay, true);

		// Send HTML content so the AI can preserve formatting
		var textToSend = data.htmlContent || data.text;

		apiFetch({
			path: '/smartypress/v1/wand',
			method: 'POST',
			data: {
				action: apiAction,
				data: {
					text: textToSend,
					prompt: promptEl ? promptEl.value : '',
					provider: provider,
					model: model,
					temperature: temp,
					language: language
				}
			}
		})
		.then(function(result) {
			showLoading(overlay, false);
			if (result && result.success) {
				var generatedText = result.result || '';
				// Pass original HTML content for compare view
				showResult(overlay, generatedText, data.htmlContent || data.text || '');

				overlay.querySelector('.smartypress-ce-apply').onclick = function() {
					// Insert as HTML to preserve formatting
					data.editor.selection.setContent(generatedText);
					overlay.remove();
				};
			} else {
				showError(overlay, result.error || __('Generation failed', 'smartypress-ai-engine'));
			}
		})
		.catch(function(err) {
			showLoading(overlay, false);
			showError(overlay, err.message || __('An error occurred', 'smartypress-ai-engine'));
		});
	}

	/**
	 * Apply result to editor
	 */
	function applyResult(action, result, editor) {
		if (action === 'title') {
			var titleField = document.getElementById('title');
			if (titleField && result.title) titleField.value = result.title;
		} else if (action === 'content') {
			if (result.content) editor.setContent(result.content);
		} else if (action === 'excerpt') {
			var excerptField = document.getElementById('excerpt');
			if (excerptField && result.excerpt) {
				excerptField.value = result.excerpt;
				// Also update TinyMCE if active (WooCommerce uses TinyMCE for excerpt)
				if (typeof tinymce !== 'undefined' && tinymce.get('excerpt')) {
					tinymce.get('excerpt').setContent(result.excerpt);
				}
			}
		} else if (action === 'categories') {
			if (result.categories && Array.isArray(result.categories)) {
				result.categories.forEach(function(catId) {
					var cb = document.getElementById('in-category-' + catId);
					if (cb) cb.checked = true;
				});
			}
		}
	}

	function showLoading(overlay, show) {
		overlay.querySelector('.smartypress-ce-loading').style.display = show ? 'flex' : 'none';
		overlay.querySelector('.smartypress-ce-error').style.display = 'none';
		overlay.querySelector('.smartypress-ce-result').style.display = 'none';
		overlay.querySelector('.smartypress-ce-generate').disabled = show;
		if (show) {
			overlay.querySelector('.smartypress-ce-generate').style.display = 'inline-flex';
			overlay.querySelector('.smartypress-ce-apply').style.display = 'none';
			// Restore form elements hidden by showResult
			var formEls = overlay.querySelectorAll('.smartypress-ce-field, .smartypress-ce-prompt-section, .smartypress-ce-accordion, .smartypress-ce-description');
			formEls.forEach(function(el) { el.style.display = ''; });
		}
	}

	function showError(overlay, msg) {
		var el = overlay.querySelector('.smartypress-ce-error');
		el.textContent = msg;
		el.style.display = 'block';
		overlay.querySelector('.smartypress-ce-generate').disabled = false;
	}

	/**
	 * Simple word-level diff algorithm
	 * Returns array of [type, text] where type: -1=remove, 0=keep, 1=add
	 */
	function computeWordDiff(oldText, newText) {
		// Strip HTML tags for clean comparison
		var tmp = document.createElement('div');
		tmp.innerHTML = oldText;
		var plainOld = tmp.textContent || tmp.innerText || '';
		tmp.innerHTML = newText;
		var plainNew = tmp.textContent || tmp.innerText || '';

		// Tokenize into words (preserving whitespace)
		var oldWords = plainOld.match(/\S+|\s+/g) || [];
		var newWords = plainNew.match(/\S+|\s+/g) || [];

		// LCS-based diff using dynamic programming
		var m = oldWords.length;
		var n = newWords.length;
		
		// Build LCS table
		var dp = [];
		for (var i = 0; i <= m; i++) {
			dp[i] = [];
			for (var j = 0; j <= n; j++) {
				if (i === 0 || j === 0) {
					dp[i][j] = 0;
				} else if (oldWords[i - 1] === newWords[j - 1]) {
					dp[i][j] = dp[i - 1][j - 1] + 1;
				} else {
					dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
				}
			}
		}

		// Backtrack to find diff
		var result = [];
		i = m;
		var j = n;
		while (i > 0 || j > 0) {
			if (i > 0 && j > 0 && oldWords[i - 1] === newWords[j - 1]) {
				result.unshift([0, oldWords[i - 1]]);
				i--;
				j--;
			} else if (j > 0 && (i === 0 || dp[i][j - 1] >= dp[i - 1][j])) {
				result.unshift([1, newWords[j - 1]]);
				j--;
			} else {
				result.unshift([-1, oldWords[i - 1]]);
				i--;
			}
		}

		// Merge consecutive same-type entries
		var merged = [];
		for (var k = 0; k < result.length; k++) {
			if (merged.length > 0 && merged[merged.length - 1][0] === result[k][0]) {
				merged[merged.length - 1][1] += result[k][1];
			} else {
				merged.push([result[k][0], result[k][1]]);
			}
		}

		return merged;
	}

	/**
	 * Convert diff array to HTML with colored spans
	 */
	function diffToHtml(diffs) {
		var html = '';
		for (var i = 0; i < diffs.length; i++) {
			var type = diffs[i][0];
			var text = esc(diffs[i][1]);
			if (type === 1) {
				html += '<span class="smartypress-ce-diff-add">' + text + '</span>';
			} else if (type === -1) {
				html += '<span class="smartypress-ce-diff-remove">' + text + '</span>';
			} else {
				html += text;
			}
		}
		return html;
	}

	function showResult(overlay, newText, originalText) {
		var resultEl = overlay.querySelector('.smartypress-ce-result');
		var diffContent = overlay.querySelector('.smartypress-ce-diff-content');
		var diffLegend = overlay.querySelector('.smartypress-ce-diff-legend');

		if (originalText && originalText.trim()) {
			// Diff mode: compute and show inline diff
			var diffs = computeWordDiff(originalText, newText);
			diffContent.innerHTML = '<div style="white-space:pre-wrap;">' + diffToHtml(diffs) + '</div>';
			if (diffLegend) diffLegend.style.display = 'flex';
		} else {
			// New content mode: show plain text
			diffContent.innerHTML = '<div style="white-space:pre-wrap;">' + esc(newText) + '</div>';
			if (diffLegend) diffLegend.style.display = 'none';
		}

		// Hide form elements to focus on diff view
		var formEls = overlay.querySelectorAll('.smartypress-ce-field, .smartypress-ce-prompt-section, .smartypress-ce-accordion, .smartypress-ce-description, .smartypress-ce-help');
		formEls.forEach(function(el) { el.style.display = 'none'; });

		resultEl.style.display = 'block';
		overlay.querySelector('.smartypress-ce-generate').style.display = 'none';
		overlay.querySelector('.smartypress-ce-apply').style.display = 'inline-flex';
	}

	/**
	 * Show notice
	 */
	window.SmartyPressClassicEditor.showNotice = function(msg) {
		var notice = document.createElement('div');
		notice.className = 'smartypress-ce-notice';
		notice.textContent = msg;
		document.body.appendChild(notice);
		setTimeout(function() { notice.remove(); }, 3000);
	};

	/**
	 * Open AI Writer modal
	 */
	window.SmartyPressClassicEditor.openModal = function(action, data) {
		createModal(action, data, false);
	};

	/**
	 * Open Magic Wand modal
	 */
	window.SmartyPressClassicEditor.openWandModal = function(wandAction, data) {
		createModal(wandAction, data, true);
	};

	/**
	 * Initialize AI Writer button handlers (for PHP-rendered button)
	 */
	function initAIWriterButton() {
		var btn = document.getElementById('smartypress-ai-writer-btn');
		var dropdown = document.getElementById('smartypress-ai-writer-dropdown');

		if (!btn || !dropdown) {
			return false;
		}

		// Prevent double initialization
		if (btn.dataset.initialized === 'true') {
			return true;
		}
		btn.dataset.initialized = 'true';

		// Toggle dropdown on button click
		btn.addEventListener('click', function(e) {
			e.preventDefault();
			e.stopPropagation();
			var isVisible = dropdown.style.display !== 'none';
			dropdown.style.display = isVisible ? 'none' : 'block';
		});

		// Handle dropdown item clicks
		dropdown.addEventListener('click', function(e) {
			var target = e.target;
			if (target.tagName !== 'A') return;
			
			e.preventDefault();
			e.stopPropagation();
			var action = target.getAttribute('data-action');
			if (!action) return;
			dropdown.style.display = 'none';

			// Get TinyMCE editor instance
			var editor = typeof tinymce !== 'undefined' ? tinymce.get('content') : null;
			var content = editor ? editor.getContent({format: 'text'}) : '';
			var titleEl = document.getElementById('title');
			var title = titleEl ? titleEl.value : '';

			if (action === 'title') {
				window.SmartyPressClassicEditor.openModal('title', { context: content || 'Generate a blog post title', editor: editor });
			} else if (action === 'content') {
				window.SmartyPressClassicEditor.openModal('content', { title: title, context: content, editor: editor });
			} else if (action === 'excerpt') {
				window.SmartyPressClassicEditor.openModal('excerpt', { content: content, editor: editor });
			} else if (action === 'categories') {
				window.SmartyPressClassicEditor.openModal('categories', { title: title, content: content, editor: editor });
			}
		});

		// Close dropdown when clicking outside
		document.addEventListener('click', function(e) {
			if (!btn.contains(e.target) && !dropdown.contains(e.target)) {
				dropdown.style.display = 'none';
			}
		});

		return true;
	}

	// Initialize with retry mechanism
	function tryInitAIWriterButton(attempts) {
		if (attempts <= 0) return;
		
		if (!initAIWriterButton()) {
			setTimeout(function() {
				tryInitAIWriterButton(attempts - 1);
			}, 100);
		}
	}

	// Start initialization
	if (document.readyState === 'loading') {
		document.addEventListener('DOMContentLoaded', function() {
			tryInitAIWriterButton(10);
		});
	} else {
		tryInitAIWriterButton(10);
	}
})();
