var scWordAIProcessGroupOfChunkResponse;
var scWordAIParseStreamingChunk;
var scWordAIProcessGeminiStream;
var scWordAIStripMarkdown;
// var scWordAIProcessAutoInsertContentOnly;
// var scWordAIProcessAutoInsertExcerptOnly
// var scWordAIProcessAutoInsertTagsOnly;


jQuery(document).ready(function($) {			
	console.log('Localized WordAI Content Generate Script Data');	
	console.log( sftcy_wordai_content_generate_script_obj );	
		
	var scWordAIContentGenerationTotalItems			= 0;
	var scWordAIContentGenerationTotalItemsTracker	= 0;
	var scWordAITotalImageGenerationTracker			= 0;
	
	var scTitleXHR									= '';	
	var scContentXHR								= ''; 	
	var scExcerptXHR								= '';
	var scTagsXHR									= '';
	var scSeoTitleXHR								= '';
	var scSeoMetaDescriptionXHR						= '';	
	var scSeoMetaFocusKeywordXHR					= '';	
	var scImageAltTextXHR							= '';
	var scImagesXHR									= ''; 	

	function scWordAIGetFeedbackMessage(message) {
		if (message === null || typeof message === 'undefined') {
			return '';
		}
		if (typeof message === 'string') {
			return message.trim();
		}
		if (typeof message === 'object') {
			return (
				message.errorMessage ||
				message.feedbackMsg ||
				message.wordAIAPIKeyMissing ||
				message.message ||
				''
			).toString().trim();
		}
		return String(message).trim();
	}

	function scWordAIAppendFeedback(type, message, iconHtml) {
		const text = scWordAIGetFeedbackMessage(message);
		if (!text) {
			return;
		}

		const normalizedText = text.replace(/\s+/g, ' ').trim();
		const $duplicate = $('.prompt-alert-msg .wordai-feedback-line').filter(function() {
			return ($(this).text() || '').replace(/\s+/g, ' ').trim() === normalizedText;
		});
		if ($duplicate.length) {
			return;
		}

		const className = type === 'success' ? 'alert-success' : (type === 'remind' ? 'alert-remind' : 'alert-error');
		const $line = $('<span/>', {
			class: className + ' wordai-feedback-line',
			text: text
		});

		if (iconHtml) {
			$line.prepend(iconHtml + ' ');
		}

		$('.prompt-alert-msg').append($line);
	}

	function scWordAISetFeedback(type, message, iconHtml) {
		$('.prompt-alert-msg').empty();
		scWordAIAppendFeedback(type, message, iconHtml);
	}

	function scWordAIExtractAjaxError(xhr, fallback) {
		const fallbackMessage = scWordAIGetFeedbackMessage(fallback) || sftcy_wordai_content_generate_script_obj.something_went_wrong || 'Something went wrong. Please try again.';
		const responseJson = xhr && xhr.responseJSON ? xhr.responseJSON : null;
		const jsonMessage = responseJson ? scWordAIGetFeedbackMessage(
			responseJson.wordAIAPIKeyMissing ||
			responseJson.errorMessage ||
			responseJson.feedbackMsg ||
			responseJson.message ||
			(responseJson.error && responseJson.error.message)
		) : '';

		if (jsonMessage) {
			return jsonMessage;
		}

		const responseText = xhr && typeof xhr.responseText === 'string' ? xhr.responseText.trim() : '';
		if (responseText) {
			try {
				const parsed = JSON.parse(responseText);
				const parsedMessage = scWordAIGetFeedbackMessage(
					parsed.wordAIAPIKeyMissing ||
					parsed.errorMessage ||
					parsed.feedbackMsg ||
					parsed.message ||
					(parsed.error && parsed.error.message)
				);
				if (parsedMessage) {
					return parsedMessage;
				}
			} catch (e) {
				const plain = responseText.replace(/<[^>]*>/g, ' ').replace(/\s+/g, ' ').trim();
				if (plain && plain.toLowerCase() !== 'internal server error') {
					return plain.substring(0, 240);
				}
			}
		}

		if (xhr && Number(xhr.status) >= 500) {
			return 'Internal server error. Please try again, or check the provider/API log if the issue continues.';
		}

		return fallbackMessage;
	}

	function scWordAIRejectAjaxError(reject, xhr, error) {
		const message = scWordAIExtractAjaxError(xhr, error);
		scWordAIAppendFeedback('error', message);
		reject(message);
	}

	function scWordAICleanGeneratedListHtml(content) {
		return 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();

				if (!plain || /^(?:\s|[•●○◦·\-*+])+$/.test(plain)) {
					return '\n';
				}

				return '\n<p>' + String(inner || '').trim() + '</p>\n';
			})
			.replace(/<\/?(ul|ol)\b[^>]*>/gi, '\n')
			.replace(/^\s*(?:&bull;|&#8226;|&#x2022;|[•●○◦·])\s*$/gmi, '');
	}

	function scWordAIGetGeneratedImageUrls() {
		return String($('.sc-wordai-generated-images-urls').val() || '')
			.split(',')
			.map(function(url) { return $.trim(url); })
			.filter(Boolean);
	}

	function scWordAIResetImageResultUI() {
		$('.sc-wordai-generated-image-wrapper').empty();
		$('.sc-wordai-generated-images-urls').val('');
		$('.sc-wordai-generated-images-model-name').val('');
		$('.sc-wordai-save-to-gallery-row').hide().attr('hidden', true);
	}

	function scWordAIShowImageResultError(message) {
		const msg = scWordAIGetFeedbackMessage(message) || (sftcy_wordai_content_generate_script_obj?.something_went_wrong_images || 'Image generation failed. Please check the selected provider and image settings.');
		$('.sc-wordai-generated-image-wrapper')
			.html($('<div/>', {
				class: 'wordai-result-inline-error',
				text: msg
			}));
		$('.sc-wordai-save-to-gallery-row').hide().attr('hidden', true);
		window.scWordAISetResultPanelState('images', 'error', msg);
	}


	/**
	 * CONTENT MODAL: Fatal stop (API key missing)
	 * - Aborts all running XHRs (re-uses your existing variables)
	 * - Resets UI (hide wave, show Generate buttons, hide Cancel)
	 * - Unlocks provider selector
	 * - Shows key icon message
	 */
	window.scWordAIStopAllContentGeneration = function (msg) {

		const promptAlertMsg = $('.prompt-alert-msg');
		const waveAnimationRow = $('#metabox-button-click-dialog .wave-animation-row');
		const cancelBtn = $('.sc-wordai-generate-cancel-requests-content-btn');
		const genBtn = $('.sc-wordai-generate-content-btn');
		const genStreamBtn = $('.sc-wordai-generate-content-streaming-btn');

		// ✅ Show message with KEY icon
		const icon = '<i class="fa-solid fa-key" aria-hidden="true"></i> ';
		scWordAISetFeedback('error', msg || 'Valid API Key required.', icon);

		// ✅ Abort XHRs safely (same as your cancel handler)
		try { if (window.scTitleXHR && window.scTitleXHR.abort) window.scTitleXHR.abort(); } catch (e) {}
		try { if (window.scContentXHR && window.scContentXHR.abort) window.scContentXHR.abort(); } catch (e) {}
		try { if (window.scExcerptXHR && window.scExcerptXHR.abort) window.scExcerptXHR.abort(); } catch (e) {}
		try { if (window.scTagsXHR && window.scTagsXHR.abort) window.scTagsXHR.abort(); } catch (e) {}
		try { if (window.scSeoTitleXHR && window.scSeoTitleXHR.abort) window.scSeoTitleXHR.abort(); } catch (e) {}
		try { if (window.scSeoMetaDescriptionXHR && window.scSeoMetaDescriptionXHR.abort) window.scSeoMetaDescriptionXHR.abort(); } catch (e) {}
		try { if (window.scSeoMetaFocusKeywordXHR && window.scSeoMetaFocusKeywordXHR.abort) window.scSeoMetaFocusKeywordXHR.abort(); } catch (e) {}
		try { if (window.scImageAltTextXHR && window.scImageAltTextXHR.abort) window.scImageAltTextXHR.abort(); } catch (e) {}
		try { if (window.scImagesXHR && window.scImagesXHR.abort) window.scImagesXHR.abort(); } catch (e) {}

		// ✅ Reset counters
		window.scWordAIContentGenerationTotalItems = 0;
		window.scWordAIContentGenerationTotalItemsTracker = 0;
		window.scWordAITotalImageGenerationTracker = 0;
		if (typeof window.scWordAIResetResultPanels === 'function') {
			window.scWordAIResetResultPanels();
		}

		// ✅ Unlock provider selector immediately
		if (typeof window.scWordAISetContentPopupBusy === 'function') {
			window.scWordAISetContentPopupBusy(false);
		}

		// ✅ Restore UI state (hide wave, hide cancel, show generate buttons)
		waveAnimationRow.stop(true, true).fadeOut(150);
		cancelBtn.stop(true, true).fadeOut(150, function () {
			genBtn.stop(true, true).fadeIn(150);
			genStreamBtn.stop(true, true).fadeIn(150);
		});
	};


	/**
	 * Lock/unlock AI provider selector inside a given modal
	 * Used by Content Generation + Suggest Title popups
	 */
	window.scWordAISetPopupProviderBusy = function (modalSelector, isBusy) {
		const $dialog = $(modalSelector);
		if (!$dialog.length) return;

		const $providerSelect = $dialog.find('select.sc-wordai-ai-provider-select');
		if (!$providerSelect.length) return;

		$providerSelect.prop('disabled', !!isBusy);

		// Optional visual cue
		$providerSelect
			.closest('.sc-wordai-provider-picker')
			.toggleClass('sc-wordai-provider-picker--disabled', !!isBusy);
	};

	// Backward compatibility for content Modal
	window.scWordAISetContentPopupBusy = function (isBusy) {
		scWordAISetPopupProviderBusy('#metabox-button-click-dialog', isBusy);
	};

	// Backward compatibility for suggest Title Modal
	window.scWordAISetSuggestTitlePopupBusy = function (isBusy) {
		scWordAISetPopupProviderBusy('#suggest-titles-button-click-dialog', isBusy);
	};

	const scWordAIResultPanelMap = {
		title: 'title',
		content: 'content',
		excerpt: 'excerpt',
		tags: 'tags',
		seotitle: 'seo-title',
		seometadescription: 'seo-meta-description',
		seometafocuskeyword: 'seo-meta-focus-keyword',
		imagealttext: 'image-alt-text',
		images: 'images'
	};

	function scWordAIGetResultPanelTarget(itemKey) {
		return scWordAIResultPanelMap[itemKey] || itemKey;
	}

	function scWordAIBuildDialogProgressContent(label, showWave) {
		const $label = $('<span/>', {
			class: 'wordai-dialog-progress-label',
			text: label
		});

		if (!showWave) {
			return $label;
		}

		const $wave = $('<span/>', {
			class: 'wordai-dialog-progress-wave',
			'aria-hidden': 'true'
		});

		for (let i = 0; i < 5; i++) {
			$wave.append($('<span/>'));
		}

		return $().add($wave).add($label);
	}

	window.scWordAIUpdateDialogProgress = function () {
		const $progress = $('.ui-dialog.sc-wordai-content-dialog .wordai-dialog-progress');
		const $panels = $('.wordai-result-panel[data-wordai-generated="1"]');
		const total = $panels.length;

		if (!$progress.length || !total) {
			$progress.attr('hidden', true).empty().removeClass('is-queued is-loading is-complete');
			return;
		}

		const completed = $panels.filter('.is-success, .is-error').length;
		const loading = $panels.filter('.is-loading').length;
		let label = 'Queued 0/' + total;

		if (completed >= total) {
			label = 'Completed ' + completed + '/' + total;
		} else if (loading > 0 || completed > 0) {
			label = 'Generating ' + completed + '/' + total;
		}

		$progress
			.empty()
			.append(scWordAIBuildDialogProgressContent(label, completed < total && (loading > 0 || completed > 0)))
			.attr('hidden', false)
			.toggleClass('is-complete', completed >= total)
			.toggleClass('is-loading', completed < total && (loading > 0 || completed > 0))
			.toggleClass('is-queued', completed === 0 && loading === 0);
	};

	window.scWordAISetResultPanelState = function (itemKey, state, message) {
		const target = scWordAIGetResultPanelTarget(itemKey);
		const $panel = $('.wordai-result-panel[data-result-target="' + target + '"]');
		const $status = $panel.find('.wordai-result-status');
		const $navBtn = $('.wordai-results-nav-btn[data-result-target="' + target + '"]');
		const $navBadge = $navBtn.find('.wordai-results-nav-badge');
		const statusText = message || (
			state === 'queued' ? 'Queued' :
			state === 'loading' ? 'Generating' :
			state === 'success' ? 'Ready' :
			state === 'error' ? 'Error' :
			''
		);
		const badgeText = (
			state === 'queued' ? 'Queued' :
			state === 'loading' ? 'Generating' :
			state === 'success' ? 'Ready' :
			state === 'error' ? 'Error' :
			statusText
		);

		$panel.removeClass('is-queued is-loading is-success is-error');
		$navBtn.removeClass('is-queued is-loading is-success is-error');

		if (!state || state === 'idle') {
			$status.attr('hidden', true).text('');
			$navBadge.attr('hidden', true).text('');
			window.scWordAIUpdateDialogProgress();
			return;
		}

		$panel.addClass('is-' + state);
		$navBtn.addClass('is-' + state).prop('hidden', false);
		$status.text(statusText).attr('hidden', false);
		$navBadge.text(badgeText).attr('hidden', false);
		window.scWordAIUpdateDialogProgress();

		if (state === 'loading' && typeof window.scWordAIScrollGenerationStatusIntoView === 'function') {
			window.setTimeout(window.scWordAIScrollGenerationStatusIntoView, 80);
		}
	};

	window.scWordAIPrimeResultPanels = function (checkedItems) {
		const targets = [];
		$('.sc-wordai-generated-image-alt-text').val('');
		$('.wordai-result-panel').each(function () {
			$(this)
				.removeAttr('data-wordai-generated')
				.removeClass('wordai-result-panel--active wordai-result-panel--inactive is-queued is-loading is-success is-error')
				.hide();
			$(this).find('.wordai-result-status').attr('hidden', true).text('');
		});

		$('.wordai-results-nav-btn').each(function () {
			$(this)
				.prop('hidden', true)
				.removeClass('is-active is-queued is-loading is-success is-error');
			$(this).find('.wordai-results-nav-badge').attr('hidden', true).text('');
		});

		(checkedItems || []).forEach(function (itemKey, index) {
			const target = scWordAIGetResultPanelTarget(itemKey);
			const $panel = $('.wordai-result-panel[data-result-target="' + target + '"]');
			targets.push(target);

			$panel
				.attr('data-wordai-generated', '1')
				.show();

			if (index === 0) {
				$panel.addClass('wordai-result-panel--active');
			} else {
				$panel.addClass('wordai-result-panel--inactive');
			}

			window.scWordAISetResultPanelState(itemKey, 'queued');
		});

		if (targets.length) {
			const $nav = $('.wordai-results-nav');
			$nav.prop('hidden', false);
			$('.wordai-results-nav-btn[data-result-target="' + targets[0] + '"]').addClass('is-active');
		}

		window.scWordAIUpdateDialogProgress();
	};

	window.scWordAIResetResultPanels = function () {
		$('.wordai-result-panel').each(function () {
			$(this)
				.removeAttr('data-wordai-generated')
				.removeClass('wordai-result-panel--active wordai-result-panel--inactive is-queued is-loading is-success is-error');
			$(this).find('.wordai-result-status').attr('hidden', true).text('');
		});

		$('.wordai-results-nav-btn').each(function () {
			$(this)
				.prop('hidden', true)
				.removeClass('is-active is-queued is-loading is-success is-error');
			$(this).find('.wordai-results-nav-badge').attr('hidden', true).text('');
		});

		$('.wordai-results-nav').prop('hidden', true);
		window.scWordAIUpdateDialogProgress();
	};

		
	// Generate [ Non Streaming ] : Title
	function scWordAIWriteTitle( hintsData ) {		
		let params 					= {};
		params.prompt				= hintsData;	
		return new Promise( ( resolve, reject ) => {
			scTitleXHR	=	$.ajax({
				  type:"POST",
				  cache: false,
				  url: sftcy_wordai_content_generate_script_obj.adminajax_url,
				  data : {			    
						action 	 : 'sc_wordai_write_titles',
						security : sftcy_wordai_content_generate_script_obj.nonce,
						params   : params
						},		  
				  success: function(data) { 
					 scWordAIContentGenerationTotalItemsTracker++; 							 
					 resolve( data ); 
					//  console.log(data); 
					},
				  error: function( xhr, status, error ) { 
					 scWordAIContentGenerationTotalItemsTracker++;  							 
					 scWordAIRejectAjaxError(reject, xhr, error);
					 console.log(xhr); 
					 console.log(status); 
					 console.log(error); 				 
					}
				});
		}); // Promise						
	}
								
	
	// Generate [ Non Streaming ]: Content
	function scWordAIWriteContent( hintsData ) {
		let params 					= {};
		params.prompt				= hintsData;	
		return new Promise( ( resolve, reject ) =>  {
			scContentXHR	=	$.ajax({
				  type:"POST",
				  cache: false,
				  url: sftcy_wordai_content_generate_script_obj.adminajax_url,
				  data : {			    
						action 	 : 'sc_wordai_write_content',
						security : sftcy_wordai_content_generate_script_obj.nonce,
						params   : params
						},		  
				  success: function(data) { 
					 scWordAIContentGenerationTotalItemsTracker++; 				 
					 resolve( data ); 
					 console.log(data); 
					},
				  error: function( xhr, status, error ) { 
					 scWordAIContentGenerationTotalItemsTracker++;				 
					 scWordAIRejectAjaxError(reject, xhr, error);
					 console.log(xhr); 
					 console.log(status); 
					 console.log(error); 				 
					}
				});
		}); // Promise			
	}
	
	// Generate [ Non Streaming ] : Excerpt
	function scWordAIWriteExcerpt( hintsData ) {
		let params 					= {};
		params.prompt				= hintsData;	
		return new Promise( ( resolve, reject ) =>  {
			scExcerptXHR	=	$.ajax({
				  type:"POST",
				  cache: false,
				  url: sftcy_wordai_content_generate_script_obj.adminajax_url,
				  data : {			    
						action 	 : 'sc_wordai_write_excerpt',
						security : sftcy_wordai_content_generate_script_obj.nonce,
						params   : params
						},		  
				  success: function(data) { 
					 scWordAIContentGenerationTotalItemsTracker++; 				 
					 resolve( data ); 
					//  console.log(data); 
					},
				  error: function( xhr, status, error ) { 
					 scWordAIContentGenerationTotalItemsTracker++;				 
					 scWordAIRejectAjaxError(reject, xhr, error);
					 console.log(xhr); 
					 console.log(status); 
					 console.log(error); 				 
					}
				});
		}); // Promise			
	}
	
	// Generate [ Non Streaming ] : Tags
	function scWordAIWriteTags( hintsData ) {		
		let params 					= {};
		params.prompt				= hintsData;	
		return new Promise( ( resolve, reject ) => {
			scTagsXHR	=	$.ajax({
				  type:"POST",
				  cache: false,
				  url: sftcy_wordai_content_generate_script_obj.adminajax_url,
				  data : {			    
						action 	 : 'sc_wordai_write_tags',
						security : sftcy_wordai_content_generate_script_obj.nonce,
						params   : params
						},		  
				  success: function(data) { 
					 scWordAIContentGenerationTotalItemsTracker++; 							 
					 resolve( data ); 
					//  console.log(data); 
					},
				  error: function( xhr, status, error ) { 
					 scWordAIContentGenerationTotalItemsTracker++;  							 
					 scWordAIRejectAjaxError(reject, xhr, error);
					 console.log(xhr); 
					 console.log(status); 
					 console.log(error); 				 
					}
				});
		}); // Promise						
	}

	// Generate [ Non Streaming ] : SEO Title
	function scWordAIWriteSeoTitle( hintsData ) {		
		let params 					= {};
		params.prompt				= hintsData;	
		// params.postID				= wp.data.select("core/editor").getCurrentPostId();	
		// params.postTitle            = wp.data.select('core/editor').getEditedPostAttribute('title');
		return new Promise( ( resolve, reject ) => {
			scSeoTitleXHR	=	$.ajax({
				  type:"POST",
				  cache: false,
				  url: sftcy_wordai_content_generate_script_obj.adminajax_url,
				  data : {			    
						action 	 : 'sc_wordai_write_seo_titles',
						security : sftcy_wordai_content_generate_script_obj.nonce,
						params   : params
						},		  
				  success: function(data) { 
					 scWordAIContentGenerationTotalItemsTracker++; 							 
					 resolve( data ); 
					//  console.log(data); 
					},
				  error: function( xhr, status, error ) { 
					 scWordAIContentGenerationTotalItemsTracker++;  							 
					 scWordAIRejectAjaxError(reject, xhr, error);
					 console.log(xhr); 
					 console.log(status); 
					 console.log(error); 				 
					}
				});
		}); // Promise						
	}

	// Generate [ Non Streaming ] : SEO Meta Description
	function scWordAIWriteSeoMetaDescription( hintsData ) {
		let params 					= {};
		params.prompt				= hintsData;	
		return new Promise( ( resolve, reject ) =>  {
			scSeoMetaDescriptionXHR	=	$.ajax({
				  type:"POST",
				  cache: false,
				  url: sftcy_wordai_content_generate_script_obj.adminajax_url,
				  data : {			    
						action 	 : 'sc_wordai_write_seo_meta_description',
						security : sftcy_wordai_content_generate_script_obj.nonce,
						params   : params
						},		  
				  success: function(data) { 
					 scWordAIContentGenerationTotalItemsTracker++; 				 
					 resolve( data ); 
					 console.log(data); 
					},
				  error: function( xhr, status, error ) { 
					 scWordAIContentGenerationTotalItemsTracker++;				 
					 scWordAIRejectAjaxError(reject, xhr, error);
					 console.log(xhr); 
					 console.log(status); 
					 console.log(error); 				 
					}
				});
		}); // Promise			
	}

	// Generate [ Non Streaming ] : SEO Meta Focus Keywrord
	function scWordAIWriteSeoMetaFocusKeyword( hintsData ) {
		let params 					= {};
		params.prompt				= hintsData;	
		return new Promise( ( resolve, reject ) =>  {
			scSeoMetaFocusKeywordXHR =	$.ajax({
				  type:"POST",
				  cache: false,
				  url: sftcy_wordai_content_generate_script_obj.adminajax_url,
				  data : {			    
						action 	 : 'sc_wordai_write_seo_meta_focus_keyword',
						security : sftcy_wordai_content_generate_script_obj.nonce,
						params   : params
						},		  
				  success: function(data) { 
					 scWordAIContentGenerationTotalItemsTracker++; 				 
					 resolve( data ); 
					 console.log(data); 
					},
				  error: function( xhr, status, error ) { 
					 scWordAIContentGenerationTotalItemsTracker++;				 
					 scWordAIRejectAjaxError(reject, xhr, error);
					 console.log(xhr); 
					 console.log(status); 
					 console.log(error); 				 
					}
				});
		}); // Promise			
	}

	// Generate [ Non Streaming ] : Image Alt Text
	function scWordAIWriteImageAltText( hintsData ) {
		let params 					= {};
		params.prompt				= hintsData;
		return new Promise( ( resolve, reject ) =>  {
			scImageAltTextXHR = $.ajax({
				  type:"POST",
				  cache: false,
				  url: sftcy_wordai_content_generate_script_obj.adminajax_url,
				  data : {
						action 	 : 'sc_wordai_write_image_alt_text',
						security : sftcy_wordai_content_generate_script_obj.nonce,
						params   : params
						},
				  success: function(data) {
					 scWordAIContentGenerationTotalItemsTracker++;
					 resolve( data );
					},
				  error: function( xhr, status, error ) {
					 scWordAIContentGenerationTotalItemsTracker++;
					 scWordAIRejectAjaxError(reject, xhr, error);
					}
				});
		});
	}

		
	
	/**
	 * =================================================================================================================
	 * Generate : Images - Both Streaming and Non Streaming - Clean, Stable Image Generation Function (OpenAI + Gemini)
	 * =================================================================================================================
	 */
	// function scWordAIGenerateImages(hintsData) {

	// 	let promptAlertMsg                    = $('.prompt-alert-msg');
	// 	let imagesWrapper                     = $('.scwordai-image');
	// 	let imagesSaveToGalleryStatus         = $('.sc-wordai-generated-images-save-to-gallery-status').val();
	// 	let scWordAIWillGenerateImageNumber   = parseInt($('.sc-wordai-will-generate-images-number').val());
	// 	let scWordAISelectedImageModelElement = $('.sc-wordai-generated-images-model-name');

	// 	// avoid repetitive errors when generating multiple images
	// 	let geminiErrorShown = false;

	// 	let params = { prompt: hintsData };

	// 	return new Promise((resolve, reject) => {

	// 		scImagesXHR = $.ajax({
	// 			type: "POST",
	// 			cache: false,
	// 			url: sftcy_wordai_content_generate_script_obj.adminajax_url,
	// 			data: {
	// 				action: 'sc_wordai_generate_image',
	// 				security: sftcy_wordai_content_generate_script_obj.nonce,
	// 				params: params
	// 			},

	// 			success: function (data) {

	// 				scWordAITotalImageGenerationTracker++;

	// 				// mark completion of image tasks
	// 				if (scWordAIWillGenerateImageNumber == scWordAITotalImageGenerationTracker) {
	// 					scWordAIContentGenerationTotalItemsTracker++;
	// 				}

	// 				let jsonData = {};

	// 				try {
	// 					jsonData = JSON.parse(data);
	// 				} catch (e) {
	// 					promptAlertMsg.append(
	// 						'<span class="alert-error">' +
	// 						sftcy_wordai_content_generate_script_obj?.something_went_wrong_images +
	// 						'</span><br/>'
	// 					);
	// 					scWordAIHideWaveAnimationWithButtonActivation();
	// 					reject('Invalid JSON');
	// 					return;
	// 				}

	// 				// ===============================
	// 				//  SUCCESS CASE (OpenAI + Gemini)
	// 				// ===============================
	// 				if (jsonData.status === 'success') {

	// 					imagesWrapper.fadeIn(300);

	// 					// store selected model name
	// 					if (jsonData.selectedImageModel) {
	// 						scWordAISelectedImageModelElement.val(jsonData.selectedImageModel);
	// 					}

	// 					// collect URLs
	// 					let previousUrls = $('.sc-wordai-generated-images-urls').val();
	// 					let existingArr = previousUrls ? previousUrls.split(',') : [];
	// 					let finalArr = existingArr.concat(jsonData.openAIImgURLs);

	// 					$('.sc-wordai-generated-images-urls').val(finalArr.join(','));

	// 					// render images
	// 					jsonData.openAIImgURLs.forEach((url) => {
	// 						$('.sc-wordai-generated-image-wrapper')
	// 							.append('<div class="each-img-wrapper-div"><img src="' + url + '" alt=""></div>');
	// 					});

	// 					resolve(jsonData);
	// 					return;
	// 				}

	// 				// ===============================
	// 				//       FAIL CASE
	// 				// ===============================
	// 				if (jsonData.status === 'fail') {

	// 					let errMsg = jsonData.errorMessage || jsonData.wordAIAPIKeyMissing || '';						


	// 					// Gemini free tier (only show once)
	// 					if (jsonData.errorType === 'gemini_free_tier_image_blocked' && errMsg.length > 0 ) {
	// 						if (!geminiErrorShown) {
	// 							geminiErrorShown = true;
	// 							promptAlertMsg.append(
	// 								'<span class="alert-error">' + errMsg + '</span><br/>'
	// 							);
	// 						}
	// 						scWordAIHideWaveAnimationWithButtonActivation();
	// 						reject(errMsg);
	// 						return;
	// 					}

	// 					// Missing API key
	// 					if (jsonData.wordAIAPIKeyMissing && jsonData.wordAIAPIKeyMissing.length > 0) {
	// 						promptAlertMsg.append(
	// 							'<span class="alert-error">' + jsonData.wordAIAPIKeyMissing + '</span><br/>'
	// 						);
	// 						scWordAIHideWaveAnimationWithButtonActivation();
	// 						reject(jsonData.wordAIAPIKeyMissing);
	// 						return;
	// 					}

	// 					// General Gemini / OpenAI error
	// 					// if (errMsg) {
	// 					if (errMsg && errMsg.length > 0) {
	// 						promptAlertMsg.append('<span class="alert-error">' + errMsg + '</span><br/>');
	// 						scWordAIHideWaveAnimationWithButtonActivation();
	// 						reject(errMsg);
	// 						return;
	// 					}

	// 					// fallback
	// 					promptAlertMsg.append(
	// 						'<span class="alert-error">' +
	// 						sftcy_wordai_content_generate_script_obj.something_went_wrong_images +
	// 						'</span><br/>'
	// 					);
	// 					scWordAIHideWaveAnimationWithButtonActivation();
	// 					reject('Unknown error');
	// 					return;
	// 				}

	// 				// Unexpected
	// 				promptAlertMsg.append(
	// 					'<span class="alert-error">' +
	// 					sftcy_wordai_content_generate_script_obj.something_went_wrong_images +
	// 					'</span><br/>'
	// 				);
	// 				scWordAIHideWaveAnimationWithButtonActivation();
	// 				reject('Unexpected response');

	// 			}, // success

	// 			error: function (xhr, status, error) {

	// 				scWordAITotalImageGenerationTracker++;

	// 				if (scWordAIWillGenerateImageNumber == scWordAITotalImageGenerationTracker) {
	// 					scWordAIContentGenerationTotalItemsTracker++;
	// 				}

	// 				console.log(xhr, status, error);

	// 				promptAlertMsg.append(
	// 					'<span class="alert-error">' +
	// 					sftcy_wordai_content_generate_script_obj.something_went_wrong_images +
	// 					'</span><br/>'
	// 				);
	// 				scWordAIHideWaveAnimationWithButtonActivation();

	// 				scWordAIRejectAjaxError(reject, xhr, error);
	// 			}
	// 		});
	// 	});
	// }

	

	/**
	 * =================================================================================================================
	 * Generate : Images - Both Streaming and Non Streaming - Clean, Stable Image Generation Function (OpenAI + Gemini)
	 * =================================================================================================================
	 *
	 * Fixes (without removing your logic):
	 * - Never prints "undefined" (all user-facing strings are normalized)
	 * - Prevents duplicate/error-fallback lines if an error message was already shown
	 * - Ensures reject() always has a safe message string
	 * - Keeps all counters, resolve/reject, wave animation behavior, and branches intact
	 */
	function scWordAIGenerateImages(hintsData) {

		let promptAlertMsg                    = $('.prompt-alert-msg');
		let imagesWrapper                     = $('.scwordai-image');
		let imagesSaveToGalleryStatus         = $('.sc-wordai-generated-images-save-to-gallery-status').val();
		let scWordAIWillGenerateImageNumber   = parseInt($('.sc-wordai-will-generate-images-number').val(), 10);
		scWordAIWillGenerateImageNumber       = Number.isFinite(scWordAIWillGenerateImageNumber) && scWordAIWillGenerateImageNumber > 0 ? scWordAIWillGenerateImageNumber : 1;
		let scWordAISelectedImageModelElement = $('.sc-wordai-generated-images-model-name');

		// avoid repetitive errors when generating multiple images (NOTE: resets per call, same as your original)
		let geminiErrorShown = false;

		let params = { prompt: hintsData };

		/**
		 * Safe localized fallback message:
		 * - Uses localized string if provided
		 * - Otherwise uses hard-coded fallback
		 * - Prevents "undefined" ever appearing in UI
		 */
		const FALLBACK_IMG_ERR =
			(sftcy_wordai_content_generate_script_obj?.something_went_wrong_images ?? 'Something went wrong while generating images.');

		/**
		 * Normalize any value to a safe printable string (never "undefined")
		 */
		const safeText = (v) => {
			if (typeof v !== 'string') return '';
			const t = v.trim();
			return t.length ? t : '';
		};

		/**
		 * Append message only if it's valid, and track that we already showed something
		 */
		let didShowErrorToUser = false;
		const appendErrorMsg = (msg) => {
			const m = safeText(msg);
			if (m) {
				scWordAIAppendFeedback('error', m);
				didShowErrorToUser = true;
			}
		};

		return new Promise((resolve, reject) => {

			/**
			 * Reject with a safe string (prevents undefined in any outer catch handlers)
			 */
			const rejectSafe = (msg) => {
				reject(safeText(msg) || FALLBACK_IMG_ERR);
			};

			scImagesXHR = $.ajax({
				type: "POST",
				cache: false,
				url: sftcy_wordai_content_generate_script_obj.adminajax_url,
				data: {
					action: 'sc_wordai_generate_image',
					security: sftcy_wordai_content_generate_script_obj.nonce,
					params: params
				},

				success: function (data) {

					scWordAITotalImageGenerationTracker++;

					// mark completion of image tasks
					if (scWordAIWillGenerateImageNumber == scWordAITotalImageGenerationTracker) {
						scWordAIContentGenerationTotalItemsTracker++;
					}

					let jsonData = {};

					try {
						jsonData = JSON.parse(data);
					} catch (e) {
						// Invalid JSON → show fallback once (safe)
						appendErrorMsg(FALLBACK_IMG_ERR);
						scWordAIHideWaveAnimationWithButtonActivation();
						rejectSafe('Invalid JSON');
						return;
					}

					// ===============================
					//  SUCCESS CASE (OpenAI + Gemini)
					// ===============================
					if (jsonData.status === 'success') {

						imagesWrapper.fadeIn(300);

						// store selected model name
						if (jsonData.selectedImageModel) {
							scWordAISelectedImageModelElement.val(jsonData.selectedImageModel);
						}

						// collect URLs (guard against non-array)
						let previousUrls = $('.sc-wordai-generated-images-urls').val();
						let existingArr = previousUrls ? previousUrls.split(',') : [];

						const urls = Array.isArray(jsonData.openAIImgURLs) ? jsonData.openAIImgURLs.filter(Boolean) : [];
						if (!urls.length) {
							const msg = safeText(jsonData?.errorMessage ?? '') || FALLBACK_IMG_ERR;
							appendErrorMsg(msg);
							scWordAIShowImageResultError(msg);
							scWordAIHideWaveAnimationWithButtonActivation();
							rejectSafe(msg);
							return;
						}

						let finalArr = existingArr.concat(urls);

						$('.sc-wordai-generated-images-urls').val(finalArr.join(','));
						if (Number(imagesSaveToGalleryStatus || 0) !== 1) {
							$('.sc-wordai-save-to-gallery-row').removeAttr('hidden').show();
						}

						// render selectable thumbnails; attachment IDs are attached after media upload succeeds.
						urls.forEach((url) => {
							const $thumb = $('<button/>', {
								type: 'button',
								class: 'each-img-wrapper-div wordai-generated-image-thumb',
								'data-image-url': url,
								title: 'Set featured image'
							});

							$thumb
								.append($('<img/>', { src: url, alt: '' }))
								.append($('<span/>', {
									class: 'wordai-generated-image-overlay',
									text: 'Set featured image'
								}));

							$('.sc-wordai-generated-image-wrapper').append($thumb);
						});

						resolve(jsonData);
						return;
					}

					// ===============================
					//       FAIL CASE
					// ===============================
					if (jsonData.status === 'fail') {

						// Safe error message extraction (never undefined)
						let errMsg = safeText(jsonData?.errorMessage ?? jsonData?.feedbackMsg ?? jsonData?.wordAIAPIKeyMissing ?? '');

						// Gemini free tier (only show once per call - same behavior you intended)
						if (jsonData.errorType === 'gemini_free_tier_image_blocked' && errMsg.length > 0) {

							if (!geminiErrorShown) {
								geminiErrorShown = true;
								appendErrorMsg(errMsg);
							}

							scWordAIShowImageResultError(errMsg);
							scWordAIHideWaveAnimationWithButtonActivation();
							rejectSafe(errMsg);
							return;
						}

						// Missing API key
						if (safeText(jsonData?.wordAIAPIKeyMissing).length > 0) {
							appendErrorMsg(jsonData.wordAIAPIKeyMissing);
							scWordAIShowImageResultError(jsonData.wordAIAPIKeyMissing);
							scWordAIHideWaveAnimationWithButtonActivation();
							rejectSafe(jsonData.wordAIAPIKeyMissing);
							return;
						}

						// General Gemini / OpenAI error
						if (errMsg.length > 0) {
							appendErrorMsg(errMsg);
							scWordAIShowImageResultError(errMsg);
							scWordAIHideWaveAnimationWithButtonActivation();
							rejectSafe(errMsg);
							return;
						}

						/**
						 * Fallback ONLY if nothing was shown already
						 * (prevents: "Gemini message" + "undefined" / extra line)
						 */
						if (!didShowErrorToUser) {
							appendErrorMsg(FALLBACK_IMG_ERR);
						}

						scWordAIShowImageResultError(FALLBACK_IMG_ERR);
						scWordAIHideWaveAnimationWithButtonActivation();
						rejectSafe('Unknown error');
						return;
					}

					// Unexpected response
					if (!didShowErrorToUser) {
						appendErrorMsg(FALLBACK_IMG_ERR);
					}
					scWordAIShowImageResultError(FALLBACK_IMG_ERR);
					scWordAIHideWaveAnimationWithButtonActivation();
					rejectSafe('Unexpected response');

				}, // success

				error: function (xhr, status, error) {

					scWordAITotalImageGenerationTracker++;

					if (scWordAIWillGenerateImageNumber == scWordAITotalImageGenerationTracker) {
						scWordAIContentGenerationTotalItemsTracker++;
					}

					console.log(xhr, status, error);

					// Ajax error fallback (safe)
					const ajaxError = scWordAIExtractAjaxError(xhr, error);
					appendErrorMsg(ajaxError);
					scWordAIShowImageResultError(ajaxError);
					scWordAIHideWaveAnimationWithButtonActivation();

					rejectSafe(ajaxError);
				}
			});
		});
	}

	


	// Generate [Streaming] : Title
	function scWordAIStreamingTitle(hintsData) {

		let titleWrapper  = $('.scwordai-title');
		let promptAlertMsg = $('.prompt-alert-msg');
		let params = { prompt: hintsData };

		let scChunkResponse = '';
		let scCompleteResponse = '';
		let scWordAIResponseErrorMessage = '';

		return new Promise((resolve, reject) => {

			scTitleXHR = $.ajax({
				type: "POST",
				cache: false,
				url: sftcy_wordai_content_generate_script_obj.adminajax_url,
				data: {
					action: 'sc_wordai_write_titles',
					security: sftcy_wordai_content_generate_script_obj.nonce,
					params: params
				},
				xhrFields: {
					onprogress: function (e) {

						titleWrapper.fadeIn(300);

						scChunkResponse = e.target.response;

						// Provider aware (OpenAI / Gemini)
						scCompleteResponse = scWordAIParseStreamingChunk(scChunkResponse);
						
						// Detect streaming errors (Gemini / OpenAI)
						if (Array.isArray(scCompleteResponse) && scCompleteResponse[0]?.errorData) {

							let err = scCompleteResponse[0];

							// ✅ API key missing = fatal stop all generation
							if (err.errorType === 'api_key_missing') {
								if (typeof window.scWordAIStopAllContentGeneration === 'function') {
									window.scWordAIStopAllContentGeneration(err.errorData);
								}
							}

							// Gemini free-tier content or image block
							if (
								err.errorType === 'gemini_free_tier_content_blocked' ||
								err.errorType === 'gemini_free_tier_image_blocked'
							) {
								scWordAIResponseErrorMessage =
									sftcy_wordai_content_generate_script_obj.google_gemini_free_tier_error;
							}
							else {
								// Normal error message from provider
								scWordAIResponseErrorMessage = err.errorData;
							}

							return;
						}

						// Clean quotes
						let clean = scCompleteResponse.replace(/^["']+|["']+$/g, '');
						$('.sc-wordai-generated-title').val(clean);
					}
				},
				success: function (data) {

					scWordAIContentGenerationTotalItemsTracker++;

					if (scWordAIResponseErrorMessage.length !== 0) {
						titleWrapper.fadeOut(300);
						scWordAIAppendFeedback('error', scWordAIResponseErrorMessage);
						reject(scWordAIResponseErrorMessage);
					} else {
						promptAlertMsg.append(
							'<span class="alert-success">' +
							sftcy_wordai_content_generate_script_obj.generated_title_success +
							'</span><br/>'
						);
						resolve(data);
					}
				},
				error: function (xhr, status, error) {
					scWordAIContentGenerationTotalItemsTracker++;
					scWordAIRejectAjaxError(reject, xhr, error);
				}
			});

		});
	}
	
	
	// Generate[Streaming] : Content
	function scWordAIStreamingContent(hintsData) {

		let contentWrapper   = $('.scwordai-content');
		let waveAnimationRow = $('#metabox-button-click-dialog .wave-animation-row');	
		let promptAlertMsg   = $('.prompt-alert-msg');

		let params = { prompt: hintsData };

		let scChunkResponse              = '';
		let scCompleteResponse           = '';
		let scWordAIResponseErrorMessage = '';

		return new Promise((resolve, reject) => {

			scContentXHR = $.ajax({
				type: "POST",
				cache: false,
				url: sftcy_wordai_content_generate_script_obj.adminajax_url,
				data: {
					action: 'sc_wordai_write_content',
					security: sftcy_wordai_content_generate_script_obj.nonce,
					params: params
				},

				xhrFields: {
					onprogress: function (e) {

						contentWrapper.fadeIn(300);

						scChunkResponse = e.target.response;

						// AUTO-PROVIDER PARSER (OpenAI or Gemini)
						// ✅ For CONTENT we must preserve paragraph/heading formatting for Gemini
						scCompleteResponse = scWordAIParseStreamingChunk(scChunkResponse, { preserveFormatting: true });						
						// scCompleteResponse = scWordAIParseStreamingChunk(scChunkResponse);

						// Detect streaming errors (Gemini / OpenAI)
						if (Array.isArray(scCompleteResponse) && scCompleteResponse[0]?.errorData) {

							let err = scCompleteResponse[0];

							// ✅ API key missing = fatal stop all generation
							if (err.errorType === 'api_key_missing') {
								if (typeof window.scWordAIStopAllContentGeneration === 'function') {
									window.scWordAIStopAllContentGeneration(err.errorData);
								}
							}

							// Gemini free-tier content or image block
							if (
								err.errorType === 'gemini_free_tier_content_blocked' ||
								err.errorType === 'gemini_free_tier_image_blocked'
							) {
								scWordAIResponseErrorMessage =
									sftcy_wordai_content_generate_script_obj.google_gemini_free_tier_error;
							}
							else {
								// Normal error message from provider
								scWordAIResponseErrorMessage = err.errorData;
							}

							return;
						}

						const scCleanCompleteResponse = scWordAINormalizeGeneratedContentHtml(scWordAIStripMarkdownPreserveParagraphs(scCompleteResponse));

						// Update live textarea for users
						$('.sc-wordai-generated-content').val(scCleanCompleteResponse);

						// BR version for Gutenberg UI
						$('.sc-wordai-replace-withbr-response-format-content')
							.val(
								scCleanCompleteResponse
									.replace(/\n/g, "<br>")
									.replace(/###|##|#/g, "")
							);
					}
				},

				success: function (data) {

					scWordAIContentGenerationTotalItemsTracker++;

					if (!scCompleteResponse) {
						const scFallbackResponse = scWordAIGetResponseTextFromJson(data, { preserveFormatting: true });

						if (scFallbackResponse) {
							const scCleanCompleteResponse = scWordAINormalizeGeneratedContentHtml(scWordAIStripMarkdownPreserveParagraphs(scFallbackResponse));

							$('.sc-wordai-generated-content').val(scCleanCompleteResponse);
							$('.sc-wordai-replace-withbr-response-format-content')
								.val(
									scCleanCompleteResponse
										.replace(/\n/g, "<br>")
										.replace(/###|##|#/g, "")
								);
						}
					}

					if (scWordAIResponseErrorMessage.length != 0) {
						contentWrapper.fadeOut(300);
						scWordAIAppendFeedback('error', scWordAIResponseErrorMessage);
						reject(scWordAIResponseErrorMessage);
					} else {
						promptAlertMsg.append(`
							<span class="alert-success">
								${sftcy_wordai_content_generate_script_obj.generated_content_success}
							</span><br/>
						`);
						resolve(data);
					}
				},

				error: function (xhr, status, error) {
					scWordAIContentGenerationTotalItemsTracker++;
					console.log(xhr, status, error);
					scWordAIRejectAjaxError(reject, xhr, error);
				}

			});
		});
	}

	
	// Generate [Streaming] : Excerpt
	function scWordAIStreamingExcerpt(hintsData) {

		let excerptWrapper  = $('.scwordai-excerpt');
		let promptAlertMsg  = $('.prompt-alert-msg');

		let params = { prompt: hintsData };

		let scChunkResponse           = '';
		let scCompleteResponse        = '';
		let scWordAIResponseErrorMessage = '';

		return new Promise((resolve, reject) => {

			scExcerptXHR = $.ajax({
				type: "POST",
				cache: false,
				url: sftcy_wordai_content_generate_script_obj.adminajax_url,
				data: {
					action: 'sc_wordai_write_excerpt',
					security: sftcy_wordai_content_generate_script_obj.nonce,
					params: params
				},
				xhrFields: {
					onprogress: function (e) {

						excerptWrapper.fadeIn(300);

						scChunkResponse = e.target.response;

						// 🔥 provider-aware parser: OpenAI or Google
						scCompleteResponse = scWordAIParseStreamingChunk(scChunkResponse);

						// Detect streaming errors (Gemini / OpenAI)
						if (Array.isArray(scCompleteResponse) && scCompleteResponse[0]?.errorData) {

							let err = scCompleteResponse[0];

							// ✅ API key missing = fatal stop all generation
							if (err.errorType === 'api_key_missing') {
								if (typeof window.scWordAIStopAllContentGeneration === 'function') {
									window.scWordAIStopAllContentGeneration(err.errorData);
								}
							}

							// Gemini free-tier content or image block
							if (
								err.errorType === 'gemini_free_tier_content_blocked' ||
								err.errorType === 'gemini_free_tier_image_blocked'
							) {
								scWordAIResponseErrorMessage =
									sftcy_wordai_content_generate_script_obj.google_gemini_free_tier_error;
							}
							else {
								// Normal error message from provider
								scWordAIResponseErrorMessage = err.errorData;
							}

							return;
						}

						// Clean beginning/ending quotes
						let cleaned = scCompleteResponse.replace(/^["']+|["']+$/g, '');

						$('.sc-wordai-generated-excerpt').val(cleaned);
						$('.sc-wordai-replace-withbr-response-format-excerpt')
							.val(cleaned.replace(/\n/g, "<br>"));
					}
				},
				success: function (data) {

					scWordAIContentGenerationTotalItemsTracker++;

					if (scWordAIResponseErrorMessage.length !== 0) {
						excerptWrapper.fadeOut(300);
						scWordAIAppendFeedback('error', scWordAIResponseErrorMessage);
						reject(scWordAIResponseErrorMessage);
					} else {
						promptAlertMsg.append(
							'<span class="alert-success">' +
							sftcy_wordai_content_generate_script_obj.generated_excerpt_success +
							'</span><br/>'
						);
						resolve(data);
					}
				},
				error: function (xhr, status, error) {
					scWordAIContentGenerationTotalItemsTracker++;
					scWordAIRejectAjaxError(reject, xhr, error);
				}
			});

		});
	}

	
	// Generate [Streaming] : Tags
	function scWordAIStreamingTags(hintsData) {

		let tagsWrapper      = $('.scwordai-tags');
		let promptAlertMsg   = $('.prompt-alert-msg');

		let params = { prompt: hintsData };

		let scChunkResponse = '';
		let scCompleteResponse = '';
		let scWordAIResponseErrorMessage = '';

		return new Promise((resolve, reject) => {

			scTagsXHR = $.ajax({
				type: "POST",
				cache: false,
				url: sftcy_wordai_content_generate_script_obj.adminajax_url,
				data: {
					action: 'sc_wordai_write_tags',
					security: sftcy_wordai_content_generate_script_obj.nonce,
					params: params
				},
				xhrFields: {
					onprogress: function (e) {

						tagsWrapper.fadeIn(300);

						scChunkResponse = e.target.response;

						// 🔥 Provider aware parser (OpenAI / Gemini)
						scCompleteResponse = scWordAIParseStreamingChunk(scChunkResponse);

						// Detect streaming errors (Gemini / OpenAI)
						if (Array.isArray(scCompleteResponse) && scCompleteResponse[0]?.errorData) {

							let err = scCompleteResponse[0];

							// ✅ API key missing = fatal stop all generation
							if (err.errorType === 'api_key_missing') {
								if (typeof window.scWordAIStopAllContentGeneration === 'function') {
									window.scWordAIStopAllContentGeneration(err.errorData);
								}
							}

							// Gemini free-tier content or image block
							if (
								err.errorType === 'gemini_free_tier_content_blocked' ||
								err.errorType === 'gemini_free_tier_image_blocked'
							) {
								scWordAIResponseErrorMessage =
									sftcy_wordai_content_generate_script_obj.google_gemini_free_tier_error;
							}
							else {
								// Normal error message from provider
								scWordAIResponseErrorMessage = err.errorData;
							}

							return;
						}

						// Clean beginning/ending quotes + newlines
						let cleaned = scCompleteResponse
							.replace(/^["']+|["']+$/g, '')
							.replace(/\n/g, '')
							.replace(/\\/g, '');

						$('.sc-wordai-generated-tags').val(cleaned);
					}
				},
				success: function (data) {

					scWordAIContentGenerationTotalItemsTracker++;

					if (scWordAIResponseErrorMessage.length !== 0) {
						tagsWrapper.fadeOut(300);
						scWordAIAppendFeedback('error', scWordAIResponseErrorMessage);
						reject(scWordAIResponseErrorMessage);
					} else {
						promptAlertMsg.append(
							'<span class="alert-success">' +
							sftcy_wordai_content_generate_script_obj.generated_tags_success +
							'</span><br/>'
						);
						resolve(data);
					}
				},
				error: function (xhr, status, error) {
					scWordAIContentGenerationTotalItemsTracker++;
					scWordAIRejectAjaxError(reject, xhr, error);
				}
			});

		});
	}

	
	// Generate [Streaming] : SEO Title
	function scWordAIStreamingSeoTitle(hintsData) {

		let seoTitleWrapper = $('.scwordai-seo-title');
		let promptAlertMsg  = $('.prompt-alert-msg');

		let params = {
			prompt: hintsData,
			// postID: wp.data.select("core/editor").getCurrentPostId(),
			// postTitle: wp.data.select('core/editor').getEditedPostAttribute('title')
		};

		let scChunkResponse = '';
		let scCompleteResponse = '';
		let scWordAIResponseErrorMessage = '';

		return new Promise((resolve, reject) => {

			scSeoTitleXHR = $.ajax({
				type: "POST",
				cache: false,
				url: sftcy_wordai_content_generate_script_obj.adminajax_url,
				data: {
					action: 'sc_wordai_write_seo_titles',
					security: sftcy_wordai_content_generate_script_obj.nonce,
					params: params
				},
				xhrFields: {
					onprogress: function (e) {

						seoTitleWrapper.fadeIn(300);

						scChunkResponse = e.target.response;

						// PROVIDER-AWARE STREAM PARSER (OpenAI or Gemini)
						scCompleteResponse = scWordAIParseStreamingChunk(scChunkResponse);

						// Detect streaming errors (Gemini / OpenAI)
						if (Array.isArray(scCompleteResponse) && scCompleteResponse[0]?.errorData) {

							let err = scCompleteResponse[0];

							// ✅ API key missing = fatal stop all generation
							if (err.errorType === 'api_key_missing') {
								if (typeof window.scWordAIStopAllContentGeneration === 'function') {
									window.scWordAIStopAllContentGeneration(err.errorData);
								}
							}

							// Gemini free-tier content or image block
							if (
								err.errorType === 'gemini_free_tier_content_blocked' ||
								err.errorType === 'gemini_free_tier_image_blocked'
							) {
								scWordAIResponseErrorMessage =
									sftcy_wordai_content_generate_script_obj.google_gemini_free_tier_error;
							}
							else {
								// Normal error message from provider
								scWordAIResponseErrorMessage = err.errorData;
							}

							return;
						}

						// Clean quotes + markdown-like crap
						let cleaned = scCompleteResponse
							.replace(/^["']+|["']+$/g, '')   // remove outer quotes
							.replace(/\n/g, '')              // SEO title must be 1 line
							.replace(/\\+/g, '');            // strip escape slashes

						$('.sc-wordai-generated-seo-title').val(cleaned);
					}
				},
				success: function (data) {

					scWordAIContentGenerationTotalItemsTracker++;

					if (scWordAIResponseErrorMessage.length !== 0) {
						seoTitleWrapper.fadeOut(300);
						scWordAIAppendFeedback('error', scWordAIResponseErrorMessage);
						reject(scWordAIResponseErrorMessage);
					} else {
						promptAlertMsg.append(
							'<span class="alert-success">' +
							sftcy_wordai_content_generate_script_obj.generated_seo_title_success +
							'</span><br/>'
						);
						resolve(data);
					}
				},
				error: function (xhr, status, error) {
					scWordAIContentGenerationTotalItemsTracker++;
					scWordAIRejectAjaxError(reject, xhr, error);
				}
			});

		});
	}


	// Generate [Streaming] : SEO Meta Description
	function scWordAIStreamingSeoMetaDescription(hintsData) {

		let seoMetaDescriptionWrapper = $('.scwordai-seo-meta-description');
		let promptAlertMsg = $('.prompt-alert-msg');

		let params = {
			prompt: hintsData
		};

		let scChunkResponse = '';
		let scCompleteResponse = '';
		let scWordAIResponseErrorMessage = '';

		return new Promise((resolve, reject) => {

			scSeoMetaDescriptionXHR = $.ajax({
				type: "POST",
				cache: false,
				url: sftcy_wordai_content_generate_script_obj.adminajax_url,
				data: {
					action: 'sc_wordai_write_seo_meta_description',
					security: sftcy_wordai_content_generate_script_obj.nonce,
					params: params
				},
				xhrFields: {
					onprogress: function (e) {

						seoMetaDescriptionWrapper.fadeIn(300);

						scChunkResponse = e.target.response;

						// AUTO detect OpenAI or Gemini stream response
						scCompleteResponse = scWordAIParseStreamingChunk(scChunkResponse);

						// Detect streaming errors (Gemini / OpenAI)
						if (Array.isArray(scCompleteResponse) && scCompleteResponse[0]?.errorData) {

							let err = scCompleteResponse[0];

							// ✅ API key missing = fatal stop all generation
							if (err.errorType === 'api_key_missing') {
								if (typeof window.scWordAIStopAllContentGeneration === 'function') {
									window.scWordAIStopAllContentGeneration(err.errorData);
								}
							}

							// Gemini free-tier content or image block
							if (
								err.errorType === 'gemini_free_tier_content_blocked' ||
								err.errorType === 'gemini_free_tier_image_blocked'
							) {
								scWordAIResponseErrorMessage =
									sftcy_wordai_content_generate_script_obj.google_gemini_free_tier_error;
							}
							else {
								// Normal error message from provider
								scWordAIResponseErrorMessage = err.errorData;
							}

							return;
						}

						// Clean output
						let cleaned = scCompleteResponse
							.replace(/^["']+|["']+$/g, '') // remove quote wrapping
							.replace(/\\+/g, '')           // remove escapes
							.replace(/\n+/g, ' ')          // meta desc should be one paragraph
							.trim();

						$('.sc-wordai-generated-seo-meta-description').val(cleaned);
					}
				},
				success: function (data) {

					scWordAIContentGenerationTotalItemsTracker++;

					if (scWordAIResponseErrorMessage.length !== 0) {
						seoMetaDescriptionWrapper.fadeOut(300);
						scWordAIAppendFeedback('error', scWordAIResponseErrorMessage);
						reject(scWordAIResponseErrorMessage);
					} else {
						promptAlertMsg.append(
							'<span class="alert-success">' +
							sftcy_wordai_content_generate_script_obj.generated_seo_meta_des_success +
							'</span><br/>'
						);
						resolve(data);
					}
				},
				error: function (xhr, status, error) {
					scWordAIContentGenerationTotalItemsTracker++;
					scWordAIRejectAjaxError(reject, xhr, error);
				}
			});

		});
	}


	// Generate [Streaming] : SEO Meta Focus Keyword
	function scWordAIStreamingSeoMetaFocusKeyword(hintsData) {

		let seoMetaFocusKeywordWrapper = $('.scwordai-seo-meta-focus-keyword');
		let promptAlertMsg = $('.prompt-alert-msg');

		let params = { prompt: hintsData };

		let scChunkResponse = '';
		let scCompleteResponse = '';
		let scWordAIResponseErrorMessage = '';

		return new Promise((resolve, reject) => {

			scSeoMetaFocusKeywordXHR = $.ajax({
				type: "POST",
				cache: false,
				url: sftcy_wordai_content_generate_script_obj.adminajax_url,
				data: {
					action: 'sc_wordai_write_seo_meta_focus_keyword',
					security: sftcy_wordai_content_generate_script_obj.nonce,
					params: params
				},

				xhrFields: {
					onprogress: function (e) {

						seoMetaFocusKeywordWrapper.fadeIn(300);

						scChunkResponse = e.target.response;

						scCompleteResponse = scWordAIParseStreamingChunk(scChunkResponse);

						// Detect streaming errors (Gemini / OpenAI)
						if (Array.isArray(scCompleteResponse) && scCompleteResponse[0]?.errorData) {

							let err = scCompleteResponse[0];

							// ✅ API key missing = fatal stop all generation
							if (err.errorType === 'api_key_missing') {
								if (typeof window.scWordAIStopAllContentGeneration === 'function') {
									window.scWordAIStopAllContentGeneration(err.errorData);
								}
							}

							// Gemini free-tier content or image block
							if (
								err.errorType === 'gemini_free_tier_content_blocked' ||
								err.errorType === 'gemini_free_tier_image_blocked'
							) {
								scWordAIResponseErrorMessage =
									sftcy_wordai_content_generate_script_obj.google_gemini_free_tier_error;
							}
							else {
								// Normal error message from provider
								scWordAIResponseErrorMessage = err.errorData;
							}

							return;
						}

						// 🔥 Reset error message on VALID chunk
						scWordAIResponseErrorMessage = '';

						// Clean keyword nicely
						let keyword = scCompleteResponse
							.replace(/^["']+|["']+$/g, '')
							.replace(/\\+/g, '')
							.replace(/\n+/g, ' ')
							.trim();

						$('.sc-wordai-generated-seo-meta-focus-keyword').val(keyword);
					}
				},

				success: function (data) {

					scWordAIContentGenerationTotalItemsTracker++;

					if (scWordAIResponseErrorMessage.length !== 0) {
						seoMetaFocusKeywordWrapper.fadeOut(300);
						scWordAIAppendFeedback('error', scWordAIResponseErrorMessage);
						reject(scWordAIResponseErrorMessage);
					}
					else {
						promptAlertMsg.append(
							'<span class="alert-success">' +
							sftcy_wordai_content_generate_script_obj.generated_seo_meta_focus_keyword_success +
							'</span><br/>'
						);
						resolve(data);
					}
				},

				error: function (xhr, status, error) {
					scWordAIContentGenerationTotalItemsTracker++;
					scWordAIRejectAjaxError(reject, xhr, error);
				}
			});

		});
	}

	// Generate [Streaming] : Image Alt Text
	function scWordAIStreamingImageAltText(hintsData) {

		let imageAltTextWrapper = $('.scwordai-image-alt-text');
		let promptAlertMsg = $('.prompt-alert-msg');
		let params = { prompt: hintsData };
		let scChunkResponse = '';
		let scCompleteResponse = '';
		let scWordAIResponseErrorMessage = '';

		return new Promise((resolve, reject) => {

			scImageAltTextXHR = $.ajax({
				type: "POST",
				cache: false,
				url: sftcy_wordai_content_generate_script_obj.adminajax_url,
				data: {
					action: 'sc_wordai_write_image_alt_text',
					security: sftcy_wordai_content_generate_script_obj.nonce,
					params: params
				},

				xhrFields: {
					onprogress: function (e) {

						imageAltTextWrapper.fadeIn(300);
						scChunkResponse = e.target.response;
						scCompleteResponse = scWordAIParseStreamingChunk(scChunkResponse);

						if (Array.isArray(scCompleteResponse) && scCompleteResponse[0]?.errorData) {
							let err = scCompleteResponse[0];
							if (err.errorType === 'api_key_missing' && typeof window.scWordAIStopAllContentGeneration === 'function') {
								window.scWordAIStopAllContentGeneration(err.errorData);
							}
							scWordAIResponseErrorMessage = err.errorData;
							return;
						}

						let altText = String(scCompleteResponse || '')
							.replace(/^["']+|["']+$/g, '')
							.replace(/\\+/g, '')
							.replace(/\s+/g, ' ')
							.trim();

						$('.sc-wordai-generated-image-alt-text').val(altText);
					}
				},

				success: function (data) {
					scWordAIContentGenerationTotalItemsTracker++;

					if (scWordAIResponseErrorMessage.length !== 0) {
						imageAltTextWrapper.fadeOut(300);
						scWordAIAppendFeedback('error', scWordAIResponseErrorMessage);
						reject(scWordAIResponseErrorMessage);
					}
					else {
						promptAlertMsg.append(
							'<span class="alert-success">Image alt text generated successfully.</span><br/>'
						);
						resolve(data);
					}
				},

				error: function (xhr, status, error) {
					scWordAIContentGenerationTotalItemsTracker++;
					scWordAIRejectAjaxError(reject, xhr, error);
				}
			});

		});
	}

	
	// Get Content Generation Checked Option Items
	function scWordAIContentGenerateCheckedOptions() {
		let scWordAICheckedOptions	= [];
		$('.sc-wordai-content-generate-options').each(function() {
			if ( $(this).is(':checked') && ! $(this).is(':disabled') ) {
				scWordAICheckedOptions.push( $(this).val() );
			}
		});
		return scWordAICheckedOptions;
	}

	function scWordAIWaitForImageAltTextIfNeeded(checkedItems) {
		const needsAltText = Array.isArray(checkedItems) && checkedItems.includes('imagealttext');
		if (!needsAltText) {
			return Promise.resolve();
		}

		const $panel = $('.wordai-result-panel[data-result-target="image-alt-text"]');
		return new Promise(function(resolve) {
			let elapsed = 0;
			const interval = window.setInterval(function() {
				elapsed += 150;
				if ($panel.hasClass('is-success') || $panel.hasClass('is-error') || elapsed >= 30000) {
					window.clearInterval(interval);
					resolve();
				}
			}, 150);
		});
	}
	

	// Hide wave animation - with Button activation - when requests finally complete
	async function scWordAIHideWaveAnimationWithButtonActivation() {
		let waveAnimationRow						= $('#metabox-button-click-dialog .wave-animation-row');
		let scWordAIContentGenerateButton			= $('.sc-wordai-generate-content-btn');
		let scWordAIContentGenerateStreamingButton	= $('.sc-wordai-generate-content-streaming-btn');
		let scWordAIContentGenerateCancelButton		= $('.sc-wordai-generate-cancel-requests-content-btn');

		// console.log('scWordAIContentGenerationTotalItems: '+ scWordAIContentGenerationTotalItems );
		// console.log('scWordAIContentGenerationTotalItemsTracker: '+ scWordAIContentGenerationTotalItemsTracker );
		if ( scWordAIContentGenerationTotalItems == scWordAIContentGenerationTotalItemsTracker ) {
			await scWordAIProcessAutoInsertItemsIntoEditor();
			waveAnimationRow.fadeOut(300);

			scWordAIContentGenerateCancelButton.fadeOut(100, function() {
				scWordAIContentGenerateButton.fadeIn();
				scWordAIContentGenerateStreamingButton.fadeIn();
			});

			// ✅ Unlock provider selector ONLY when everything completed
			if (typeof window.scWordAISetContentPopupBusy === 'function') {
				window.scWordAISetContentPopupBusy(false);
			}
		}
	}

	
	// Auto Insert Items Title | Content | Excerpt | Tags | SEO Title | SEO Meta Description | SEO Meta Focus Keyword
    async function scWordAIProcessAutoInsertItemsIntoEditor() {
		// Get checked Items initially requested
		let scWordAICheckedItems = scWordAIContentGenerateCheckedOptions()
		let titleItemValue = $('.sc-wordai-generate-content-post-title').val();
		let contentItemValue = $('.sc-wordai-generate-content-post-content').val();
		let excerptItemValue = $('.sc-wordai-generate-content-post-excerpt').val();
		let tagsItemValue = $('.sc-wordai-generate-content-post-tags').val();
		let seoTitleItemValue = $('.sc-wordai-generate-content-seo-title').val();
		let seoMetaDescriptionItemValue = $('.sc-wordai-generate-content-seo-meta-description').val();
		let seoMetaFocusKeywordItemValue = $('.sc-wordai-generate-content-seo-meta-focus-keyword').val();
		
		let titleInsertStatus = 0;
		let contentInsertStatus = 0;
		let excerptInsertStatus = 0;
		let tagsInsertStatus = 0;
		let seoTitleInsertStatus = 0;
		let seoMetaDescriptionInsertStatus = 0;
		let seoMetaFocusKeywordInsertStatus = 0;
		
		// Auto Insert Title - If it was checked 
		if ( $('.sc-wordai-generated-title-auto-insert-status').val() == 1 && scWordAICheckedItems.includes( titleItemValue ) ) {
			console.log('Auto Inserting Title...');
			titleInsertStatus = await sftcyWordAIInsertTitleFunc();
		} 
		// If it was NOT checked
		else {
			titleInsertStatus = 1;
		}
		
		
		// Auto Insert Content  - If it was checked
		if ( $('.sc-wordai-generated-content-auto-insert-status').val() == 1 && scWordAICheckedItems.includes( contentItemValue ) && titleInsertStatus == 1 ) {
			console.log('Auto Inserting Content...');
			contentInsertStatus = await sftcyWordAIInsertContentFunc();						
		}
		// If it was NOT checked
		else {
			contentInsertStatus = 1;
		}   									 

		// Auto Insert Excerpt  - If it was checked
		if ( $('.sc-wordai-generated-excerpt-auto-insert-status').val() == 1 && scWordAICheckedItems.includes( excerptItemValue ) && contentInsertStatus == 1 ) {	
			console.log('Auto Inserting Excerpt...');			
			excerptInsertStatus = await sftcyWordAIInsertExcerptFunc();						
		}   		
		// If it was NOT checked
		else {
			excerptInsertStatus = 1;
		}

		// Auto Insert Tags - If it was checked
		if ( $('.sc-wordai-generated-tags-auto-insert-status').val() == 1 && scWordAICheckedItems.includes( tagsItemValue ) && excerptInsertStatus == 1 ) {
			console.log('Auto Inserting Tags...');
			tagsInsertStatus = await sftcyWordAIInsertTagstFunc();
		}   					
		// If it was checked	
		else {
			tagsInsertStatus = 1;
		}
				
		// Auto Insert SEO Title - If it was checked 
		if ( $('.sc-wordai-generated-seo-title-auto-insert-status').val() == 1 && scWordAICheckedItems.includes( seoTitleItemValue ) ) {
			console.log('Auto Inserting SEO Title...');
			seoTitleInsertStatus = await sftcyWordAIInsertSeoTitleFunc();
		} 
		// If it was NOT checked
		else {
			seoTitleInsertStatus = 1;
		}
		
		// Auto Insert SEO Meta Description - If it was checked 
		if ( $('.sc-wordai-generated-seo-meta-description-auto-insert-status').val() == 1 && scWordAICheckedItems.includes( seoMetaDescriptionItemValue ) ) {
			console.log('Auto Inserting SEO Meta Description...');
			seoMetaDescriptionInsertStatus = await sftcyWordAIInsertSeoMetaDescriptionFunc();
		} 
		// If it was NOT checked
		else {
			seoMetaDescriptionInsertStatus = 1;
		}

		// Auto Insert SEO Meta Focus - If it was checked 
		if ( $('.sc-wordai-generated-seo-meta-focus-keyword-auto-insert-status').val() == 1 && scWordAICheckedItems.includes( seoMetaFocusKeywordItemValue ) ) {
			console.log('Auto Inserting SEO Meta Focus Keyword...');
			seoMetaFocusKeywordInsertStatus = await sftcyWordAIInsertSeoMetaFocusKeywordFunc();
		} 
		// If it was NOT checked
		else {
			seoMetaFocusKeywordInsertStatus = 1;
		}


	}	

	
	// Abort XHR Requests - User Request Abort
	$('body').on("click", ".sc-wordai-generate-cancel-requests-content-btn", function () {
		let waveAnimationRow                        = $('#metabox-button-click-dialog .wave-animation-row');
		let scWordAIContentGenerateButton           = $('.sc-wordai-generate-content-btn');
		let scWordAIContentGenerateStreamingButton  = $('.sc-wordai-generate-content-streaming-btn');

		// Abort XHRs safely
		if (scTitleXHR && scTitleXHR.length !== 0) scTitleXHR.abort();
		if (scContentXHR && scContentXHR.length !== 0) scContentXHR.abort();
		if (scExcerptXHR && scExcerptXHR.length !== 0) scExcerptXHR.abort();
		if (scTagsXHR && scTagsXHR.length !== 0) scTagsXHR.abort();
		if (scSeoTitleXHR && scSeoTitleXHR.length !== 0) scSeoTitleXHR.abort();
		if (scSeoMetaDescriptionXHR && scSeoMetaDescriptionXHR.length !== 0) scSeoMetaDescriptionXHR.abort();
		if (scSeoMetaFocusKeywordXHR && scSeoMetaFocusKeywordXHR.length !== 0) scSeoMetaFocusKeywordXHR.abort();
		if (scImageAltTextXHR && scImageAltTextXHR.length !== 0) scImageAltTextXHR.abort();
		if (scImagesXHR && scImagesXHR.length !== 0) scImagesXHR.abort();

		// ✅ Reset counters so "completion" logic won't misbehave
		scWordAIContentGenerationTotalItems = 0;
		scWordAIContentGenerationTotalItemsTracker = 0;
		scWordAITotalImageGenerationTracker = 0;
		if (typeof window.scWordAIResetResultPanels === 'function') {
			window.scWordAIResetResultPanels();
		}

		// ✅ Unlock provider selector immediately on cancel
		if (typeof window.scWordAISetContentPopupBusy === 'function') {
			window.scWordAISetContentPopupBusy(false);
		}

		$(this).fadeOut(100, function () {
			waveAnimationRow.fadeOut(100);
			scWordAIContentGenerateButton.fadeIn();
			scWordAIContentGenerateStreamingButton.fadeIn();
		});
	});

	
	

	/**
	 * ==========================================================
	 * Remove Markdown Syntax (JS Equivalent of PHP Helper)
	 * ----------------------------------------------------------
	 * - Removes: **bold**, *italic*, # headings, > quotes,
	 *   inline code, lists, underscores, tildes.
	 * - Keeps paragraphs & normal text structure.
	 * ==========================================================
	 */
	function scWordAIStripMarkdown(text) {
		if (!text || typeof text !== "string") return text;

		return text
			// Remove headings #### ###
			.replace(/(^|\s)#{1,6}\s*/g, ' ')
			// Remove bold/italic markers
			.replace(/\*\*(.*?)\*\*/g, '$1')
			.replace(/\*(.*?)\*/g, '$1')
			.replace(/_(.*?)_/g, '$1')
			// Remove inline code backticks
			.replace(/`([^`]*)`/g, '$1')
			// Remove blockquote marker
			.replace(/^\s*>+\s?/gm, '')
			// Remove strikethrough ~~
			.replace(/~~(.*?)~~/g, '$1')
			// Remove list markers (-, *, +, bullets)
			.replace(/^\s*(?:[-*+]|&bull;|&#8226;|&#x2022;|[•●○◦·])\s+/gm, '')
			.replace(/^\s*(?:&bull;|&#8226;|&#x2022;|[•●○◦·])\s*$/gm, '')
			// Clean extra whitespace
			.replace(/\s{2,}/g, ' ')
			.trim();
	}

	/**
	 * Strip Markdown but PRESERVE paragraph/newline structure.
	 * Use ONLY for long-form content streaming (Gemini).
	 */
	function scWordAIStripMarkdownPreserveParagraphs(text, options) {
		if (!text || typeof text !== "string") return text;
		const keepEdges = !!(options && options.keepEdges);

		const cleaned = text
			.replace(/\r\n?/g, '\n')
			// Remove heading markers but KEEP line breaks
			.replace(/^#{1,6}\s+/gm, '')
			// Remove bold/italic markers
			.replace(/(\*\*|__)([\s\S]*?)\1/g, '$2')
			.replace(/(^|[^\w])(\*|_)([^\n*_]+?)\2(?=[^\w]|$)/gm, '$1$3')
			// Remove inline code
			.replace(/`([^`]*)`/g, '$1')
			// Remove blockquote marker
			.replace(/^\s*>+\s?/gm, '')
			// Remove strikethrough
			.replace(/~~(.*?)~~/g, '$1')
			// Remove list markers (-, *, +, bullets)
			.replace(/^\s*(?:[-*+]|&bull;|&#8226;|&#x2022;|[•●○◦·])\s+/gm, '')
			.replace(/^\s*(?:&bull;|&#8226;|&#x2022;|[•●○◦·])\s*$/gm, '')
			.replace(/[ \t]+\n/g, '\n');
			// IMPORTANT: do NOT collapse whitespace/newlines

		return keepEdges ? cleaned : cleaned.trim();
	}

	function scWordAIEscapeHtml(text) {
		return String(text || '')
			.replace(/&/g, '&amp;')
			.replace(/</g, '&lt;')
			.replace(/>/g, '&gt;')
			.replace(/"/g, '&quot;')
			.replace(/'/g, '&#039;');
	}

	function scWordAINormalizeGeneratedContentHtml(content) {
		return scWordAICleanGeneratedListHtml(String(content || ''))
			.replace(/\r\n?/g, '\n')
			.replace(/```(?:html)?\s*/gi, '')
			.replace(/```/g, '')
			.replace(/<\s*script\b[^>]*>[\s\S]*?<\s*\/\s*script\s*>/gi, '')
			.replace(/<\s*style\b[^>]*>[\s\S]*?<\s*\/\s*style\s*>/gi, '')
			.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 + '>' + scWordAIEscapeHtml(text.replace(/<[^>]*>/g, '').trim()) + '</h' + level + '>';
			})
			.replace(/<h([1-6])([a-z][a-z0-9-]*)(\s[^>]*)?>\s*(?:<br\s*\/?>\s*)*/gi, function(match, level, firstWord, attrs) {
				const words = [firstWord];
				String(attrs || '').replace(/\s+([a-z][a-z0-9-]*)(?:<)?\s*=/gi, function(attrMatch, word) {
					if (!/^h[1-6]$/i.test(word)) {
						words.push(word);
					}
					return attrMatch;
				});

				const headingText = words.join(' ').toLowerCase()
					.replace(/\b\w/g, function(char) { return char.toUpperCase(); })
					.replace(/\bAi\b/g, 'AI');

				return '<h' + level + '>' + scWordAIEscapeHtml(headingText) + '</h' + level + '>\n';
			})
			.replace(/<\/h[1-6][a-z0-9_-]+>/gi, '')
			.replace(/<\/h([1-6])>\s*(?:<br\s*\/?>\s*)+/gi, '</h$1>\n')
			.replace(/>\s*</g, '>\n<')
			.replace(/^\s*(?:&bull;|&#8226;|&#x2022;|[•●○◦·])\s*$/gmi, '')
			.replace(/\n{3,}/g, '\n\n')
			.trim();
	}

	/**
	 * Provider-aware streamer
	 * Decides which streaming parser to use
 	 * @param {string} chunk
 	 * @param {object} opts { preserveFormatting?: boolean }
	 */
	// scWordAIParseStreamingChunk = function (chunk, opts = {} ) {
	// return (window.SFTCY_WORDAI_ACTIVE_PROVIDER === 'google')
	// 	? scWordAIProcessGeminiStream(chunk, opts )
	// 	: scWordAIProcessGroupOfChunkResponse(chunk);
	// };

	/**
	 * Provider-aware streamer (OpenAI / Gemini)
	 * - Also detects NON-stream JSON errors (like API key missing) early
	 * - Returns either:
	 *   - string (normal stream text)
	 *   - array([{ errorData, errorType }]) for unified error handling
	 */
	window.scWordAIParseStreamingChunk = function (chunk, opts = {}) {

		// 1) Try to detect a plain JSON response inside the chunk.
		// Sometimes server returns JSON immediately, not stream tokens.
		if (typeof chunk === 'string' && chunk.trim().length) {
			const trimmed = chunk.trim();

			// quick JSON check
			if (trimmed[0] === '{' || trimmed[0] === '[') {
				try {
					const obj = JSON.parse(trimmed);

					if (obj && obj.status === 'fail') {
						const msg = obj.wordAIAPIKeyMissing || obj.errorMessage || obj.feedbackMsg || 'Request failed.';
						return [{
							errorData: msg,
							errorType: 'api_key_missing'
						}];
					}

					const plainResponseText = scWordAIGetResponseTextFromJson(obj, opts);

					if (plainResponseText) {
						return plainResponseText;
					}
				} catch (e) {
					// not pure JSON, ignore
				}
			}
		}

		// 2) Normal provider streaming parsing
		if (window.SFTCY_WORDAI_ACTIVE_PROVIDER === 'google') {
			return scWordAIProcessGeminiStream(chunk, opts);
		}

		if (window.SFTCY_WORDAI_ACTIVE_PROVIDER === 'anthropic') {
			return scWordAIProcessAnthropicStream(chunk, opts);
		}

		return scWordAIProcessGroupOfChunkResponse(chunk, opts);
	};

	function scWordAIGetResponseTextFromJson(data, opts = {}) {
		let obj = data;

		if (typeof obj === 'string') {
			const trimmed = obj.trim();

			if (!trimmed || (trimmed[0] !== '{' && trimmed[0] !== '[')) {
				return '';
			}

			try {
				obj = JSON.parse(trimmed);
			} catch (e) {
				return '';
			}
		}

		if (!obj || typeof obj !== 'object') {
			return '';
		}

		let responseText = '';

		if (typeof obj.responseText === 'string') {
			responseText = obj.responseText;
		} else if (typeof obj.reply === 'string') {
			responseText = obj.reply;
		}

		if (!responseText) {
			return '';
		}

		return opts.preserveFormatting
			? scWordAIStripMarkdownPreserveParagraphs(responseText, { keepEdges: true })
			: scWordAIStripMarkdown(responseText.trim());
	}



	/**
	 * ==========================================================
	 * WordAI Streaming: Process SSE (Server-Sent Events)
	 * ----------------------------------------------------------
	 * - Safely parse OpenAI chunked JSON lines
	 * - Collect text deltas
	 * - Return either string or [{error, errorData}]
	 * ==========================================================
	 */
	scWordAIProcessGroupOfChunkResponse = function( scChunkResponse, opts = {} ) {
		let processedText = '';
		let errorMessages = [];
		const preserve = !!opts.preserveFormatting;

		try {
			const chunks = scChunkResponse.split("\n\n").filter(Boolean);

			for (const raw of chunks) {
				const jsonPart = raw.replace(/^data:\s*/i, '').trim();
				if (!jsonPart || jsonPart === '[DONE]') continue;

				try {
					const parsed = JSON.parse(jsonPart);

					// handle API error chunks
					if (parsed.error && parsed.error.message) {
						errorMessages.push({
							error: 'error',
							errorData: parsed.error.message
						});
						continue;
					}

					// accumulate delta content (streamed text)
					if (
						parsed.choices &&
						parsed.choices[0] &&
						parsed.choices[0].delta &&
						parsed.choices[0].delta.content
					) {
						processedText += parsed.choices[0].delta.content;
					}
				} catch (err) {
					console.debug('Skipping invalid JSON chunk:', raw);
				}
			}
		} catch (outerErr) {
			console.warn('⚠️ scWordAIProcessGroupOfChunkResponse error:', outerErr);
		}

		if (errorMessages.length > 0) {
			return errorMessages;
		}

		return preserve
			? scWordAIStripMarkdownPreserveParagraphs(processedText)
			: scWordAIStripMarkdown(processedText);
	}


	/**
	 * ===================================================================
	 * SSE Parser for Google Gemini (FINAL VERSION) - Old Working Version 
	 * -------------------------------------------------------------------
	 * - Handles multi-array chunked events
	 * - Merges text naturally (no forced line breaks)
	 * - Removes markdown using helper
	 * - Matches OpenAI streaming behavior
	 * ==========================================================
	 */
	// function scWordAIProcessGeminiStream(scChunkResponse ) {

	// 	console.log("Gemini chunk raw:", scChunkResponse);
	
	// 	let processedText = "";
	// 	let errorMessages = [];

	// 	try {
	// 		// Gemini chunks arrive as:  data:[{...}]data:[{...}]
	// 		const blocks = scChunkResponse
	// 			.split("data:")
	// 			.map(b => b.trim())
	// 			.filter(Boolean);

	// 		for (const block of blocks) {

	// 			if (!block || block === "[DONE]") continue;

	// 			let parsedAny = null;

	// 			try {
	// 				parsedAny = JSON.parse(block);
	// 			} catch (err) {
	// 				console.warn("Skip invalid Gemini JSON block:", block);
	// 				continue;
	// 			}

	// 			// Gemini returns an ARRAY of chunks
	// 			const chunkList = Array.isArray(parsedAny) ? parsedAny : [parsedAny];

	// 			chunkList.forEach(parsed => {

	// 				// Handle Gemini error object
	// 				if (parsed?.error?.message) {
	// 					errorMessages.push({
	// 						error: "error",
	// 						errorData: parsed.error.message,
	// 					});
	// 					return;
	// 				}

	// 				const parts = parsed?.candidates?.[0]?.content?.parts || [];

	// 				parts.forEach(part => {
	// 					if (!part.text) return;

	// 					let t = part.text.trim();

	// 					// Remove Markdown (same style as backend)
	// 					t = scWordAIStripMarkdown(t);

	// 					// FIX: Merge seamlessly → no \n breaks
	// 					if (processedText.length > 0) {
	// 						const lastChar = processedText.slice(-1);
	// 						if (![" ", "\n"].includes(lastChar)) {
	// 							processedText += " ";
	// 						}
	// 					}

	// 					processedText += t;
	// 				});
	// 			});
	// 		}

	// 	} catch (outerErr) {
	// 		console.warn("Gemini stream parser fatal:", outerErr);
	// 	}

	// 	// Either errors → array OR final combined string
	// 	return errorMessages.length ? errorMessages : processedText;
	// }


	/**
	 * ====================================================================
	 * SSE Parser for Google Gemini
	 * ----------------------------------------------------------
	 * - Default behavior: merges text naturally (single-line fields)
	 * - preserveFormatting=true: keeps \n and heading structure (content)
	 * ====================================================================
	 */
	function scWordAIExtractGeminiJsonBlocks(scChunkResponse) {
		const source = String(scChunkResponse || '').replace(/\r\n?/g, '\n');
		const blocks = [];
		let buffer = '';
		let depth = 0;
		let inString = false;
		let escapeNext = false;

		function pushJsonText(text) {
			const trimmed = String(text || '').trim();
			if (!trimmed || trimmed === '[DONE]') return;
			blocks.push(trimmed);
		}

		source.split(/\n/).forEach(function(line) {
			let text = line.trim();
			if (!text) return;
			if (text.indexOf('data:') === 0) {
				text = text.slice(5).trim();
			}
			if (text === '[DONE]') return;

			for (let i = 0; i < text.length; i++) {
				const char = text[i];
				buffer += char;

				if (escapeNext) {
					escapeNext = false;
					continue;
				}

				if (char === '\\' && inString) {
					escapeNext = true;
					continue;
				}

				if (char === '"') {
					inString = !inString;
					continue;
				}

				if (inString) continue;

				if (char === '{' || char === '[') {
					depth++;
				} else if (char === '}' || char === ']') {
					depth = Math.max(0, depth - 1);
					if (depth === 0 && buffer.trim()) {
						pushJsonText(buffer);
						buffer = '';
					}
				}
			}
		});

		return blocks;
	}

	function scWordAIProcessGeminiStream(scChunkResponse, opts = {}) {

	const preserve = !!opts.preserveFormatting;

	let processedText = "";
	let errorMessages = [];

	try {
		const blocks = scWordAIExtractGeminiJsonBlocks(scChunkResponse);

		for (const block of blocks) {

			if (!block || block === "[DONE]") continue;

			let parsedAny = null;

			try {
				parsedAny = JSON.parse(block);
			} catch (err) {
				// partial chunks can happen during streaming, skip safely
				continue;
			}

			const chunkList = Array.isArray(parsedAny) ? parsedAny : [parsedAny];

			chunkList.forEach(parsed => {

				// Handle Gemini error object
				if (parsed?.error?.message) {
				errorMessages.push({
					error: "error",
					errorData: parsed.error.message,
					errorType: (parsed?.error?.status || 'gemini_error').toLowerCase(),
				});
				return;
				}

					const parts = parsed?.candidates?.[0]?.content?.parts || [];

					parts.forEach(part => {
						if (!part.text) return;

						let t;

						if (preserve) {
							// ✅ Content mode: keep \n + headings/paragraph structure
							t = scWordAIStripMarkdownPreserveParagraphs(String(part.text), { keepEdges: true });
							// do NOT trim - chunk boundaries may contain leading newlines
							if (!t) return;
							processedText += t;
						} else {
							// ✅ Default mode: titles/seo/etc. single-line merge behavior
							t = scWordAIStripMarkdown(String(part.text).trim());
							if (!t) return;

							if (processedText.length > 0) {
								const lastChar = processedText.slice(-1);
								if (![" ", "\n"].includes(lastChar)) processedText += " ";
							}
							processedText += t;
						}
					});

			});

		}

	} catch (outerErr) {
		// fail safe
	}

	return errorMessages.length ? errorMessages : processedText;
	}

	function scWordAIProcessAnthropicStream(scChunkResponse, opts = {}) {

		const preserve = !!opts.preserveFormatting;
		let processedText = "";
		let errorMessages = [];

		try {
			const blocks = scChunkResponse
				.split(/\n\n+/)
				.map(block => block.trim())
				.filter(Boolean);

			for (const block of blocks) {
				const lines = block.split(/\r?\n/);
				let eventName = "";
				const dataLines = [];

				for (const line of lines) {
					if (line.indexOf("event:") === 0) {
						eventName = line.slice(6).trim();
					} else if (line.indexOf("data:") === 0) {
						dataLines.push(line.slice(5).trim());
					}
				}

				if (!dataLines.length) continue;

				let parsed;
				try {
					parsed = JSON.parse(dataLines.join("\n"));
				} catch (err) {
					continue;
				}

				if (parsed?.error?.message) {
					errorMessages.push({
						error: "error",
						errorData: parsed.error.message,
						errorType: parsed?.error?.type || "anthropic_error",
					});
					continue;
				}

				if (
					eventName === "content_block_delta" &&
					parsed?.delta?.type === "text_delta" &&
					typeof parsed?.delta?.text === "string"
				) {
					let t;

					if (preserve) {
						t = scWordAIStripMarkdownPreserveParagraphs(parsed.delta.text, { keepEdges: true });
						if (!t) continue;
						processedText += t;
					} else {
						t = scWordAIStripMarkdown(parsed.delta.text.trim());
						if (!t) continue;

						if (processedText.length > 0) {
							const lastChar = processedText.slice(-1);
							if (![" ", "\n"].includes(lastChar)) processedText += " ";
						}
						processedText += t;
					}
				}
			}
		} catch (outerErr) {
			// fail safe
		}

		return errorMessages.length ? errorMessages : processedText;
	}


	// Generate Content Button Clicks - Non Streaming - [ Title | Content | Excerpt | Tags | Images | SEO ]
	$('body').on( "click", ".sc-wordai-generate-content-btn", function() {
		scWordAIContentGenerationTotalItems				= 0;
		scWordAIContentGenerationTotalItemsTracker		= 0;
		scWordAITotalImageGenerationTracker				= 0;
		
		let scWordAIContentGenerateButton				= $(this);
		let scWordAICheckedItems						= scWordAIContentGenerateCheckedOptions();
		scWordAIContentGenerationTotalItems				= scWordAICheckedItems.length;
		// console.log( scWordAICheckedItems );
		// console.log( 'scWordAIContentGenerationTotalItems: '+ scWordAIContentGenerationTotalItems);
		let scWordAIContentGenerateCancelButton			= $('.sc-wordai-generate-cancel-requests-content-btn');
		let promptAlertMsg								= $('.prompt-alert-msg');
		let waveAnimationRow							= $('#metabox-button-click-dialog .wave-animation-row');
		let titleWrapper								= $('.scwordai-title');
		let contentWrapper								= $('.scwordai-content');
		let excerptWrapper								= $('.scwordai-excerpt');
		let tagsWrapper									= $('.scwordai-tags');

		let seoTitleWrapper								= $('.scwordai-seo-title');
		let seoMetaDescriptionWrapper					= $('.scwordai-seo-meta-description');
		let seoMetaFcocusKeywordWrapper					= $('.scwordai-seo-meta-focus-keyword');
		let imageAltTextWrapper							= $('.scwordai-image-alt-text');
		
		let imagesWrapper								= $('.scwordai-image');
		
		let params 										= {};
		params.prompt									= $('.scwordai-prompt').val();		
		let promptValidation							= { valid: true };

		if ( typeof window.scWordAIValidatePromptBeforeGenerate === 'function' ) {
			promptValidation = window.scWordAIValidatePromptBeforeGenerate() || { valid: true };
			params.prompt = $('.scwordai-prompt').val();
		}

		if ( ! promptValidation.valid ) {
			return;
		}

		if ( $.trim( params.prompt).length == 0 ) {
			scWordAISetFeedback('remind', sftcy_wordai_content_generate_script_obj.write_ur_prompt);
		} 
		else {		
			promptAlertMsg.html("");
			if ( promptValidation.info ) {
				scWordAIAppendFeedback('remind', promptValidation.info);
			}
			if ( scWordAICheckedItems.length > 0 ) {
				if (typeof window.scWordAIPrimeResultPanels === 'function') {
					window.scWordAIPrimeResultPanels(scWordAICheckedItems);
				}
				if (typeof window.scWordAIPrepareGenerationView === 'function') {
					window.scWordAIPrepareGenerationView();
				}
				scWordAISetContentPopupBusy(true); // ✅ Lock AI provider selector while generation starts running
				scWordAIContentGenerateButton.fadeOut( 400, function() { scWordAIContentGenerateCancelButton.fadeIn(); });
				waveAnimationRow.fadeIn(300, function () {
					if (typeof window.scWordAIScrollGenerationStatusIntoView === 'function') {
						window.scWordAIScrollGenerationStatusIntoView();
					}
				});
				for ( let i = 0; i < scWordAICheckedItems.length; i++ ) {					
					switch( scWordAICheckedItems[i] ) {
						case 'title':
							window.scWordAISetResultPanelState('title', 'loading');
							scWordAIWriteTitle( params.prompt ).then( (data) => {
								//   let jsonData	= JSON.parse( data );
								  let jsonData = (typeof data === "string") ? JSON.parse(data) : data;
								  if ( jsonData.status == 'success' ) {
									promptAlertMsg.append('<span class="alert-success">'+sftcy_wordai_content_generate_script_obj.generated_title_success+'</span><br/>');
									$('.sc-wordai-generated-title').val( jsonData.responseText );
									titleWrapper.fadeIn(300);  		
									window.scWordAISetResultPanelState('title', 'success');
								  }
								  else if ( jsonData.status == 'fail' ) {			
									// Special Gemini free-tier check (text + images)
										if (jsonData.errorType === 'gemini_free_tier_image_blocked' || 
											jsonData.errorType === 'gemini_free_tier_content_blocked') {

											promptAlertMsg.append(
												'<span class="alert-error">' + jsonData.google_gemini_free_tier_error + '</span><br/>'
											);

										} else {											
											// promptAlertMsg.append(
											// 	'<span class="alert-error">' + jsonData.errorMessage + '</span><br/>'
											// );
											const msg = jsonData.wordAIAPIKeyMissing || jsonData.errorMessage || jsonData.feedbackMsg || sftcy_wordai_content_generate_script_obj.something_went_wrong;
											if (jsonData.wordAIAPIKeyMissing) {
												// fatal stop all
												if (typeof window.scWordAIStopAllContentGeneration === 'function') {
													window.scWordAIStopAllContentGeneration(msg);
													return; // stop further work
												}
											}
											promptAlertMsg.append('<span class="alert-error"><i class="fa-solid fa-key"></i> ' + msg + '</span><br/>');
											window.scWordAISetResultPanelState('title', 'error');
										}											  									  
								  }
								  else {									  
									  scWordAIAppendFeedback('error', sftcy_wordai_content_generate_script_obj.something_went_wrong_title);
									  window.scWordAISetResultPanelState('title', 'error');
								  }					
								  scWordAIHideWaveAnimationWithButtonActivation(); 
							})
							.catch( (error) => {
								console.log(error);
								window.scWordAISetResultPanelState('title', 'error');
								scWordAIHideWaveAnimationWithButtonActivation();
							});
							break;
						case 'content':			
							window.scWordAISetResultPanelState('content', 'loading');
							scWordAIWriteContent( params.prompt ).then( (data) => {
								//  let jsonData	= JSON.parse( data );
								 let jsonData = (typeof data === "string") ? JSON.parse(data) : data;
								 if ( jsonData.status == 'success' ) {
									const scCleanResponseText = scWordAINormalizeGeneratedContentHtml(scWordAIStripMarkdownPreserveParagraphs(jsonData.responseText || ''));
									promptAlertMsg.append('<span class="alert-success">'+sftcy_wordai_content_generate_script_obj.generated_content_success+'</span><br/>');
									$('.sc-wordai-replace-withbr-response-format-content').val(scCleanResponseText.replace(/\n\n/g, "<br/><br/>"));
									$('.sc-wordai-generated-content').val( scCleanResponseText );
									contentWrapper.fadeIn(300); 
									window.scWordAISetResultPanelState('content', 'success');
								  }
								  else if ( jsonData.status == 'fail' ) {			
									// Special Gemini free-tier check (text + images)
										if (jsonData.errorType === 'gemini_free_tier_image_blocked' || 
											jsonData.errorType === 'gemini_free_tier_content_blocked') {

											promptAlertMsg.append(
												'<span class="alert-error">' + jsonData.google_gemini_free_tier_error + '</span><br/>'
											);

										} else {
											// promptAlertMsg.append(
											// 	'<span class="alert-error">' + jsonData.errorMessage + '</span><br/>'
											// );
											const msg = jsonData.wordAIAPIKeyMissing || jsonData.errorMessage || jsonData.feedbackMsg || sftcy_wordai_content_generate_script_obj.something_went_wrong;
											if (jsonData.wordAIAPIKeyMissing) {
												// fatal stop all
												if (typeof window.scWordAIStopAllContentGeneration === 'function') {
													window.scWordAIStopAllContentGeneration(msg);
													return; // stop further work
												}
											}
											promptAlertMsg.append('<span class="alert-error"><i class="fa-solid fa-key"></i> ' + msg + '</span><br/>');
											window.scWordAISetResultPanelState('content', 'error');
										}											  									  
								  }
								  else {
									  scWordAIAppendFeedback('error', sftcy_wordai_content_generate_script_obj.something_went_wrong_content);
									  window.scWordAISetResultPanelState('content', 'error');
								  }				
								  scWordAIHideWaveAnimationWithButtonActivation();
							})
							.catch( (error) => {
								console.log(error);
								window.scWordAISetResultPanelState('content', 'error');
								scWordAIHideWaveAnimationWithButtonActivation();
							});							
							break;
						case 'excerpt':			
							window.scWordAISetResultPanelState('excerpt', 'loading');
							scWordAIWriteExcerpt( params.prompt ).then( (data) => {
								//  let jsonData	= JSON.parse( data );
								 let jsonData = (typeof data === "string") ? JSON.parse(data) : data;
								 if ( jsonData.status == 'success' ) {
									promptAlertMsg.append('<span class="alert-success">'+sftcy_wordai_content_generate_script_obj.generated_excerpt_success+'</span><br/>');
									$('.sc-wordai-replace-withbr-response-format-excerpt').val(jsonData.responseTextWithBR);  									
									$('.sc-wordai-generated-excerpt').val( jsonData.responseText );					
									excerptWrapper.fadeIn(300); 
									window.scWordAISetResultPanelState('excerpt', 'success');
								  }
								  else if ( jsonData.status == 'fail' ) {			
									// Special Gemini free-tier check (text + images)
										if (jsonData.errorType === 'gemini_free_tier_image_blocked' || 
											jsonData.errorType === 'gemini_free_tier_content_blocked') {

											promptAlertMsg.append(
												'<span class="alert-error">' + jsonData.google_gemini_free_tier_error + '</span><br/>'
											);

										} else {
											// promptAlertMsg.append(
											// 	'<span class="alert-error">' + jsonData.errorMessage + '</span><br/>'
											// );
											const msg = jsonData.wordAIAPIKeyMissing || jsonData.errorMessage || jsonData.feedbackMsg || sftcy_wordai_content_generate_script_obj.something_went_wrong;
											if (jsonData.wordAIAPIKeyMissing) {
												// fatal stop all
												if (typeof window.scWordAIStopAllContentGeneration === 'function') {
													window.scWordAIStopAllContentGeneration(msg);
													return; // stop further work
												}
											}
											promptAlertMsg.append('<span class="alert-error"><i class="fa-solid fa-key"></i> ' + msg + '</span><br/>');
											window.scWordAISetResultPanelState('excerpt', 'error');
										}											  									  
								  }
								  else {
									  scWordAIAppendFeedback('error', sftcy_wordai_content_generate_script_obj.something_went_wrong_content);
									  window.scWordAISetResultPanelState('excerpt', 'error');
								  }				
								  scWordAIHideWaveAnimationWithButtonActivation();
							})
							.catch( (error) => {
								console.log(error);
								window.scWordAISetResultPanelState('excerpt', 'error');
								scWordAIHideWaveAnimationWithButtonActivation();
							});							
							break;	
						case 'tags':
							window.scWordAISetResultPanelState('tags', 'loading');
							scWordAIWriteTags( params.prompt ).then( (data) => {
								//   let jsonData	= JSON.parse( data );
								  let jsonData = (typeof data === "string") ? JSON.parse(data) : data;
								  if ( jsonData.status == 'success' ) {
									promptAlertMsg.append('<span class="alert-success">'+sftcy_wordai_content_generate_script_obj.generated_tags_success+'</span><br/>');
									$('.sc-wordai-generated-tags').val( jsonData.responseText );
									tagsWrapper.fadeIn(300);  		
									window.scWordAISetResultPanelState('tags', 'success');
								  }
								  else if ( jsonData.status == 'fail' ) {			
									// Special Gemini free-tier check (text + images)
										if (jsonData.errorType === 'gemini_free_tier_image_blocked' || 
											jsonData.errorType === 'gemini_free_tier_content_blocked') {

											promptAlertMsg.append(
												'<span class="alert-error">' + jsonData.google_gemini_free_tier_error + '</span><br/>'
											);

										} else {
											// promptAlertMsg.append(
											// 	'<span class="alert-error">' + jsonData.errorMessage + '</span><br/>'
											// );
											const msg = jsonData.wordAIAPIKeyMissing || jsonData.errorMessage || jsonData.feedbackMsg || sftcy_wordai_content_generate_script_obj.something_went_wrong;
											if (jsonData.wordAIAPIKeyMissing) {
												// fatal stop all
												if (typeof window.scWordAIStopAllContentGeneration === 'function') {
													window.scWordAIStopAllContentGeneration(msg);
													return; // stop further work
												}
											}
											promptAlertMsg.append('<span class="alert-error"><i class="fa-solid fa-key"></i> ' + msg + '</span><br/>');
											window.scWordAISetResultPanelState('tags', 'error');
										}											  									  
								  }
								  else {									  
									  scWordAIAppendFeedback('error', sftcy_wordai_content_generate_script_obj.something_went_wrong_title);
									  window.scWordAISetResultPanelState('tags', 'error');
								  }					
								  scWordAIHideWaveAnimationWithButtonActivation(); 
							})
							.catch( (error) => {
								console.log(error);
								window.scWordAISetResultPanelState('tags', 'error');
								scWordAIHideWaveAnimationWithButtonActivation();
							});
							break;	
							case 'seotitle':								
								window.scWordAISetResultPanelState('seotitle', 'loading');
								scWordAIWriteSeoTitle( params.prompt ).then( (data) => {
									//   let jsonData	= JSON.parse( data );
									  let jsonData = (typeof data === "string") ? JSON.parse(data) : data;
									  if ( jsonData.status == 'success' ) {
										promptAlertMsg.append('<span class="alert-success">'+sftcy_wordai_content_generate_script_obj.generated_seo_title_success+'</span><br/>');
										$('.sc-wordai-generated-seo-title').val( jsonData.responseText );
										seoTitleWrapper.fadeIn(300);  		
										window.scWordAISetResultPanelState('seotitle', 'success');
									  }
								  else if ( jsonData.status == 'fail' ) {			
									// Special Gemini free-tier check (text + images)
										if (jsonData.errorType === 'gemini_free_tier_image_blocked' || 
											jsonData.errorType === 'gemini_free_tier_content_blocked') {

											promptAlertMsg.append(
												'<span class="alert-error">' + jsonData.google_gemini_free_tier_error + '</span><br/>'
											);

										} else {											
											// promptAlertMsg.append(
											// 	'<span class="alert-error">' + jsonData.errorMessage + '</span><br/>'
											// );
											const msg = jsonData.wordAIAPIKeyMissing || jsonData.errorMessage || jsonData.feedbackMsg || sftcy_wordai_content_generate_script_obj.something_went_wrong;
											if (jsonData.wordAIAPIKeyMissing) {
												// fatal stop all
												if (typeof window.scWordAIStopAllContentGeneration === 'function') {
													window.scWordAIStopAllContentGeneration(msg);
													return; // stop further work
												}
											}
											promptAlertMsg.append('<span class="alert-error"><i class="fa-solid fa-key"></i> ' + msg + '</span><br/>');
											window.scWordAISetResultPanelState('seotitle', 'error');
										}											  									  
								  }
									  else {									  
											scWordAIAppendFeedback('error', sftcy_wordai_content_generate_script_obj.something_went_wrong_seo_title);
											window.scWordAISetResultPanelState('seotitle', 'error');
									  }					
									  scWordAIHideWaveAnimationWithButtonActivation(); 
								})
								.catch( (error) => {
									console.log(error);
									window.scWordAISetResultPanelState('seotitle', 'error');
									scWordAIHideWaveAnimationWithButtonActivation();
								});
								break;												
							case 'seometadescription':								
								window.scWordAISetResultPanelState('seometadescription', 'loading');
								scWordAIWriteSeoMetaDescription( params.prompt ).then( (data) => {
									//   let jsonData	= JSON.parse( data );
									  let jsonData = (typeof data === "string") ? JSON.parse(data) : data;
									  if ( jsonData.status == 'success' ) {
										promptAlertMsg.append('<span class="alert-success">'+sftcy_wordai_content_generate_script_obj.generated_seo_meta_des_success+'</span><br/>');
										$('.sc-wordai-generated-seo-meta-description').val( jsonData.responseText );
										seoMetaDescriptionWrapper.fadeIn(300);  		
										window.scWordAISetResultPanelState('seometadescription', 'success');
									  }
								  else if ( jsonData.status == 'fail' ) {			
									// Special Gemini free-tier check (text + images)
										if (jsonData.errorType === 'gemini_free_tier_image_blocked' || 
											jsonData.errorType === 'gemini_free_tier_content_blocked') {

											promptAlertMsg.append(
												'<span class="alert-error">' + jsonData.google_gemini_free_tier_error + '</span><br/>'
											);

										} else {
											// promptAlertMsg.append(
											// 	'<span class="alert-error">' + jsonData.errorMessage + '</span><br/>'
											// );
											const msg = jsonData.wordAIAPIKeyMissing || jsonData.errorMessage || jsonData.feedbackMsg || sftcy_wordai_content_generate_script_obj.something_went_wrong;
											if (jsonData.wordAIAPIKeyMissing) {
												// fatal stop all
												if (typeof window.scWordAIStopAllContentGeneration === 'function') {
													window.scWordAIStopAllContentGeneration(msg);
													return; // stop further work
												}
											}
											promptAlertMsg.append('<span class="alert-error"><i class="fa-solid fa-key"></i> ' + msg + '</span><br/>');
											window.scWordAISetResultPanelState('seometadescription', 'error');
										}											  									  
								  }
									  else {									  
											scWordAIAppendFeedback('error', sftcy_wordai_content_generate_script_obj.something_went_wrong_seo_meta_des);
											window.scWordAISetResultPanelState('seometadescription', 'error');
									  }					
									  scWordAIHideWaveAnimationWithButtonActivation(); 
								})
								.catch( (error) => {
									console.log(error);
									window.scWordAISetResultPanelState('seometadescription', 'error');
									scWordAIHideWaveAnimationWithButtonActivation();
								});
							break;	
							case 'seometafocuskeyword':								
								window.scWordAISetResultPanelState('seometafocuskeyword', 'loading');
								scWordAIWriteSeoMetaFocusKeyword( params.prompt ).then( (data) => {
									//   let jsonData	= JSON.parse( data );
									  let jsonData = (typeof data === "string") ? JSON.parse(data) : data;
									  console.log( jsonData );
									  if ( jsonData.status == 'success' ) {
										promptAlertMsg.append('<span class="alert-success">'+sftcy_wordai_content_generate_script_obj.generated_seo_meta_focus_keyword_success+'</span><br/>');
										$('.sc-wordai-generated-seo-meta-focus-keyword').val( jsonData.responseText );
										seoMetaFcocusKeywordWrapper.fadeIn(300);  		
										window.scWordAISetResultPanelState('seometafocuskeyword', 'success');
									  }
								      else if ( jsonData.status == 'fail' ) {			
									  // Special Gemini free-tier check (text + images)
										if (jsonData.errorType === 'gemini_free_tier_image_blocked' || 
											jsonData.errorType === 'gemini_free_tier_content_blocked') {

											promptAlertMsg.append(
												'<span class="alert-error">' + jsonData.google_gemini_free_tier_error + '</span><br/>'
											);

										} else {
											// promptAlertMsg.append(
											// 	'<span class="alert-error">' + jsonData.errorMessage + '</span><br/>'
											// );
											const msg = jsonData.wordAIAPIKeyMissing || jsonData.errorMessage || jsonData.feedbackMsg || sftcy_wordai_content_generate_script_obj.something_went_wrong;
											if (jsonData.wordAIAPIKeyMissing) {
												// fatal stop all
												if (typeof window.scWordAIStopAllContentGeneration === 'function') {
													window.scWordAIStopAllContentGeneration(msg);
													return; // stop further work
												}
											}
											promptAlertMsg.append('<span class="alert-error"><i class="fa-solid fa-key"></i> ' + msg + '</span><br/>');
											window.scWordAISetResultPanelState('seometafocuskeyword', 'error');
										}											  									  
								     }
									  else {									  
											scWordAIAppendFeedback('error', sftcy_wordai_content_generate_script_obj.something_went_wrong_seo_meta_focus_keyword);
											window.scWordAISetResultPanelState('seometafocuskeyword', 'error');
									  }					
									  scWordAIHideWaveAnimationWithButtonActivation(); 
								})
							.catch( (error) => {
									console.log(error);
									window.scWordAISetResultPanelState('seometafocuskeyword', 'error');
									scWordAIHideWaveAnimationWithButtonActivation();
								});
							break;	
							case 'imagealttext':
								window.scWordAISetResultPanelState('imagealttext', 'loading');
								scWordAIWriteImageAltText( params.prompt ).then( (data) => {
									let jsonData = (typeof data === "string") ? JSON.parse(data) : data;
									if ( jsonData.status == 'success' ) {
										promptAlertMsg.append('<span class="alert-success">Image alt text generated successfully.</span><br/>');
										$('.sc-wordai-generated-image-alt-text').val( jsonData.responseText );
										imageAltTextWrapper.fadeIn(300);
										window.scWordAISetResultPanelState('imagealttext', 'success');
									}
									else if ( jsonData.status == 'fail' ) {
										const msg = jsonData.wordAIAPIKeyMissing || jsonData.errorMessage || jsonData.feedbackMsg || sftcy_wordai_content_generate_script_obj.something_went_wrong;
										if (jsonData.wordAIAPIKeyMissing && typeof window.scWordAIStopAllContentGeneration === 'function') {
											window.scWordAIStopAllContentGeneration(msg);
											return;
										}
										scWordAIAppendFeedback('error', msg);
										window.scWordAISetResultPanelState('imagealttext', 'error');
									}
									else {
										scWordAIAppendFeedback('error', sftcy_wordai_content_generate_script_obj.something_went_wrong);
										window.scWordAISetResultPanelState('imagealttext', 'error');
									}
									scWordAIHideWaveAnimationWithButtonActivation();
								})
								.catch( (error) => {
									console.log(error);
									window.scWordAISetResultPanelState('imagealttext', 'error');
									scWordAIHideWaveAnimationWithButtonActivation();
								});
							break;
						case 'images':
							scWordAIResetImageResultUI();
							window.scWordAISetResultPanelState('images', 'loading');
							
							/**
							 * IMPORTANT:
							 * This counter MUST reset per generation run.
							 * Modal workflows do not reload the page.
							 * Removing this will break image upload after provider switching.
							 */
							scWordAITotalImageGenerationTracker = 0;

							// let imagesSaveToGalleryStatus = $('.sc-wordai-generated-images-save-to-gallery-status').val();
							let scWordAIWillGenerateImageNumber = parseInt($('.sc-wordai-will-generate-images-number').val(), 10);
							scWordAIWillGenerateImageNumber = Number.isFinite(scWordAIWillGenerateImageNumber) && scWordAIWillGenerateImageNumber > 0 ? scWordAIWillGenerateImageNumber : 1;
							console.log('scWordAIWillGenerateImageNumber: ' + scWordAIWillGenerateImageNumber);

							for (let i = 0; i < scWordAIWillGenerateImageNumber; i++) {

								scWordAIGenerateImages(params.prompt)
									.then((data) => {

										if (scWordAIWillGenerateImageNumber == scWordAITotalImageGenerationTracker) {
											if (!scWordAIGetGeneratedImageUrls().length) {
												const msg = sftcy_wordai_content_generate_script_obj.something_went_wrong_images || 'No image was returned by the selected provider.';
												scWordAIAppendFeedback('error', msg);
												scWordAIShowImageResultError(msg);
												scWordAIHideWaveAnimationWithButtonActivation();
												return;
											}

											promptAlertMsg.append(
												'<span class="alert-success">' +
												sftcy_wordai_content_generate_script_obj.generated_image_success +
												'</span><br/>'
											);

											// ✅ Read latest value (provider may have switched without reload)
											const imagesSaveToGalleryStatus = Number($('.sc-wordai-generated-images-save-to-gallery-status').val() || 0);
											console.log('then block- imagesSaveToGalleryStatus: ' + imagesSaveToGalleryStatus);

											if (imagesSaveToGalleryStatus == 1) {
												scWordAIWaitForImageAltTextIfNeeded(scWordAICheckedItems).then(function() {
													scWordAIUploadImagesWithSavetoImageGallery();
												});
											}

											window.scWordAISetResultPanelState('images', 'success');
											scWordAIHideWaveAnimationWithButtonActivation();
										}
									})
									.catch((err) => {

										if (scWordAIWillGenerateImageNumber == scWordAITotalImageGenerationTracker) {
											scWordAIShowImageResultError(err);
											scWordAIHideWaveAnimationWithButtonActivation();
										}
									});
							}
							break;



					} // switch								
				} // for loop
			} // if ( scWordAICheckedItems.length > 0 )
			else {
				scWordAISetFeedback('remind', sftcy_wordai_content_generate_script_obj.check_ur_generate_options);
			}			
		}
										
	});
			
	// Generate Content Button Clicks - Streaming - [ Title | Content | Excerpt | Tags | Images | SEO ]
	$('body').on( "click", ".sc-wordai-generate-content-streaming-btn",  function() {			

		scWordAIContentGenerationTotalItems				= 0;
		scWordAIContentGenerationTotalItemsTracker		= 0;
		
		let scWordAIContentGenerateButton				= $(this);				
		let scWordAICheckedItems						= scWordAIContentGenerateCheckedOptions();
		scWordAIContentGenerationTotalItems				= scWordAICheckedItems.length;
		// console.log( scWordAICheckedItems );
		// console.log( 'scWordAIContentGenerationTotalItems: '+ scWordAIContentGenerationTotalItems);
		let scWordAIContentGenerateCancelButton			= $('.sc-wordai-generate-cancel-requests-content-btn');
		let promptAlertMsg								= $('.prompt-alert-msg');
		let waveAnimationRow							= $('#metabox-button-click-dialog .wave-animation-row');
		
		let titleWrapper								= $('.scwordai-title');
		let titleCopyBtn                                = $('.sc-wordai-title-copy-btn');
		let titleInsertBtn                              = $('.sc-wordai-title-insert-btn');		
		
		let contentWrapper								= $('.scwordai-content');
		let contentCopyBtn                              = $('.sc-wordai-content-copy-btn');
		let contentInsertBtn                            = $('.sc-wordai-content-insert-btn');
		
		let excerptWrapper								= $('.scwordai-excerpt');
		let excerptCopyBtn                              = $('.sc-wordai-excerpt-copy-btn');
		let excerptInsertBtn                            = $('.sc-wordai-excerpt-insert-btn');
		
		let tagsWrapper									= $('.scwordai-tags');
		let tagsCopyBtn                                 = $('.sc-wordai-tags-copy-btn');
		let tagsInsertBtn                               = $('.sc-wordai-tags-insert-btn');

		let seoTitleCopyBtn								= $('.sc-wordai-seo-title-copy-btn');
		let seoTitleInsertBtn                           = $('.sc-wordai-seo-title-insert-btn');

		let seoMetaDescriptionCopyBtn                   = $('.sc-wordai-seo-meta-description-copy-btn');
		let seoMetaDescriptionInsertBtn                 = $('.sc-wordai-seo-meta-description-insert-btn');

		let seoMetaFocusKeywordCopyBtn                   = $('.sc-wordai-seo-meta-focus-keyword-copy-btn');
		let seoMetaFocusKeywordInsertBtn                 = $('.sc-wordai-seo-meta-focus-keyword-insert-btn');
		let imageAltTextCopyBtn							= $('.sc-wordai-image-alt-text-copy-btn');
		

		let seoTitleWrapper								= $('.scwordai-seo-title');
		let seoMetaDescriptionWrapper					= $('.scwordai-seo-meta-description');
		let seoMetaFocusKeywordWrapper					= $('.scwordai-seo-meta-focus-keyword');
		let imageAltTextWrapper							= $('.scwordai-image-alt-text');
				
		let imagesWrapper								= $('.scwordai-image');		
		let params 										= {};
		params.prompt									= $('.scwordai-prompt').val();		
		let promptValidation							= { valid: true };

		if ( typeof window.scWordAIValidatePromptBeforeGenerate === 'function' ) {
			promptValidation = window.scWordAIValidatePromptBeforeGenerate() || { valid: true };
			params.prompt = $('.scwordai-prompt').val();
		}

		if ( ! promptValidation.valid ) {
			return;
		}

		if ( $.trim( params.prompt).length == 0 ) {
			scWordAISetFeedback('remind', sftcy_wordai_content_generate_script_obj.write_ur_prompt);
		} 
		else {		
			promptAlertMsg.html("");
			if ( promptValidation.info ) {
				scWordAIAppendFeedback('remind', promptValidation.info);
			}
			console.log('Checked Items: ' + scWordAICheckedItems );
			if ( scWordAICheckedItems.length > 0 ) {				
				if (typeof window.scWordAIPrimeResultPanels === 'function') {
					window.scWordAIPrimeResultPanels(scWordAICheckedItems);
				}
				if (typeof window.scWordAIPrepareGenerationView === 'function') {
					window.scWordAIPrepareGenerationView();
				}
				scWordAISetContentPopupBusy(true); // ✅ Lock AI provider selector while generation starts running
				scWordAIContentGenerateButton.fadeOut( 400, function() { scWordAIContentGenerateCancelButton.fadeIn(); });
				waveAnimationRow.fadeIn(300, function () {
					if (typeof window.scWordAIScrollGenerationStatusIntoView === 'function') {
						window.scWordAIScrollGenerationStatusIntoView();
					}
				});
				for ( let i = 0; i < scWordAICheckedItems.length; i++ ) {					
					switch( scWordAICheckedItems[i] ) {
						case 'title':
							window.scWordAISetResultPanelState('title', 'loading');
							titleCopyBtn.prop( "disabled", true );
							titleInsertBtn.prop( "disabled", true );																					
							scWordAIStreamingTitle( params.prompt ).then( (data) => {
								scWordAIHideWaveAnimationWithButtonActivation(); 
								window.scWordAISetResultPanelState('title', 'success');
								titleCopyBtn.prop( "disabled", false );
								titleInsertBtn.prop( "disabled", false );																					
								
							})
							.catch( (error) => {
								console.log(error);
								// scWordAIHideWaveAnimationWithButtonActivation();
								window.scWordAISetResultPanelState('title', 'error');
								titleCopyBtn.prop( "disabled", false );
								titleInsertBtn.prop( "disabled", false );																					
								
							});
							break;
						case 'content':			
							window.scWordAISetResultPanelState('content', 'loading');
							contentCopyBtn.prop( "disabled", true );
							contentInsertBtn.prop( "disabled", true );														
							scWordAIStreamingContent( params.prompt ).then( (data) => {
								scWordAIHideWaveAnimationWithButtonActivation();								
								window.scWordAISetResultPanelState('content', 'success');
								contentCopyBtn.prop( "disabled", false );
								contentInsertBtn.prop( "disabled", false );															
							})
							.catch( (error) => {
								console.log(error);
								// scWordAIHideWaveAnimationWithButtonActivation();
								window.scWordAISetResultPanelState('content', 'error');
								contentCopyBtn.prop( "disabled", false );
								contentInsertBtn.prop( "disabled", false );							
								
							});							
							break;
						case 'excerpt':
							window.scWordAISetResultPanelState('excerpt', 'loading');
							excerptCopyBtn.prop( "disabled", true );
							excerptInsertBtn.prop( "disabled", true );																					
							scWordAIStreamingExcerpt( params.prompt ).then( (data) => {
								scWordAIHideWaveAnimationWithButtonActivation(); 								
								window.scWordAISetResultPanelState('excerpt', 'success');
								excerptCopyBtn.prop( "disabled", false );
								excerptInsertBtn.prop( "disabled", false );																													
							})
							.catch( (error) => {
								console.log(error);
								// scWordAIHideWaveAnimationWithButtonActivation();
								window.scWordAISetResultPanelState('excerpt', 'error');
								excerptCopyBtn.prop( "disabled", false );
								excerptInsertBtn.prop( "disabled", false );
							});
							break;			
						case 'tags':
							window.scWordAISetResultPanelState('tags', 'loading');
							tagsCopyBtn.prop( "disabled", true );
							tagsInsertBtn.prop( "disabled", true );																												
							scWordAIStreamingTags( params.prompt ).then( (data) => {
								scWordAIHideWaveAnimationWithButtonActivation(); 
								window.scWordAISetResultPanelState('tags', 'success');
								tagsCopyBtn.prop( "disabled", false );
								tagsInsertBtn.prop( "disabled", false );									
							})
							.catch( (error) => {
								console.log(error);
								// scWordAIHideWaveAnimationWithButtonActivation();
								window.scWordAISetResultPanelState('tags', 'error');
								tagsCopyBtn.prop( "disabled", false );
								tagsInsertBtn.prop( "disabled", false );	
							});
							break;		
						case 'seotitle':
								window.scWordAISetResultPanelState('seotitle', 'loading');
								seoTitleCopyBtn.prop( "disabled", true );
								seoTitleInsertBtn.prop( "disabled", true );																					
								scWordAIStreamingSeoTitle( params.prompt ).then( (data) => {
									scWordAIHideWaveAnimationWithButtonActivation(); 
									window.scWordAISetResultPanelState('seotitle', 'success');
									seoTitleCopyBtn.prop( "disabled", false );
									 seoTitleInsertBtn.prop( "disabled", false );																														
								})
								.catch( (error) => {
									console.log(error);									
									window.scWordAISetResultPanelState('seotitle', 'error');
									 seoTitleCopyBtn.prop( "disabled", false );
									 seoTitleInsertBtn.prop( "disabled", false );																					
									
								});
							break;	
						case 'seometadescription':
								window.scWordAISetResultPanelState('seometadescription', 'loading');
								seoMetaDescriptionCopyBtn.prop( "disabled", true );
								seoMetaDescriptionInsertBtn.prop( "disabled", true );																					
								scWordAIStreamingSeoMetaDescription( params.prompt ).then( (data) => {
									scWordAIHideWaveAnimationWithButtonActivation(); 
									window.scWordAISetResultPanelState('seometadescription', 'success');
									seoMetaDescriptionCopyBtn.prop( "disabled", false );
									seoMetaDescriptionInsertBtn.prop( "disabled", false );																														
								})
								.catch( (error) => {
									console.log(error);									
									window.scWordAISetResultPanelState('seometadescription', 'error');
									seoMetaDescriptionCopyBtn.prop( "disabled", false );
									seoMetaDescriptionInsertBtn.prop( "disabled", false );																														
								});
							break;
							case 'seometafocuskeyword':
								window.scWordAISetResultPanelState('seometafocuskeyword', 'loading');								
								seoMetaFocusKeywordCopyBtn.prop("disabled", true);
								seoMetaFocusKeywordInsertBtn.prop("disabled", true);
								scWordAIStreamingSeoMetaFocusKeyword(params.prompt).then((data) => {									
									scWordAIHideWaveAnimationWithButtonActivation();									
									window.scWordAISetResultPanelState('seometafocuskeyword', 'success');
									seoMetaFocusKeywordCopyBtn.prop("disabled", false);
									seoMetaFocusKeywordInsertBtn.prop("disabled", false);
								}).catch((error) => {
									console.log(error);									
									window.scWordAISetResultPanelState('seometafocuskeyword', 'error');
									seoMetaFocusKeywordCopyBtn.prop("disabled", false);
									seoMetaFocusKeywordInsertBtn.prop("disabled", false);									
								});

								break;
						case 'imagealttext':
							window.scWordAISetResultPanelState('imagealttext', 'loading');
							imageAltTextCopyBtn.prop("disabled", true);
							scWordAIStreamingImageAltText(params.prompt).then((data) => {
								scWordAIHideWaveAnimationWithButtonActivation();
								window.scWordAISetResultPanelState('imagealttext', 'success');
								imageAltTextWrapper.fadeIn(300);
								imageAltTextCopyBtn.prop("disabled", false);
							}).catch((error) => {
								console.log(error);
								window.scWordAISetResultPanelState('imagealttext', 'error');
								imageAltTextCopyBtn.prop("disabled", false);
							});
							break;
						case 'images':
							scWordAIResetImageResultUI();
							window.scWordAISetResultPanelState('images', 'loading');

							/**
							 * IMPORTANT:
							 * This counter MUST reset per generation run.
							 * Modal workflows do not reload the page.
							 * Removing this will break image upload after provider switching.
							 */
							scWordAITotalImageGenerationTracker = 0;

							// let imagesSaveToGalleryStatus = $('.sc-wordai-generated-images-save-to-gallery-status').val();
							let scWordAIWillGenerateImageNumber = parseInt($('.sc-wordai-will-generate-images-number').val(), 10);
							scWordAIWillGenerateImageNumber = Number.isFinite(scWordAIWillGenerateImageNumber) && scWordAIWillGenerateImageNumber > 0 ? scWordAIWillGenerateImageNumber : 1;
							console.log('scWordAIWillGenerateImageNumber: ' + scWordAIWillGenerateImageNumber);

							for (let i = 0; i < scWordAIWillGenerateImageNumber; i++) {

								scWordAIGenerateImages(params.prompt)
									.then((data) => {

										if (scWordAIWillGenerateImageNumber == scWordAITotalImageGenerationTracker) {
											if (!scWordAIGetGeneratedImageUrls().length) {
												const msg = sftcy_wordai_content_generate_script_obj.something_went_wrong_images || 'No image was returned by the selected provider.';
												scWordAIAppendFeedback('error', msg);
												scWordAIShowImageResultError(msg);
												scWordAIHideWaveAnimationWithButtonActivation();
												return;
											}

											promptAlertMsg.append(
												'<span class="alert-success">' +
												sftcy_wordai_content_generate_script_obj.generated_image_success +
												'</span><br/>'
											);

											// ✅ Read latest value (provider may have switched without reload)
											const imagesSaveToGalleryStatus = Number($('.sc-wordai-generated-images-save-to-gallery-status').val() || 0);
											console.log('then block- imagesSaveToGalleryStatus: ' + imagesSaveToGalleryStatus);

											if (imagesSaveToGalleryStatus == 1) {
												scWordAIWaitForImageAltTextIfNeeded(scWordAICheckedItems).then(function() {
													scWordAIUploadImagesWithSavetoImageGallery();
												});
											}

											window.scWordAISetResultPanelState('images', 'success');
											scWordAIHideWaveAnimationWithButtonActivation();
										}
									})
									.catch((err) => {

										if (scWordAIWillGenerateImageNumber == scWordAITotalImageGenerationTracker) {
											scWordAIShowImageResultError(err);
											scWordAIHideWaveAnimationWithButtonActivation();
										}
									});
							}
							break;


					} // switch								
				} // for loop
			} // if ( scWordAICheckedItems.length > 0 )
			else {
				scWordAISetFeedback('remind', sftcy_wordai_content_generate_script_obj.check_ur_generate_options);
			}			
		}
										
	});
						
	
}); // End jQuery(document).ready(function($)
