// Meta Box popup window Events
var sftcyWordAIInsertTitleFunc;
var sftcyWordAIInsertContentFunc;	
var sftcyWordAIInsertExcerptFunc;
var sftcyWordAIInsertTagstFunc;	
var sftcyWordAIInsertSeoTitleFunc;
var sftcyWordAIInsertSeoMetaDescriptionFunc;
var sftcyWordAIInsertSeoMetaFocusKeywordFunc;


// ============================================================================
// 🔇 Silence benign Gutenberg "getComputedStyle defaultView is null" warning
// =============================================================================
(function() {
	const originalError = window.onerror;
	window.onerror = function(message, source, lineno, colno, error) {
		if (
			message &&
			message.includes("getComputedStyle") &&
			message.includes("defaultView")
		) {
			// prevent browser from logging this transient React render warning
			return true; // stops the error from appearing in console
		}
		if (typeof originalError === "function") {
			return originalError.apply(this, arguments);
		}
		return false;
	};
})();

// Sanitize html tags 
function wordAIRemoveHtmlTags(input) {
    return input.replace(/<[^>]*>/g, '');
}

jQuery(document).ready(function($) {			
	// console.log('Localized WordAI Admin View Script Data');	
	// console.log( sftcy_wordai_admin_view_script_obj );	
				
	// Start Metabox button click Popup Config (cleaned, keeps your options) - Content Generation Modal Window Configuration //

	function scWordAI_getContentWorkspace($) {
		const winW = $(window).width();
		const winH = $(window).height();
		const gutter = winW < 1024 ? 12 : 20;
		const $adminMenu = $('#adminmenuwrap:visible');
		const adminMenuW = $adminMenu.length ? $adminMenu.outerWidth(true) : 0;
		const $sidebar = $('.edit-post-sidebar:visible, #postbox-container-1:visible').first();
		let rightInset = gutter;

		if ($sidebar.length) {
			const sidebarLeft = $sidebar.offset().left || 0;
			rightInset = Math.max(gutter, winW - sidebarLeft + gutter);
		}

		const workspaceLeft = adminMenuW + gutter;
		const workspaceRight = Math.max(workspaceLeft + 420, winW - rightInset);
		const workspaceWidth = Math.max(420, workspaceRight - workspaceLeft);
		const widthCap = Math.min(1220, workspaceWidth);
		const minWidth = winW < 1024 ? 560 : 760;
		const modalWidth = Math.max(Math.min(minWidth, workspaceWidth), widthCap);
		const modalLeft = workspaceLeft + Math.max(0, Math.floor((workspaceWidth - modalWidth) / 2));

		return {
			width: Math.floor(modalWidth),
			left: Math.floor(modalLeft),
			top: winW < 1024 ? 8 : 10,
			maxHeight: Math.max(620, Math.floor(winH - 28))
		};
	}

	function scWordAI_applyContentDialogLayout($dialog) {
		const layout = scWordAI_getContentWorkspace($);
		$dialog.dialog('option', {
			width: layout.width,
			maxHeight: layout.maxHeight,
			position: {
				my: 'left top',
				at: 'left+' + layout.left + ' top+' + layout.top,
				of: window,
				collision: 'fit'
			}
		});

		const $widget = $dialog.dialog('widget');
		if ($widget.length) {
			const applyWidgetPosition = function () {
				$widget.css({
					position: 'fixed',
					left: layout.left + 'px',
					top: layout.top + 'px'
				});
			};

			applyWidgetPosition();
			window.requestAnimationFrame(applyWidgetPosition);
		}
	}

	function scWordAI_refreshResultPanels($dialog, preferredTarget) {
		const $nav = $dialog.find('.wordai-results-nav');
		const $buttons = $nav.find('.wordai-results-nav-btn');
		const $panels = $dialog.find('.wordai-result-panel');
		const availableTargets = [];
		let activeTarget = preferredTarget || $buttons.filter('.is-active').data('resultTarget');

		$panels.each(function () {
			const $panel = $(this);
			const target = $panel.data('resultTarget');
			const inlineDisplay = (this.style && this.style.display) ? this.style.display : '';
			const isGenerated = inlineDisplay && inlineDisplay !== 'none';

			if (isGenerated) {
				$panel.attr('data-wordai-generated', '1');
			}

			if ($panel.attr('data-wordai-generated') === '1') {
				availableTargets.push(target);
			}
		});

		$buttons.each(function () {
			const $button = $(this);
			const target = $button.data('resultTarget');
			const isAvailable = availableTargets.indexOf(target) !== -1;
			$button.prop('hidden', !isAvailable);
		});

		if (!availableTargets.length) {
			$nav.prop('hidden', true);
			$buttons.removeClass('is-active');
			$panels.removeClass('wordai-result-panel--active wordai-result-panel--inactive');
			return;
		}

		if (!activeTarget || availableTargets.indexOf(activeTarget) === -1) {
			activeTarget = availableTargets[0];
		}

		$nav.prop('hidden', false);
		$buttons.removeClass('is-active');
		$panels.each(function () {
			const $panel = $(this);
			const target = $panel.data('resultTarget');
			const isAvailable = availableTargets.indexOf(target) !== -1;
			const isActive = isAvailable && target === activeTarget;

			if (!isAvailable) {
				$panel.removeClass('wordai-result-panel--active wordai-result-panel--inactive');
				return;
			}

			$panel.toggleClass('wordai-result-panel--active', isActive);
			$panel.toggleClass('wordai-result-panel--inactive', !isActive);
		});

		$buttons.filter('[data-result-target="' + activeTarget + '"]').addClass('is-active');
	}

	// Setup the dialog
	const $dlg = $('#metabox-button-click-dialog');
	const $resultPanels = $dlg.find('.wordai-result-panel');
	let scWordAIResultObserver = null;
	let scWordAIMetaboxOrderObserver = null;

	function scWordAIKeepGeneratorAboveSeoFields() {
		const $generatorBox = $('#sftcy_wordai_metabox');
		const $seoBox = $('#sftcy_wordai_seo_metabox');

		if ($generatorBox.length && $seoBox.length && $generatorBox.index() > $seoBox.index()) {
			$generatorBox.insertBefore($seoBox);
		}
	}

	function scWordAIWatchMetaboxOrder() {
		scWordAIKeepGeneratorAboveSeoFields();

		if (scWordAIMetaboxOrderObserver || !window.MutationObserver) {
			return;
		}

		const sideSortables = document.getElementById('side-sortables');
		if (!sideSortables) {
			return;
		}

		scWordAIMetaboxOrderObserver = new MutationObserver(function () {
			window.requestAnimationFrame(scWordAIKeepGeneratorAboveSeoFields);
		});

		scWordAIMetaboxOrderObserver.observe(sideSortables, { childList: true });
	}

	function scWordAIScrollGenerationStatusIntoView() {
		window.setTimeout(function () {
			const $target = $dlg.find('.wordai-results-nav:visible, .wordai-results-shell:visible').first();
			const $content = $dlg.closest('.ui-dialog').find('.ui-dialog-content');

			if (!$target.length || !$content.length) {
				return;
			}

			const contentRect = $content[0].getBoundingClientRect();
			const targetRect = $target[0].getBoundingClientRect();
			const scrollTop = $content.scrollTop();
			const targetTop = scrollTop + targetRect.top - contentRect.top - Math.max(20, Math.round(contentRect.height * 0.28));
			$content.stop(true).animate({ scrollTop: Math.max(0, targetTop) }, 260);
		}, 180);
	}

	window.scWordAIScrollGenerationStatusIntoView = scWordAIScrollGenerationStatusIntoView;

	function scWordAIClosePromptAssistant() {
		const $panel = $dlg.find('.wordai-prompt-assistant-panel');
		const $toggle = $dlg.find('.wordai-prompt-assistant-toggle');

		if (!$panel.length) {
			return;
		}

		$panel.prop('hidden', true);
		$toggle.attr('aria-expanded', 'false');
		$dlg.find('.wordai-prompt-builder-insert').removeClass('is-attention');
	}

	window.scWordAIPrepareGenerationView = function () {
		scWordAIClosePromptAssistant();
		window.setTimeout(scWordAIScrollGenerationStatusIntoView, 70);
		window.setTimeout(scWordAIScrollGenerationStatusIntoView, 240);
	};

	scWordAIWatchMetaboxOrder();
	window.setTimeout(scWordAIWatchMetaboxOrder, 500);

	$dlg.dialog({
		title: sftcy_wordai_admin_view_script_obj.metabox_popup_dialog_title,
		dialogClass: 'metabox-button-click-popup-dialog-class sc-wordai-global-dialog sc-wordai-content-dialog',
		autoOpen: false,
		draggable: true,
		minWidth: 760,
		maxHeight: 1000,
		modal: true,
		resizable: false,
		closeOnEscape: true,
		position: { my: 'left top', at: 'left+20 top+10', of: window },

		open: function() {
		scWordAI_applyContentDialogLayout($dlg);
		scWordAI_refreshResultPanels($dlg);

		if (typeof window.scWordAISyncPopupRuntimeSettings === 'function') {
			window.scWordAISyncPopupRuntimeSettings();
		}

		if (!scWordAIResultObserver && window.MutationObserver) {
			scWordAIResultObserver = new MutationObserver(function () {
				scWordAI_refreshResultPanels($dlg);
			});

			$resultPanels.each(function () {
				scWordAIResultObserver.observe(this, {
					attributes: true,
					attributeFilter: ['style', 'class']
				});
			});
		}

		// overlay click closes
		$('.ui-widget-overlay').off('click').on('click', function () {
			$dlg.dialog('close');
		});
		},

		create: function () {
		// WP admin style fix
		$('.ui-dialog-titlebar-close').addClass('ui-button');

		// Custom icon + title (your code)
		const w = $(this).dialog("widget");
		const t = $(".ui-dialog-title", w);
		t.html(
			sftcy_wordai_admin_view_script_obj.sc_wordai_icon +
			sftcy_wordai_admin_view_script_obj.metabox_popup_dialog_title
		);
		if (!w.find('.wordai-dialog-progress').length) {
			w.find('.ui-dialog-titlebar').append('<span class="wordai-dialog-progress" hidden aria-live="polite"></span>');
		}
		if (!w.find('.wordai-dialog-drag-hint').length) {
			w.find('.ui-dialog-titlebar').append('<span class="wordai-dialog-drag-hint" aria-hidden="true"><span class="dashicons dashicons-move"></span></span>');
		}
		}
	});

	// Recalculate width on window resize while open
	$(window).on('resize', function(){
		if ($dlg.is(':visible')) {
		scWordAI_applyContentDialogLayout($dlg);
		}
	});

	$('body').on('click', '.wordai-results-nav-btn', function () {
		scWordAI_refreshResultPanels($dlg, $(this).data('resultTarget'));
	});

	$('body').on('click', '.sc-wordai-generate-content-btn, .sc-wordai-generate-content-streaming-btn', function () {
		$dlg.find('.wordai-results-nav').prop('hidden', true);
		$dlg.find('.wordai-results-nav-btn').removeClass('is-active');
		$dlg.find('.wordai-result-panel').removeAttr('data-wordai-generated').removeClass('wordai-result-panel--active wordai-result-panel--inactive');
	});

	function scWordAISetPromptText(promptText) {
		const cleanPrompt = $.trim(promptText || '');
		if (!cleanPrompt) {
			return;
		}

		$dlg.find('.scwordai-prompt')
			.val(cleanPrompt)
			.trigger('input')
			.focus();
	}

	function scWordAIBuildPromptFromFields() {
		const values = {};
		$dlg.find('.wordai-prompt-builder-input').each(function () {
			const key = $(this).data('promptField');
			if (key && !$(this).is(':disabled')) {
				values[key] = $.trim($(this).val() || '');
			}
		});

		if (!values.topic && !values.audience && !values.goal) {
			return '';
		}

		const lines = [];
		lines.push('Create high-quality WordPress content' + (values.topic ? ' about ' + values.topic : '') + '.');

		if (values.audience) {
			lines.push('Target audience: ' + values.audience + '.');
		}
		if (values.goal) {
			lines.push('Content goal: ' + values.goal + '.');
		}
		if (values.keyword) {
			lines.push('Focus keyword: ' + values.keyword + '. Use it naturally in the title, introduction, headings, body, and SEO fields where selected.');
		}
		if (values.points) {
			lines.push('Cover these key points: ' + values.points + '.');
		}
		if (values.cta) {
			lines.push('Call to action: ' + values.cta + '.');
		}

		lines.push('Keep the writing clear, useful, people-first, search-friendly, and easy to scan with natural headings and short paragraphs.');
		return lines.join(' ');
	}

	function scWordAIRefreshPromptBuilderPreview() {
		$dlg.find('.wordai-prompt-builder-preview').val(scWordAIBuildPromptFromFields());
	}

	function scWordAIGetPromptPlaceholders(promptText) {
		const matches = String(promptText || '').match(/\[[a-z0-9][a-z0-9 _/-]{1,60}\]/gi) || [];
		return matches
			.map(function (placeholder) {
				return placeholder.replace(/\s+/g, ' ').trim();
			})
			.filter(function (placeholder, index, list) {
				return list.indexOf(placeholder) === index;
			});
	}

	function scWordAIClearPromptAssistantAttention() {
		$dlg.find('.scwordai-prompt').removeClass('wordai-prompt-needs-attention');
		$dlg.find('.wordai-prompt-builder-input').removeClass('wordai-prompt-builder-input--missing');
		$dlg.find('.wordai-prompt-builder-insert').removeClass('is-attention');
	}

	function scWordAISetPromptAssistantMessage(message, variant) {
		const $feedback = $dlg.find('.prompt-alert-msg');
		const noticeClass = variant === 'info'
			? 'alert-remind wordai-feedback-line wordai-prompt-assistant-notice wordai-prompt-assistant-notice--info'
			: 'alert-remind wordai-feedback-line wordai-prompt-assistant-notice';
		$feedback
			.empty()
			.append(
				$('<span/>', {
					class: noticeClass,
					text: message
				})
			);
	}

	function scWordAIOpenPromptAssistant() {
		const $panel = $dlg.find('.wordai-prompt-assistant-panel');
		const $toggle = $dlg.find('.wordai-prompt-assistant-toggle');

		$panel.prop('hidden', false);
		$toggle.attr('aria-expanded', 'true');
		scWordAIRefreshPromptBuilderPreview();
	}

	function scWordAIHighlightFieldsForPlaceholders(placeholders) {
		const lookup = placeholders.join(' ').toLowerCase();
		const fieldMap = {
			topic: ['topic', 'service', 'product', 'page', 'faq'],
			audience: ['audience', 'customer', 'reader', 'visitor'],
			keyword: ['keyword', 'focus'],
			points: ['point', 'feature', 'benefit'],
			cta: ['cta', 'call to action']
		};

		Object.keys(fieldMap).forEach(function (field) {
			const shouldHighlight = fieldMap[field].some(function (needle) {
				return lookup.indexOf(needle) !== -1;
			});

			if (shouldHighlight) {
				$dlg.find('.wordai-prompt-builder-input[data-prompt-field="' + field + '"]:not(:disabled)')
					.addClass('wordai-prompt-builder-input--missing');
			}
		});
	}

	window.scWordAIValidatePromptBeforeGenerate = function () {
		const $prompt = $dlg.find('.scwordai-prompt');
		const promptText = $.trim($prompt.val() || '');
		const placeholders = scWordAIGetPromptPlaceholders(promptText);
		const builtPrompt = $.trim(scWordAIBuildPromptFromFields());
		const hasBuilderInput = $dlg.find('.wordai-prompt-builder-input:not(:disabled)').filter(function () {
			return $.trim($(this).val() || '').length > 0;
		}).length > 0;

		scWordAIClearPromptAssistantAttention();

		if ((placeholders.length || !promptText) && builtPrompt && hasBuilderInput) {
			scWordAISetPromptText(builtPrompt);
			scWordAIClearPromptAssistantAttention();
			return {
				valid: true,
				info: 'WordAI used your Prompt Assistant details for this generation.'
			};
		}

		if (placeholders.length) {
			scWordAIOpenPromptAssistant();
			$prompt.addClass('wordai-prompt-needs-attention').focus();
			$dlg.find('.wordai-prompt-builder-insert').addClass('is-attention');
			scWordAIHighlightFieldsForPlaceholders(placeholders);
			scWordAISetPromptAssistantMessage(
				'Your prompt still contains template placeholders: ' + placeholders.join(', ') + '. Replace them in Prompt / Hints, or fill the Prompt Assistant fields and click Use Prompt before generating.'
			);
			return { valid: false };
		}

		if (!promptText && hasBuilderInput) {
			scWordAIOpenPromptAssistant();
			$dlg.find('.wordai-prompt-builder-input[data-prompt-field="topic"]:not(:disabled), .wordai-prompt-builder-input[data-prompt-field="audience"]:not(:disabled), .wordai-prompt-builder-input[data-prompt-field="goal"]:not(:disabled)')
				.addClass('wordai-prompt-builder-input--missing');
			scWordAISetPromptAssistantMessage('Add at least a topic, audience, or goal in Prompt Assistant, or write a prompt manually before generating.');
			return { valid: false };
		}

		return { valid: true };
	};

	$('body').on('click', '.wordai-prompt-assistant-toggle', function () {
		const $button = $(this);
		const $panel = $dlg.find('.wordai-prompt-assistant-panel');
		const willOpen = $panel.prop('hidden');

		$panel.prop('hidden', !willOpen);
		$button.attr('aria-expanded', willOpen ? 'true' : 'false');

		if (willOpen) {
			scWordAIRefreshPromptBuilderPreview();
		}
	});

	$('body').on('click', '.wordai-prompt-template-card', function () {
		const $button = $(this);
		if ($button.data('templateLocked')) {
			const $upgrade = $dlg.find('.wordai-prompt-assistant-upgrade');
			const upgradeHref = $upgrade.attr('href') || 'https://softcoy.com/products/wordai-pro/checkout';
			if ($upgrade.length) {
				$upgrade.focus();
			}
			$dlg.find('.prompt-alert-msg')
				.empty()
				.append(
					$('<span/>', { class: 'alert-remind wordai-feedback-line wordai-prompt-lock-notice' })
						.append(document.createTextNode('This prompt template is available in WordAI Pro. '))
						.append($('<a/>', {
							href: upgradeHref,
							target: '_blank',
							rel: 'noopener',
							text: 'Get Pro'
						}))
				);
			return;
		}

		$dlg.find('.wordai-prompt-lock-notice').remove();
		scWordAIClearPromptAssistantAttention();
		scWordAISetPromptText($button.attr('data-template-prompt') || '');
		scWordAIOpenPromptAssistant();
		$dlg.find('.wordai-prompt-builder-insert').addClass('is-attention');
		scWordAISetPromptAssistantMessage('Template added. Replace the bracketed placeholders in Prompt / Hints, or fill Prompt Assistant fields and click Use Prompt.');
	});

	$('body').on('input', '.scwordai-prompt', function () {
		const placeholders = scWordAIGetPromptPlaceholders($(this).val() || '');
		if (!placeholders.length) {
			$(this).removeClass('wordai-prompt-needs-attention');
			$dlg.find('.wordai-prompt-builder-input').removeClass('wordai-prompt-builder-input--missing');
		}
	});

	$('body').on('input', '.wordai-prompt-builder-input', function () {
		scWordAIRefreshPromptBuilderPreview();
		$(this).removeClass('wordai-prompt-builder-input--missing');
		if ($.trim(scWordAIBuildPromptFromFields())) {
			$dlg.find('.wordai-prompt-builder-insert').addClass('is-attention');
		}
	});

	$('body').on('click', '.wordai-prompt-builder-insert', function () {
		const promptText = scWordAIBuildPromptFromFields();
		if (promptText) {
			$dlg.find('.wordai-prompt-lock-notice').remove();
			scWordAIClearPromptAssistantAttention();
			scWordAISetPromptText(promptText);
			scWordAISetPromptAssistantMessage('Prompt is ready. Review it if needed, then click Generate.', 'info');
		} else {
			$dlg.find('.wordai-prompt-builder-preview').focus();
		}
	});

	$('body').on('click', '.wordai-prompt-builder-clear', function () {
		$dlg.find('.wordai-prompt-builder-input:not(:disabled)').val('');
		$dlg.find('.wordai-prompt-builder-preview').val('');
		scWordAIClearPromptAssistantAttention();
	});
	

						
	// Insert Title
	$('body').on("click", ".sc-wordai-title-insert-btn", function() {
		sftcyWordAIInsertTitleFunc();
	});
	
	// Insert Content	
	$('.sc-wordai-content-insert-btn').click(function() {								
		sftcyWordAIInsertContentFunc();
	});

	// Insert Excerpt	
	$('.sc-wordai-excerpt-insert-btn').click(function() {								
		sftcyWordAIInsertExcerptFunc();
	});

	// Insert Tags	
	$('.sc-wordai-tags-insert-btn').click(function() {								
		sftcyWordAIInsertTagstFunc();
	});		
		
	// Insert SEO Title
	$('body').on("click", ".sc-wordai-seo-title-insert-btn", function() {
		sftcyWordAIInsertSeoTitleFunc();
	});

	// Insert SEO Meta Description
	$('body').on("click", ".sc-wordai-seo-meta-description-insert-btn", function() {
		sftcyWordAIInsertSeoMetaDescriptionFunc();
	});

	// Insert SEO Meta Description
	$('body').on("click", ".sc-wordai-seo-meta-focus-keyword-insert-btn", function() {
		sftcyWordAIInsertSeoMetaFocusKeywordFunc();
	});

	

	// Copy to clipboard
	if ( typeof ClipboardJS !== 'undefined' ) {
		new ClipboardJS('.sc-wordai-title-copy-btn, .sc-wordai-content-copy-btn, .sc-wordai-excerpt-copy-btn, .sc-wordai-tags-copy-btn, .sc-wordai-seo-title-copy-btn, .sc-wordai-seo-meta-description-copy-btn .sc-wordai-seo-meta-focus-keyword-copy-btn');
	}
	
	// Title Copied | Inserted
	$('.sc-wordai-title-copy-btn').click(function() {
		let copyBtn = $(this);
		copyBtn.html(sftcy_wordai_admin_view_script_obj.copied);
		setTimeout( function() { copyBtn.html(sftcy_wordai_admin_view_script_obj.copy_title); }, 6000 );
	});
	$('.sc-wordai-title-insert-btn').click(function() {
		let insertBtn = $(this );
		insertBtn.html(sftcy_wordai_admin_view_script_obj.inserted);		
		setTimeout( function() { insertBtn.html(sftcy_wordai_admin_view_script_obj.insert_title); }, 6000 );
	});
		
	// Content Copied | Inserted
	$('.sc-wordai-content-copy-btn').click(function() {
		let copyBtn = $(this);
		copyBtn.html(sftcy_wordai_admin_view_script_obj.copied);
		setTimeout( function() { copyBtn.html(sftcy_wordai_admin_view_script_obj.copy_content); }, 6000 );
	});
	$('.sc-wordai-content-insert-btn').click(function() {
		let insertBtn = $(this );
		insertBtn.html(sftcy_wordai_admin_view_script_obj.inserted);
		setTimeout( function() { insertBtn.html(sftcy_wordai_admin_view_script_obj.insert_content); }, 6000 );
	});
	
	// Excerpt Copied | Inserted
	$('.sc-wordai-excerpt-copy-btn').click(function() {
		let copyBtn = $(this);
		copyBtn.html(sftcy_wordai_admin_view_script_obj.copied);
		setTimeout( function() { copyBtn.html(sftcy_wordai_admin_view_script_obj.copy_excerpt); }, 6000 );
	});
	$('.sc-wordai-excerpt-insert-btn').click(function() {
		let insertBtn = $(this );
		insertBtn.html(sftcy_wordai_admin_view_script_obj.inserted);
		setTimeout( function() { insertBtn.html(sftcy_wordai_admin_view_script_obj.insert_excerpt); }, 6000 );
	});
	
	// Tags Copied | Inserted
	$('.sc-wordai-tags-copy-btn').click(function() {
		let copyBtn = $(this);
		copyBtn.html(sftcy_wordai_admin_view_script_obj.copied);
		setTimeout( function() { copyBtn.html(sftcy_wordai_admin_view_script_obj.copy_tags); }, 6000 );
	});
	$('.sc-wordai-tags-insert-btn').click(function() {
		let insertBtn = $(this );
		insertBtn.html(sftcy_wordai_admin_view_script_obj.inserted);
		setTimeout( function() { insertBtn.html(sftcy_wordai_admin_view_script_obj.insert_tags); }, 6000 );
	});
	
	// SEO Title Copied | Inserted
	$('.sc-wordai-seo-title-copy-btn').click(function() {
		let copyBtn = $(this);
		copyBtn.html(sftcy_wordai_admin_view_script_obj.copied);
		setTimeout( function() { copyBtn.html(sftcy_wordai_admin_view_script_obj.copy_seo_title); }, 6000 );
	});
	$('.sc-wordai-seo-title-insert-btn').click(function() {
		let insertBtn = $(this );
		insertBtn.html(sftcy_wordai_admin_view_script_obj.inserted);		
		setTimeout( function() { insertBtn.html(sftcy_wordai_admin_view_script_obj.insert_seo_title); }, 6000 );
	});

	// SEO Meta Description Copied | Inserted
	$('.sc-wordai-seo-meta-description-copy-btn').click(function() {
		let copyBtn = $(this);
		copyBtn.html(sftcy_wordai_admin_view_script_obj.copied);
		setTimeout( function() { copyBtn.html(sftcy_wordai_admin_view_script_obj.copy_meta_description); }, 6000 );
	});
	$('.sc-wordai-seo-meta-description-insert-btn').click(function() {
		let insertBtn = $(this );
		insertBtn.html(sftcy_wordai_admin_view_script_obj.inserted);
		setTimeout( function() { insertBtn.html(sftcy_wordai_admin_view_script_obj.insert_meta_description); }, 6000 );
	});
	// SEO Meta Focus Keyword Copied | Inserted
	$('.sc-wordai-seo-meta-focus-keyword-copy-btn').click(function() {
		let copyBtn = $(this);
		copyBtn.html(sftcy_wordai_admin_view_script_obj.copied);
		setTimeout( function() { copyBtn.html(sftcy_wordai_admin_view_script_obj.copy_meta_focus_keyword); }, 6000 );
	});
	$('.sc-wordai-seo-meta-focus-keyword-insert-btn').click(function() {
		let insertBtn = $(this );
		insertBtn.html(sftcy_wordai_admin_view_script_obj.inserted);
		setTimeout( function() { insertBtn.html(sftcy_wordai_admin_view_script_obj.insert_meta_focus_keyword); }, 6000 );
	});

	if ( $('.sc-wordai-support-page-wrapper').length > 0 ) {
		const supportOfficeStatusUrl = sftcy_wordai_admin_view_script_obj.support_office_status_url || 'https://softcoy.com/api/v1/support/tickets/status';
		const supportBrandIcons = {
			softcoy: sftcy_wordai_admin_view_script_obj.support_softcoy_icon_url || 'https://www.softcoy.com/brand-assets/logos/softcoy-mark.png',
			wordai: sftcy_wordai_admin_view_script_obj.support_wordai_icon_url || 'https://softcoy.com/brand-assets/logos/wordai-pro.svg'
		};

		const formatSupportLabel = function (value) {
			if (!value) {
				return '—';
			}
			return String(value)
				.replace(/_/g, ' ')
				.replace(/\b\w/g, (m) => m.toUpperCase())
				.replace(/\bCustomer\b/g, 'User')
				.replace(/\bSoftcoy Admin\b/gi, 'SOFTCOY Support')
				.replace(/\bSoftcoy Support\b/gi, 'SOFTCOY Support');
		};

		const formatSupportRoleLabel = function (role) {
			const roleKey = String(role || '').toLowerCase();
			if (roleKey.includes('customer') || roleKey.includes('user')) {
				return 'Plugin User';
			}
			if (roleKey.includes('support') || roleKey.includes('admin') || roleKey.includes('softcoy')) {
				return 'SOFTCOY Support';
			}
			return formatSupportLabel(role || 'support');
		};

		const escapeHtml = function (value) {
			return $('<div>').text(value || '').html();
		};

		const decodeSupportTicketPayload = function (rawPayload) {
			const parseSupportTicketJson = function (value) {
				if (!value) {
					return {};
				}

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

			const decodedUriPayload = function (value) {
				try {
					return decodeURIComponent(value);
				} catch (error) {
					return null;
				}
			};

			const decodedBase64Payload = function (value) {
				try {
					return decodeURIComponent(escape(window.atob(value)));
				} catch (error) {
					return null;
				}
			};

			const directPayload = parseSupportTicketJson(rawPayload || '{}');
			if (directPayload) {
				return directPayload;
			}

			const uriPayload = parseSupportTicketJson(decodedUriPayload(rawPayload || ''));
			if (uriPayload) {
				return uriPayload;
			}

			const base64Payload = parseSupportTicketJson(decodedBase64Payload(rawPayload || ''));
			if (base64Payload) {
				return base64Payload;
			}

			try {
				const parsed = JSON.parse(rawPayload || '{}');
				return parsed && typeof parsed === 'object' ? parsed : {};
			} catch (error) {
				return {};
			}
		};

		const encodeSupportTicketPayload = function (ticketData) {
			try {
				return window.btoa(unescape(encodeURIComponent(JSON.stringify(ticketData || {}))));
			} catch (error) {
				return '';
			}
		};

		const normalizeSupportTicket = function (ticketData) {
			const replies = Array.isArray(ticketData?.replies) ? ticketData.replies : [];
			return {
				ticket_uuid: ticketData?.ticket_uuid || '',
				sender_email: ticketData?.sender_email || '',
				initial_message: ticketData?.initial_message || ticketData?.message || '',
				initial_author_name: ticketData?.initial_author_name || 'Plugin User',
				initial_created_at: ticketData?.initial_created_at || ticketData?.created_at || '',
				issue_type: ticketData?.issue_type || 'General',
				channels: Array.isArray(ticketData?.channels) ? ticketData.channels : [],
				overall_status: formatSupportLabel(ticketData?.overall_status || ticketData?.overall_status_key || 'received'),
				email_status: ticketData?.email_status || '—',
				office_status: ticketData?.office_status || '—',
				office_status_key: ticketData?.office_status_key || '',
				office_status_label: formatSupportLabel(ticketData?.office_status_label || ticketData?.office_status || 'Open'),
				status_badge_class: ticketData?.status_badge_class || '',
				status_badge_label: ticketData?.status_badge_label || '',
				office_ticket_id: ticketData?.office_ticket_id || '',
				office_update: ticketData?.office_update || 'Awaiting office update.',
				created_at: ticketData?.created_at || '',
				updated_at: ticketData?.updated_at || '',
				office_last_synced_at: ticketData?.office_last_synced_at || '',
				resolved_at: ticketData?.resolved_at || '',
				timings: ticketData?.timings && typeof ticketData.timings === 'object' ? ticketData.timings : {},
				replies: replies
			};
		};

		const supportStatusKey = function (ticket) {
			return String(ticket.office_status_key || ticket.office_status || ticket.overall_status || 'open').toLowerCase().replace(/\s+/g, '_');
		};

		const hasSupportReply = function (ticket) {
			return Array.isArray(ticket.replies) && ticket.replies.length > 0;
		};

		const latestSupportReplyRole = function (ticket) {
			const replies = Array.isArray(ticket.replies) ? ticket.replies : [];
			const latestReply = replies.length ? replies[replies.length - 1] : {};
			return String(latestReply?.role || '').toLowerCase();
		};

		const supportStatusBadgeClass = function (ticket) {
			const key = supportStatusKey(ticket);
			if (ticket.status_badge_class) {
				return ticket.status_badge_class;
			}
			if (['resolved', 'closed', 'solved'].includes(key)) {
				return 'is-resolved';
			}
			if (['failed', 'error', 'rejected'].includes(key)) {
				return 'is-error';
			}
			if (key === 'customer_replied' || latestSupportReplyRole(ticket).includes('customer')) {
				return 'is-waiting';
			}
			if (hasSupportReply(ticket) || ['answered', 'replied', 'in_review', 'pending_customer', 'waiting_on_customer'].includes(key)) {
				return 'is-replied';
			}
			return 'is-open';
		};

		const supportStatusBadgeLabel = function (ticket) {
			const key = supportStatusKey(ticket);
			if (ticket.status_badge_label) {
				return ticket.status_badge_label;
			}
			if (['resolved', 'closed', 'solved'].includes(key)) {
				return 'Solved';
			}
			if (['failed', 'error', 'rejected'].includes(key)) {
				return 'Needs attention';
			}
			if (key === 'customer_replied' || latestSupportReplyRole(ticket).includes('customer')) {
				return 'Waiting for SOFTCOY';
			}
			if (hasSupportReply(ticket) || ['answered', 'replied', 'in_review', 'pending_customer', 'waiting_on_customer'].includes(key)) {
				return 'SOFTCOY replied';
			}
			return 'Open';
		};

		const mergeSupportTicketWithOffice = function (ticketData, officeTicket) {
			const ticket = normalizeSupportTicket(ticketData);
			if (!officeTicket || typeof officeTicket !== 'object') {
				return ticket;
			}

			return normalizeSupportTicket({
				...ticket,
				overall_status: formatSupportLabel(officeTicket.status_label || officeTicket.status || ticket.overall_status),
				office_status: formatSupportLabel(officeTicket.status || ticket.office_status),
				office_status_key: officeTicket.status || ticket.office_status_key,
				office_status_label: officeTicket.status_label || ticket.office_status_label,
				status_badge_class: '',
				status_badge_label: '',
				office_update: officeTicket?.latest_reply?.message || ticket.office_update,
				updated_at: officeTicket.updated_at || ticket.updated_at,
				office_last_synced_at: officeTicket.updated_at || ticket.office_last_synced_at,
				resolved_at: officeTicket.resolved_at || ticket.resolved_at,
				timings: officeTicket.timings || ticket.timings,
				replies: Array.isArray(officeTicket.replies) ? officeTicket.replies : ticket.replies
			});
		};

		const syncSupportTicketWithOffice = function (ticketData) {
			const ticket = normalizeSupportTicket(ticketData);

			if (!ticket.office_ticket_id || !ticket.sender_email) {
				return $.Deferred().resolve(ticket).promise();
			}

			return $.ajax({
				type: 'POST',
				url: supportOfficeStatusUrl,
				dataType: 'json',
				cache: false,
				contentType: 'application/json',
				data: JSON.stringify({
					email: ticket.sender_email,
					ticket_id: ticket.office_ticket_id
				})
			}).then(function (json) {
				const officeTicket = json && Array.isArray(json.tickets) ? json.tickets[0] : null;
				return mergeSupportTicketWithOffice(ticket, officeTicket);
			}).catch(function () {
				return ticket;
			});
		};

		const syncSupportTicketBatchWithOffice = function (ticketCollection) {
			const tickets = Array.isArray(ticketCollection) ? ticketCollection.map(normalizeSupportTicket) : [];
			const groupedTickets = {};
			const resolvedTickets = {};
			const deferred = $.Deferred();

			tickets.forEach(function (ticket) {
				if (!ticket.office_ticket_id || !ticket.sender_email) {
					resolvedTickets[ticket.ticket_uuid] = ticket;
					return;
				}

				if (!groupedTickets[ticket.sender_email]) {
					groupedTickets[ticket.sender_email] = [];
				}

				groupedTickets[ticket.sender_email].push(ticket);
			});

			const groupedEntries = Object.keys(groupedTickets);
			if (!groupedEntries.length) {
				deferred.resolve(resolvedTickets);
				return deferred.promise();
			}

			const requests = groupedEntries.map(function (email) {
				const groupTickets = groupedTickets[email];
				return $.ajax({
					type: 'POST',
					url: supportOfficeStatusUrl,
					dataType: 'json',
					cache: false,
					contentType: 'application/json',
					data: JSON.stringify({
						email: email,
						ticket_ids: groupTickets.map(function (ticket) {
							return ticket.office_ticket_id;
						})
					})
				}).done(function (response) {
					const officeTickets = Array.isArray(response?.tickets) ? response.tickets : [];

					groupTickets.forEach(function (ticket) {
						const officeTicket = officeTickets.find(function (candidate) {
							return candidate.ticket_id === ticket.office_ticket_id;
						});

						resolvedTickets[ticket.ticket_uuid] = mergeSupportTicketWithOffice(ticket, officeTicket);
					});
				}).fail(function () {
					groupTickets.forEach(function (ticket) {
						resolvedTickets[ticket.ticket_uuid] = ticket;
					});
				});
			});

			$.when.apply($, requests).always(function () {
				deferred.resolve(resolvedTickets);
			});

			return deferred.promise();
		};

		const buildSupportConversation = function (ticket) {
			const conversation = [];
			const initialMessage = $.trim(ticket.initial_message || '');
			if (initialMessage.length) {
				conversation.push({
					role: 'user',
					author_name: ticket.initial_author_name || 'Plugin User',
					message: initialMessage,
					created_at: ticket.initial_created_at || ticket.created_at || 'Submitted with ticket',
					is_initial: true
				});
			}

			(Array.isArray(ticket.replies) ? ticket.replies : []).forEach(function (reply) {
				if (!$.trim(reply?.message || '').length) {
					return;
				}
				conversation.push(reply);
			});

			return conversation;
		};

		const renderSupportReplies = function (ticket) {
			const conversation = buildSupportConversation(ticket);
			if (!conversation.length) {
				return '<div class="sc-wordai-support-modal-empty">No conversation message has been recorded for this ticket yet.</div>';
			}

			return conversation.map(function (reply) {
				const roleLabel = formatSupportRoleLabel(reply?.role || (reply?.is_initial ? 'user' : 'support'));
				const isUser = roleLabel.toLowerCase().includes('user');
				const iconUrl = isUser ? supportBrandIcons.wordai : supportBrandIcons.softcoy;
				const authorName = isUser ? 'Plugin User' : 'SOFTCOY Support';
				return [
					'<article class="sc-wordai-support-modal-reply ' + (isUser ? 'is-user' : 'is-support') + '">',
					'<div class="sc-wordai-support-modal-reply-inner">',
					'<span class="sc-wordai-support-modal-reply-avatar"><img src="' + escapeHtml(iconUrl) + '" alt="" loading="lazy"></span>',
					'<div class="sc-wordai-support-modal-reply-content">',
					'<div class="sc-wordai-support-modal-reply-meta">',
					'<strong>' + escapeHtml(authorName) + '</strong>',
					'<span>' + escapeHtml(reply?.created_at || 'Unknown time') + '</span>',
					'</div>',
					'<p class="sc-wordai-support-modal-reply-message">' + escapeHtml(reply?.message || '') + '</p>',
					'</div>',
					'</div>',
					'</article>',
				].join('');
			}).join('');
		};

		const renderSupportTicketModal = function (ticketData) {
			const ticket = normalizeSupportTicket(ticketData);
			const channels = ticket.channels.length ? ticket.channels.join(', ') : 'Email';
			const timings = ticket.timings || {};
			const canReplyToOffice = !!ticket.office_ticket_id;
			const html = [
				'<div class="sc-wordai-support-modal-grid">',
				'<div class="sc-wordai-support-modal-stat"><span>Status</span><strong>' + escapeHtml(ticket.office_status_label || ticket.overall_status) + '</strong><small>' + escapeHtml(ticket.office_update) + '</small></div>',
				'<div class="sc-wordai-support-modal-stat"><span>Submitted</span><strong>' + escapeHtml(ticket.created_at || timings.submitted_at || 'Unknown time') + '</strong><small>' + escapeHtml('First reply: ' + (timings.first_reply_at || 'Waiting')) + '</small></div>',
				'<div class="sc-wordai-support-modal-stat"><span>Resolution</span><strong>' + escapeHtml(ticket.resolved_at || 'Open') + '</strong><small>' + escapeHtml('Resolved in: ' + (timings.resolved_in_seconds ? Math.round(timings.resolved_in_seconds / 60) + ' min' : 'Open')) + '</small></div>',
				'</div>',
				'<div class="sc-wordai-support-modal-meta">',
				'<p><strong>Local Ticket:</strong> ' + escapeHtml(ticket.ticket_uuid) + '</p>',
				'<p><strong>SOFTCOY Ticket:</strong> ' + escapeHtml(ticket.office_ticket_id || 'Not assigned yet') + '</p>',
				'<p><strong>Issue:</strong> ' + escapeHtml(ticket.issue_type) + '</p>',
				'<p><strong>Channels:</strong> ' + escapeHtml(channels) + '</p>',
				'<p><strong>Email Status:</strong> ' + escapeHtml(ticket.email_status) + '</p>',
				'<p><strong>Office Status:</strong> ' + escapeHtml(ticket.office_status) + '</p>',
				'<p><strong>Last Synced:</strong> ' + escapeHtml(ticket.office_last_synced_at || ticket.updated_at || 'Not synced yet') + '</p>',
				'</div>',
				'<div class="sc-wordai-support-modal-thread">',
				'<h4>Support Conversation</h4>',
				renderSupportReplies(ticket),
				canReplyToOffice ? [
					'<div class="sc-wordai-support-modal-reply-form">',
					'<label for="wordaiSupportModalReplyMessage"><strong>Reply to SOFTCOY Support</strong></label>',
					'<textarea id="wordaiSupportModalReplyMessage" rows="5" placeholder="Reply on this ticket so the SOFTCOY support team can continue the same conversation."></textarea>',
					'<div class="sc-wordai-support-modal-reply-actions">',
					'<span class="sc-wordai-support-modal-reply-feedback" hidden></span>',
					'<button type="button" class="button button-primary sc-wordai-support-modal-send-reply" data-ticket="' + escapeHtml(ticket.ticket_uuid) + '" data-email="' + escapeHtml(ticket.sender_email || '') + '">Send Reply</button>',
					'</div>',
					'</div>',
				].join('') : '<div class="sc-wordai-support-modal-empty">This ticket does not have an office thread yet. Use the SOFTCOY Support Office delivery channel when creating the ticket.</div>',
				'</div>'
			].join('');

			$('#wordaiSupportTicketModal .sc-wordai-support-modal-body').html(html);
			$('#wordaiSupportTicketModal')
				.attr('data-ticket-payload', encodeSupportTicketPayload(ticket))
				.prop('hidden', false);
			$('body').addClass('sc-wordai-support-modal-open');
		};

		const closeSupportTicketModal = function () {
			$('#wordaiSupportTicketModal').prop('hidden', true);
			$('body').removeClass('sc-wordai-support-modal-open');
		};

		const buildSupportHistoryRowHtml = function (ticketData) {
			const ticket = normalizeSupportTicket(ticketData);
			const channelLabel = ticket.channels.length ? ticket.channels.join(', ') : 'Email';
			const channelStatus = '<span class="sc-wordai-support-channel-stack"><span>Email: ' + escapeHtml(ticket.email_status) + '</span><span>Office: ' + escapeHtml(ticket.office_status) + '</span></span>';

			return [
				'<tr>',
				'<td><button type="button" class="button-link sc-wordai-support-ticket-trigger" data-ticket="' + encodeSupportTicketPayload(ticket) + '"><strong>' + escapeHtml(ticket.ticket_uuid) + '</strong></button></td>',
				'<td>' + escapeHtml(ticket.issue_type) + '</td>',
				'<td>' + escapeHtml(channelLabel) + '</td>',
				'<td><span class="sc-wordai-support-status-badge ' + escapeHtml(supportStatusBadgeClass(ticket)) + '">' + escapeHtml(supportStatusBadgeLabel(ticket)) + '</span></td>',
				'<td>' + channelStatus + '</td>',
				'<td>' + escapeHtml(ticket.office_update) + '</td>',
				'<td>' + escapeHtml(ticket.updated_at || new Date().toLocaleString()) + '</td>',
				'</tr>',
			].join('');
		};

		const prependSupportHistoryRow = function (ticketId, issueType, deliveryChannels, overallStatus, deliveryResults, initialMessage) {
			const $tbody = $('.sc-wordai-support-history-table tbody');
			if (!$tbody.length) {
				window.location.reload();
				return;
			}

			const ticketData = {
				ticket_uuid: ticketId || '',
				sender_email: $('#wordaiSupportSenderEmail').val() || '',
				initial_message: initialMessage || '',
				initial_author_name: 'Plugin User',
				initial_created_at: new Date().toLocaleString(),
				issue_type: formatSupportLabel(issueType || 'general'),
				channels: (deliveryChannels || []).map((channel) => formatSupportLabel(channel)).filter(Boolean),
				overall_status: formatSupportLabel(overallStatus || 'received'),
				email_status: formatSupportLabel(deliveryResults?.email?.status || ''),
				office_status: formatSupportLabel(deliveryResults?.office?.status || ''),
				office_status_key: deliveryResults?.office?.status || '',
				office_status_label: formatSupportLabel(deliveryResults?.office?.status_label || deliveryResults?.office?.status || ''),
				office_ticket_id: deliveryResults?.office?.ticket_id || '',
				office_update: deliveryResults?.office?.message || 'Awaiting office update.',
				created_at: new Date().toLocaleString(),
				updated_at: new Date().toLocaleString(),
				office_last_synced_at: '',
				resolved_at: deliveryResults?.office?.resolved_at || '',
				timings: deliveryResults?.office?.timings || {},
				replies: Array.isArray(deliveryResults?.office?.replies) ? deliveryResults.office.replies : []
			};

			$tbody.prepend(buildSupportHistoryRowHtml(ticketData));
		};

		const refreshSupportHistoryRows = function () {
			const buttonEntries = $('.sc-wordai-support-ticket-trigger').map(function () {
				return {
					button: this,
					ticket: decodeSupportTicketPayload($(this).attr('data-ticket'))
				};
			}).get();

			syncSupportTicketBatchWithOffice(buttonEntries.map(function (entry) {
				return entry.ticket;
			})).then(function (resolvedTickets) {
				buttonEntries.forEach(function (entry) {
					const updatedTicket = resolvedTickets[entry.ticket.ticket_uuid] || normalizeSupportTicket(entry.ticket);
					$(entry.button).closest('tr').replaceWith(buildSupportHistoryRowHtml(updatedTicket));
				});
			});
		};

		$('body').on('click', '.sc-wordai-support-ticket-trigger', function () {
			const $button = $(this);
			const currentTicket = decodeSupportTicketPayload($(this).attr('data-ticket'));

			renderSupportTicketModal(currentTicket);

			syncSupportTicketWithOffice(currentTicket).then(function (updatedTicket) {
				$button.closest('tr').replaceWith(buildSupportHistoryRowHtml(updatedTicket));
				renderSupportTicketModal(updatedTicket);
			});
		});

		$('body').on('click', '.sc-wordai-support-modal-close, .sc-wordai-support-modal-backdrop', function () {
			closeSupportTicketModal();
		});

		$('body').on('click', '.sc-wordai-support-modal-send-reply', function () {
			const $button = $(this);
			const $modal = $('#wordaiSupportTicketModal');
			const $feedback = $modal.find('.sc-wordai-support-modal-reply-feedback');
			const replyMessage = $.trim($('#wordaiSupportModalReplyMessage').val() || '');
			const ticketUuid = $button.attr('data-ticket') || '';
			const senderEmail = $button.attr('data-email') || $('#wordaiSupportTicketReplySenderEmail').val() || $('#wordaiSupportSenderEmail').val() || '';
			const currentTicket = decodeSupportTicketPayload($modal.attr('data-ticket-payload'));

			if (!replyMessage.length) {
				$feedback.prop('hidden', false).removeClass('is-success').addClass('is-error').text('Write a reply before sending.');
				return;
			}

			$button.prop('disabled', true);
			$feedback.prop('hidden', false).removeClass('is-success is-error').addClass('is-pending').text('Sending reply to SOFTCOY Support Office...');

			$.ajax({
				type: 'POST',
				url: sftcy_wordai_admin_view_script_obj.adminajax_url,
				dataType: 'json',
				cache: false,
				data: {
					action: 'sc_wordai_reply_support_request',
					security: sftcy_wordai_admin_view_script_obj.nonce,
					ticket_uuid: ticketUuid,
					sender_email: senderEmail,
					reply_message: replyMessage
				},
				success: function (json) {
					const isSuccess = json && json.status === 'success';
					$feedback.removeClass('is-pending is-success is-error').addClass(isSuccess ? 'is-success' : 'is-error').text((json && json.message) ? json.message : 'Reply could not be sent.');

					if (!isSuccess) {
						return;
					}

					const fallbackTicket = normalizeSupportTicket({
						...currentTicket,
						ticket_uuid: ticketUuid || currentTicket.ticket_uuid,
						sender_email: senderEmail || currentTicket.sender_email,
						overall_status: formatSupportLabel(json?.overall_status || currentTicket.overall_status),
						office_status: formatSupportLabel(json?.delivery_results?.office?.status || currentTicket.office_status),
						office_status_label: formatSupportLabel(json?.delivery_results?.office?.status_label || currentTicket.office_status_label),
						office_update: json?.delivery_results?.office?.message || currentTicket.office_update,
						updated_at: new Date().toLocaleString(),
						office_last_synced_at: new Date().toLocaleString(),
						timings: json?.delivery_results?.office?.timings || currentTicket.timings,
						replies: Array.isArray(json?.delivery_results?.office?.replies) ? json.delivery_results.office.replies : currentTicket.replies
					});
					const updateRowAndModal = function (updatedTicket) {
						const $rowButton = $('.sc-wordai-support-ticket-trigger').filter(function () {
							return $.trim($(this).text()) === ticketUuid;
						}).first();

						if ($rowButton.length) {
							$rowButton.closest('tr').replaceWith(buildSupportHistoryRowHtml(updatedTicket));
						}

						renderSupportTicketModal(updatedTicket);
						$('#wordaiSupportModalReplyMessage').val('');
						$('#wordaiSupportTicketModal .sc-wordai-support-modal-reply-feedback')
							.prop('hidden', false)
							.removeClass('is-pending is-error')
							.addClass('is-success')
							.text((json && json.message) ? json.message : 'Reply sent successfully.');
					};

					syncSupportTicketWithOffice(fallbackTicket)
						.then(function (updatedTicket) {
							updateRowAndModal(updatedTicket);
						})
						.fail(function () {
							updateRowAndModal(fallbackTicket);
						});
				},
				error: function () {
					$feedback.removeClass('is-pending is-success').addClass('is-error').text('Reply could not be sent right now.');
				},
				complete: function () {
					$button.prop('disabled', false);
				}
			});
		});

		$(document).on('keydown.scWordaiSupportModal', function (event) {
			if (event.key === 'Escape') {
				closeSupportTicketModal();
			}
		});

		setTimeout(refreshSupportHistoryRows, 2000);
		setInterval(refreshSupportHistoryRows, 300000);

		$('body').on('click', '#wordaiSupportAttachButton', function () {
			$('#wordaiSupportAttachments').trigger('click');
		});

		$('body').on('change', '#wordaiSupportAttachments', function () {
			const files = Array.from(this.files || []);
			const $list = $('#wordaiSupportAttachmentList');

			if (!files.length) {
				$list.empty();
				return;
			}

			$list.html(files.map(function (file) {
				const sizeKb = Math.max(1, Math.round(file.size / 1024));
				return '<span class="sc-wordai-support-attachment-chip"><span class="dashicons dashicons-media-default" aria-hidden="true"></span>' + $('<div>').text(file.name + ' (' + sizeKb + ' KB)').html() + '</span>';
			}).join(''));
		});

		$('body').on('submit', '#wordaiSupportRequestForm', function (event) {
			event.preventDefault();

			const $form = $(this);
			const $feedback = $('.sc-wordai-support-submit-feedback');
			const $button = $form.find('.sc-wordai-support-send-btn');
			const $pageTop = $('.sc-wordai-support-page-wrapper');
			const includeDiagnostics = $('#wordaiSupportIncludeDiagnostics').is(':checked') ? 'yes' : 'no';
			const deliveryChannels = $form.find('input[name="delivery_channels[]"]:checked').map(function () {
				return $(this).val();
			}).get();

			if (!deliveryChannels.length) {
				$feedback
					.prop('hidden', false)
					.removeClass('is-pending is-success')
					.addClass('is-error')
					.html(sftcy_wordai_admin_view_script_obj.support_choose_channel);
				return;
			}

			$button.prop('disabled', true);
			$feedback
				.prop('hidden', false)
				.removeClass('is-success is-error')
				.addClass('is-pending')
				.html(sftcy_wordai_admin_view_script_obj.support_sending_request);

			$('html, body').stop(true).animate({
				scrollTop: Math.max(0, $pageTop.offset().top - 32)
			}, 220);

			const formData = new FormData();
			formData.append('action', 'sc_wordai_submit_support_request');
			formData.append('security', sftcy_wordai_admin_view_script_obj.nonce);
			formData.append('sender_email', $('#wordaiSupportSenderEmail').val());
			formData.append('subject', $('#wordaiSupportSubject').val());
			formData.append('issue_type', $('#wordaiSupportIssueType').val());
			formData.append('message', $('#wordaiSupportMessage').val());
			formData.append('include_diagnostics', includeDiagnostics);
			deliveryChannels.forEach(function (channel) {
				formData.append('delivery_channels[]', channel);
			});
			Array.from($('#wordaiSupportAttachments')[0]?.files || []).forEach(function (file) {
				formData.append('support_attachments[]', file);
			});

			$.ajax({
				type: 'POST',
				url: sftcy_wordai_admin_view_script_obj.adminajax_url,
				dataType: 'json',
				cache: false,
				processData: false,
				contentType: false,
				data: formData,
				success: function (json) {
					const isSuccess = json && json.status === 'success';
					$feedback
						.removeClass('is-pending is-success is-error')
						.addClass(isSuccess ? 'is-success' : 'is-error')
						.html((json && json.message) ? json.message : sftcy_wordai_admin_view_script_obj.support_request_failed);

					$('html, body').stop(true).animate({
						scrollTop: Math.max(0, $pageTop.offset().top - 32)
					}, 220);

					if (isSuccess) {
						prependSupportHistoryRow(
							json.ticket_uuid || '',
							$('#wordaiSupportIssueType').val(),
							deliveryChannels,
							json.overall_status || 'received',
							json.delivery_results || {},
							$('#wordaiSupportMessage').val()
						);
						$('#wordaiSupportMessage').val('');
						$('#wordaiSupportAttachments').val('');
						$('#wordaiSupportAttachmentList').empty();
					}
				},
				error: function () {
					$feedback
						.removeClass('is-pending is-success')
						.addClass('is-error')
						.html(sftcy_wordai_admin_view_script_obj.support_request_failed);
				},
				complete: function () {
					$button.prop('disabled', false);
				}
			});
		});
	}



	function scWordAINormalizeGeneratedEditorHtml(content) {
		content = String(content || '')
			.replace(/<(p|div|span)[^>]*>\s*(?:&nbsp;|\u00a0|<br\s*\/?>|\s|&bull;|&#8226;|&#x2022;|[•●○◦·\-*+])*\s*<\/\1>/gi, '')
			.replace(/<li\b[^>]*>([\s\S]*?)<\/li>/gi, function(match, inner) {
				const plain = String(inner || '').replace(/<[^>]*>/g, '').replace(/&nbsp;|&#160;/gi, ' ').replace(/&bull;|&#8226;|&#x2022;/gi, '•').trim();
				return (!plain || /^(?:\s|[•●○◦·\-*+])+$/.test(plain)) ? '\n' : '\n<p>' + String(inner || '').trim() + '</p>\n';
			})
			.replace(/<\/?(ul|ol)\b[^>]*>/gi, '\n')
			.replace(/<p(?!\s|>|\/|icture\b|re\b|aram\b|ath\b|olygon\b|olyline\b|rogress\b)([a-z])/gi, '<p>$1')
			.replace(/<\/p(?!\s|>)([a-z][a-z0-9-]*)>/gi, '</p>$1')
			.replace(/<li(?!\s|>|\/|nk\b)([a-z])/gi, '<li>$1')
			.replace(/<\/li(?!\s|>)([a-z][a-z0-9-]*)>/gi, '</li>$1')
			.replace(/<h([1-6])([^>\s/][^<>]*?)<\/h\1>/gi, function(match, level, text) {
				return '<h' + level + '>' + text.replace(/<[^>]*>/g, '').trim() + '</h' + level + '>';
			})
			.replace(/<\/h([1-6])>\s*(?:<br\s*\/?>\s*)+/gi, '</h$1>\n');

		return content
			.replace(/\r\n?/g, '\n')
			.replace(/>\s*</g, '>\n<')
			.replace(/^\s*(?:&bull;|&#8226;|&#x2022;|[•●○◦·])\s*$/gmi, '')
			.replace(/<\/(h[1-6]|p|div|li|ul|ol|blockquote)>\s*(?=<)/gi, '</$1>\n')
			.replace(/\n{3,}/g, '\n\n')
			.trim();
	}


	// Block Editor: Insert Title method
	sftcyWordAIInsertTitleFunc = function() {
		return new Promise( ( resolve, reject ) => {
			let postTitle = $('.sc-wordai-generated-title').val();		    
			if ( sftcy_wordai_admin_view_script_obj.current_posttype == 'post' || sftcy_wordai_admin_view_script_obj.current_posttype == 'page' ) {		
				//wp.data.dispatch('core/editor').editPost({title: postTitle});
				//scWordaiBlockEditorContentInsert( postTitle, 'title' );	
				wp.data.dispatch('core/editor').editPost({title: postTitle }).then( function() {
					console.log('Title: Inserted.');	
					setTimeout(() => {
						resolve(1);				
					}, 3000 );							
				});				
			}
			else if ( sftcy_wordai_admin_view_script_obj.current_posttype == 'product' ) {	
				if (tinymce.activeEditor) {
					$('#title').siblings('label').addClass('screen-reader-text');
					$('#title').val( postTitle );												
				}
				resolve(1);
			}
			else {
				console.log('Post Type Not Supported!');
				reject(0);
			}		
		});
	}
	

	// Block Editor: Insert Content method
	sftcyWordAIInsertContentFunc = function() {
		return new Promise((resolve, reject) => {
			let postContent = $('.sc-wordai-replace-withbr-response-format-content').val(); // Get content with <br>
			if (!postContent) {
				postContent = ($('.sc-wordai-generated-content').val() || '').replace(/\n\n/g, "<br/><br/>");
			}
			postContent = scWordAINormalizeGeneratedEditorHtml(postContent);

			if (
				sftcy_wordai_admin_view_script_obj.current_posttype == 'post' ||
				sftcy_wordai_admin_view_script_obj.current_posttype == 'page'
			) {
				let postBlocks = [];

				if (wp.blocks && typeof wp.blocks.rawHandler === 'function') {
					postBlocks = wp.blocks.rawHandler({ HTML: postContent });
				}

				if (!postBlocks.length && wp.blocks && typeof wp.blocks.parse === 'function') {
					postBlocks = wp.blocks.parse(postContent);
				}

				if (!postBlocks.length) {
					postBlocks = [wp.blocks.createBlock("core/paragraph", { content: postContent })];
				}

				Promise.resolve(wp.data.dispatch('core/block-editor').resetBlocks(postBlocks)).then(function() {
					console.log('Content: Replaced.');
					resolve(1);
				});
			}

			else if (sftcy_wordai_admin_view_script_obj.current_posttype === 'product') {
				if (tinymce.activeEditor) {
					var activeEditor = tinyMCE.get('content');
					activeEditor.setContent(postContent);
				}
				resolve(1);
			}

			else {
				console.log('Post Type Not Supported!');
				reject(0);
			}
		});
	};


	// Block Editor: Insert Excerpt method
	sftcyWordAIInsertExcerptFunc = function() {		
		return new Promise( ( resolve, reject ) => {
			let postExcerpt		= $('.sc-wordai-replace-withbr-response-format-excerpt').val();				
			if (!postExcerpt) {
				postExcerpt = $('.sc-wordai-generated-excerpt').val() || '';
			}
			if ( sftcy_wordai_admin_view_script_obj.current_posttype == 'post' || sftcy_wordai_admin_view_script_obj.current_posttype == 'page' ) {
				wp.data.dispatch('core/editor').editPost({excerpt: postExcerpt}).then(function() {
					console.log('Excerpt: Replaced.');
					resolve(1);
				});
			}
			else if ( sftcy_wordai_admin_view_script_obj.current_posttype == 'product' ) {	
				if (tinymce.activeEditor) {								
					//tinymce.activeEditor.execCommand('mceInsertContent', false, postExcerpt );
					var activeEditor = tinyMCE.get('excerpt');
					activeEditor.setContent(postExcerpt);
				}
				resolve(1);
			}
			else {
				console.log('Post Type Not Supported!');
				reject(0);
			}			
		});
	}
	//  Block Editor: Insert content on different request	
	let scWordaiBlockEditorContentInsert = function( content, contentType ) {
		switch( contentType ) {
			case 'title':
				wp.data.dispatch('core/editor').editPost({title: content }).then( function() {
					console.log('Title: Finally Inserted.');							
				});				
				break;
			case 'content':											    
				// let paragraphBlocksIds = wp.data.select('core/block-editor').getBlocksByName('core/paragraph');
				// if ( paragraphBlocksIds.length > 0 ) {
				// wp.data.dispatch('core/block-editor').removeBlocks( paragraphBlocksIds );											        																			
				wp.data.dispatch( 'core/block-editor' ).insertBlocks( wp.blocks.createBlock( 'core/paragraph', { content: content }) ).then( function() {
					console.log('Content: Finally Inserted.');
				});			
				// wp.data.dispatch( 'core/block-editor' ).insertBlocks( wp.blocks.createBlock( 'core/html', { content: content }) );												
				// $('.components-button.edit-post-sidebar__panel-tab:first').trigger( "click"); 												
				// wp.data.dispatch( 'core/block-editor' ).insertBlocks( wp.blocks.createBlock( 'core/paragraph', { content: content }) );													
				// wp.data.dispatch('core/editor').editPost({content: content});																						
				break;
			case 'excerpt':																
				// wp.data.dispatch('core/block-editor').insertBlocks( wp.blocks.createBlock( 'core/post-excerpt', { content: content }) );
				// wp.data.dispatch( 'core/editor' ).resetBlocks( [] ); // Reseting previous created all blocks													
				// let excerptBlocksIds = wp.data.select('core/block-editor').getBlocksByName('core/post-excerpt');
				// if ( excerptBlocksIds.length > 0 ) {					
					// await wp.data.dispatch('core/block-editor').removeBlocks( excerptBlocksIds );							
				// }					
				wp.data.dispatch('core/block-editor').insertBlocks( wp.blocks.createBlock( 'core/post-excerpt', {}) ).then( function() {
					wp.data.dispatch('core/editor').editPost({excerpt: content}).then(function() {
						console.log('Excerpt: Finally Inserted.');
					});
				});
				// wp.data.dispatch('core/editor').editPost({excerpt: content});						
													
				// $('.components-button.edit-post-sidebar__panel-tab:first').trigger( "click");
				// wp.data.select( 'core/editor' ).getEditedPostAttribute( 'excerpt' ); 																	
				break;
			default:
				console.log('Inserting for Item[' + contentType + '] not supported.');
				break;
		}
	}
	
	
	// Block Editor: Insert Tags method
	sftcyWordAIInsertTagstFunc	= function() {		
		let postTags		= $('.sc-wordai-generated-tags').val();			
		// console.log('Tags: '+ postTags );					
        if ( sftcy_wordai_admin_view_script_obj.current_posttype === 'post' || sftcy_wordai_admin_view_script_obj.current_posttype === 'page' ) {				
			 let params		= {};
			 let actionName = 'sc_wordai_save_tags';
			 params.tags	= postTags;
			 params.postID	= wp.data.select("core/editor").getCurrentPostId();
			 
			 scWordAIGlobalAjax(params, actionName).then( function(data) {
				//console.log(data);
				let jData	= JSON.parse(data);
				//console.log(jData);
				//  console.log(jData.tagIDs);
				// wp.data.select( 'core/editor' ).getEditedPostAttribute( 'tags' );
				wp.data.dispatch( 'core/editor' ).editPost({tags: jData.tagIDs});
			 })
			 .catch( function(error) {
				 console.log(error);
			 });			
		}
		else if ( sftcy_wordai_admin_view_script_obj.current_posttype === 'product' ) {	
			//$('#new-tag-product_tag').attr('value', postTags );
			$('#new-tag-product_tag').val( postTags );
			$('.button.tagadd').trigger('click');			 									
			$('.scwordai-prompt').focus();
		}
		else {
			console.log('Post Type Not Supported!');
		}		
	};		


	// Block Editor: Insert SEO Title method
	sftcyWordAIInsertSeoTitleFunc = function() {
		return new Promise( ( resolve, reject ) => {
			let seotTitle = $('.sc-wordai-generated-seo-title').val();		
			console.log('SEO Title: '+ seotTitle );    
			// $('.wordaiSEOTitleData').val( seotTitle );
			$('#wordaiSEOTitle').val( seotTitle );
			// Now refresh ranks + SERP preview instantly
			window.wordaiRefreshSEO();				 
			resolve(1);
		});
	}

	// Block Editor: Insert SEO Meta Description method
	sftcyWordAIInsertSeoMetaDescriptionFunc = function() {
		return new Promise( ( resolve, reject ) => {
			let seoMetaDescription = $('.sc-wordai-generated-seo-meta-description').val();		
			console.log('Meta Description: '+ seoMetaDescription );    
			// $('.wordaiSEOMetaDescriptionData').val( seoMetaDescription );
			$('#wordaiSEOMetaDescription').val( seoMetaDescription );
			// Now refresh ranks + SERP preview instantly
			window.wordaiRefreshSEO();			
			resolve(1);
		});
	}

	// Block Editor: Insert SEO Focus Keyword method
	sftcyWordAIInsertSeoMetaFocusKeywordFunc = function() {
		return new Promise( ( resolve, reject ) => {
			let seoMetaFocusKeyword = $('.sc-wordai-generated-seo-meta-focus-keyword').val();		
			console.log('Focus Keyword: '+ seoMetaFocusKeyword );    			
			$('#wordaiSEOFocusKeyword').val( seoMetaFocusKeyword );
			// Now refresh ranks + SERP preview instantly
			window.wordaiRefreshSEO();			
			resolve(1);
		});
	}

			
	// API Settings: API Settings Page
	$('body').on( "change", ".sc-temperature-input", function() { $(this).next().text( this.value ); });
	$('body').on( "change", ".sc-wordai-frequency-penalty-input", function() { $(this).next().text( this.value ); });
	$('body').on( "change", ".sc-wordai-presence-penalty-input", function() { $(this).next().text( this.value ); });


	

}); // End jQuery(document).ready(function($)
