var scWordAIUploadImagesWithSavetoImageGallery;
var scWordAIGlobalAjax;
var scWordaiGlobalInfoDialog;
var scWordAIForceNonStreamingForProvider;


/**
 * Global runtime provider state (single source of truth)
 * Accessible from ANY JS file.
 *
 * Possible values: 'openai' | 'google' | 'anthropic' | 'xai'
 */
window.SFTCY_WORDAI_ACTIVE_PROVIDER =
  window.SFTCY_WORDAI_ACTIVE_PROVIDER ||
  window.sftcy_wordai_metabox_script_obj && window.sftcy_wordai_metabox_script_obj.active_provider ||
  '';
console.log('SFTCY_WORDAI_ACTIVE_PROVIDER: ' + window.SFTCY_WORDAI_ACTIVE_PROVIDER);  


/**
 * Force non-streaming UI flow for providers that use the stable JSON path.
 * - Because Gemini streaming is disabled / not SSE in our current implementation
 * - So streaming handlers should redirect to non-streaming equivalents
 */
scWordAIForceNonStreamingForProvider = function() {
  try {
    // You said you already have active_provider in localized object
    // Use whichever localized object is available on that page:
    const p1 = (window.sftcy_wordai_metabox_script_obj && window.sftcy_wordai_metabox_script_obj.active_provider) || "";
    const p2 = (window.sftcy_wordai_content_generate_script_obj && window.sftcy_wordai_content_generate_script_obj.active_provider) || "";
    const provider = (p1 || p2 || "").toLowerCase();
    return provider === "google" || provider === "anthropic" || provider === "xai";
  } catch (e) {
    return false;
  }
}

jQuery(document).ready(function($) {		
	console.log('Localized WordAI Misc Script ( Metabox Script Object ) Data');	
	console.log( sftcy_wordai_metabox_script_obj );	

	function scWordaiSyncOpenaiModelHint($select, $hint) {
		if (!$select.length || !$hint.length) {
			return;
		}

		var hint = $select.find('option:selected').data('model-hint') || '';
		if (hint) {
			$hint.text(hint);
		}
	}

	scWordaiSyncOpenaiModelHint($('#sc-wordai-openai-model-slug'), $('#sc-wordai-openai-model-hint'));
	$(document).on('change', '#sc-wordai-openai-model-slug', function() {
		scWordaiSyncOpenaiModelHint($(this), $('#sc-wordai-openai-model-hint'));
	});

	scWordaiSyncOpenaiModelHint($('#sc-wordai-xai-model-slug'), $('#sc-wordai-xai-model-hint'));
	$(document).on('change', '#sc-wordai-xai-model-slug', function() {
		scWordaiSyncOpenaiModelHint($(this), $('#sc-wordai-xai-model-hint'));
	});
	


	/**
	 * Refresh Featured Image preview box (classic / Woo product screens)
	 * Uses WP core ajax "get-post-thumbnail-html" to update #postimagediv UI.
	 */
	function scWordAIRefreshFeaturedImageBox(postId, attachmentId) {
		postId = parseInt(postId || 0, 10);
		attachmentId = parseInt(attachmentId || 0, 10);

		if (!postId || !attachmentId) return;

		// Update hidden field if present (classic editor + WC product editor)
		const $thumb = jQuery('#_thumbnail_id');
		if ($thumb.length) $thumb.val(attachmentId);

		// If WP ajax helper exists, use it (best)
		if (window.wp && wp.ajax && typeof wp.ajax.post === 'function') {
			// Try to find a usable nonce
			const nonce =
				jQuery('#_wpnonce').val() ||
				(window._wpnonce || '') ||
				(window.wp && wp.media && wp.media.view && wp.media.view.settings && wp.media.view.settings.nonce && wp.media.view.settings.nonce.setFeaturedImage) ||
				'';

			wp.ajax.post('get-post-thumbnail-html', {
				post_id: postId,
				thumbnail_id: attachmentId,
				_ajax_nonce: nonce
			}).done(function (html) {
				const $inside = jQuery('#postimagediv .inside');
				if ($inside.length) $inside.html(html);
			}).fail(function () {
				// If nonce mismatch etc. — UI won't refresh, but image still set in DB
				// Keep silent to avoid breaking.
			});

			return;
		}

		// Fallback: try direct metabox refresh if wp.ajax not available
		const $inside = jQuery('#postimagediv .inside');
		if ($inside.length) {
			$inside.find('img').remove(); // very light fallback (not perfect)
		}
	}

	function scWordAIGetCurrentPostId() {
		let postID = 0;

		try {
			const maybePostId = wp?.data?.select?.('core/editor')?.getCurrentPostId?.();
			if (maybePostId) postID = parseInt(maybePostId, 10);
		} catch (e) {}

		if (!postID) {
			const pid = parseInt(jQuery('#post_ID').val() || 0, 10);
			if (pid) postID = pid;
		}

		return postID || 0;
	}

	function scWordAIApplyFeaturedImage(postId, attachmentId) {
		postId = parseInt(postId || 0, 10);
		attachmentId = parseInt(attachmentId || 0, 10);

		if (!postId || !attachmentId) return;

		switch ((sftcy_wordai_metabox_script_obj?.current_posttype ?? '').toLowerCase()) {
			case 'product':
				scWordAIRefreshFeaturedImageBox(postId, attachmentId);
				break;

			case 'post':
			case 'page':
				try {
					wp.data.dispatch('core/editor').editPost({ featured_media: attachmentId });
				} catch (error) {
					console.log('Set Featured Image (Post/Page) Error:', error);
				}
				break;

			default:
				scWordAIRefreshFeaturedImageBox(postId, attachmentId);
				break;
		}
	}

	function scWordAISelectGeneratedImageThumb(attachmentId) {
		attachmentId = parseInt(attachmentId || 0, 10);
		if (!attachmentId) return;

		jQuery('.wordai-generated-image-thumb')
			.removeClass('is-featured')
			.filter(function () {
				return parseInt(jQuery(this).attr('data-attachment-id') || 0, 10) === attachmentId;
			})
			.addClass('is-featured');
	}

	window.scWordAIRefreshGeneratedImageThumbs = function(uploadInfo, featuredId) {
		const rows = Array.isArray(uploadInfo) ? uploadInfo : [];
		const $thumbs = jQuery('.wordai-generated-image-thumb');

		rows.forEach(function(row, index) {
			if (!row || row.status !== 'success') return;

			const attachmentId = parseInt(row.attachmentID || 0, 10);
			if (!attachmentId) return;

			const $thumb = $thumbs.eq(index);
			if (!$thumb.length) return;

			$thumb
				.attr('data-attachment-id', attachmentId)
				.attr('data-alt-text', row.altText || '')
				.addClass('is-uploaded');

			if (row.attachmentURL) {
				$thumb.attr('data-attachment-url', row.attachmentURL);
			}
		});

		scWordAISelectGeneratedImageThumb(featuredId);
	};




	window.SFTCY_WordAI = window.SFTCY_WordAI || {};

	SFTCY_WordAI.showDialog = function (title, message, onConfirm, options) {
		const settings = Object.assign(
			{
				type: 'confirm',
				variant: 'info',
				buttons: { ok: 'Yes', cancel: 'Cancel' }
			},
			options || {}
		);

		// icon + color mapping
		const variants = {
			info:    { icon: 'fa-circle-info',          color: '#0073aa' },
			success: { icon: 'fa-circle-check',         color: '#00a32a' },
			warning: { icon: 'fa-triangle-exclamation', color: '#dba617' },
			error:   { icon: 'fa-circle-xmark',         color: '#d63638' }
		};
		const variant = variants[settings.variant] || variants.info;

		// Create reusable container if not exists
		let $dialog = jQuery('#sc-wordai-global-dialog');
		if (!$dialog.length) {
			jQuery('body').append(`
				<div id="sc-wordai-global-dialog" title="${title}" style="display:none;">
					<p class="sc-wordai-dialog-message"></p>
				</div>
			`);
			$dialog = jQuery('#sc-wordai-global-dialog');
		}

		// Prepare content
		const iconHTML = `<i class="fa-solid ${variant.icon}" style="color:${variant.color};margin-right:8px;"></i>`;
		const contentHTML = `${iconHTML}${message}`;
		$dialog.html(`<p class="sc-wordai-dialog-message">${contentHTML}</p>`);

		// Build button set dynamically
		let dialogButtons = {};
		if (settings.type === 'alert') {
			dialogButtons[settings.buttons.ok || 'OK'] = function () {
				if (typeof onConfirm === 'function') onConfirm();
				jQuery(this).dialog('close');
			};
		} else {
			dialogButtons[settings.buttons.ok || 'Yes'] = function () {
				if (typeof onConfirm === 'function') onConfirm();
				jQuery(this).dialog('close');
			};
			dialogButtons[settings.buttons.cancel || 'Cancel'] = function () {
				jQuery(this).dialog('close');
			};
		}

		// Initialize or reopen the dialog safely
		if (!$dialog.hasClass('ui-dialog-content')) {
			// First-time initialization
			$dialog.dialog({
				modal: true,				
				// width: 420,
				minWidth: 600,
				// maxHeight: 500,
				resizable: false,
				draggable: false,
				dialogClass: 'sc-wordai-dialog ' + settings.variant,
				title: title,
				closeOnEscape: true,
				titleIsHtml: true,
				buttons: dialogButtons
			});
		} else {
			// Already initialized — just update and reopen
			$dialog
				.dialog('option', {
					title: title,
					buttons: dialogButtons,
					dialogClass: 'sc-wordai-dialog ' + settings.variant
				})
				.html(`<p class="sc-wordai-dialog-message">${contentHTML}</p>`)
				.dialog('open');
		}
	};





	var scSuggestTitleXHR =	'';
	// var scWordAIHideWaveAnimationWithSuggesTitleButtonActivation;	
	
	// Global Ajax call 
	scWordAIGlobalAjax = function(params, actionName ) {							
		return new Promise( ( resolve, reject ) => {
			    $.ajax({
				  type:"POST",				  
				  url: sftcy_wordai_metabox_script_obj.adminajax_url,
				  data : {			    
						action 	 : actionName,
						security : sftcy_wordai_metabox_script_obj.nonce,
						params   : params
						},		  
				  success: function(data) { 					 
					 resolve( data ); 					 
					},
				  error: function( xhr, status, error ) { 					 
					 reject( error ); 
					}
				});
		}); // Promise						
	};


	function scWordAINormalizeSuggestedTitleCandidates(raw) {
		let text = String(raw || '').replace(/[“”„‟]/g, '"').replace(/```(?:json|text)?|```/gi, '').replace(/\r\n?/g, '\n').trim();
		let candidates = [];
		try {
			const decoded = JSON.parse(text);
			const values = Array.isArray(decoded) ? decoded : (Array.isArray(decoded?.titles) ? decoded.titles : []);
			candidates = values.filter(value => ['string', 'number'].includes(typeof value)).map(String);
		} catch (e) {}
		const parseText = text.replace(/\\(["“”„‟])/g, '$1');
		if (!candidates.length) {
			const adjacent = parseText.split(/"\s*(?:,|;|\||\/)?\s*"/u);
			if (adjacent.length > 1) candidates = adjacent;
		}
		if (!candidates.length) {
			const quoted = [...parseText.matchAll(/"([^"\r\n]{2,})"/gu)].map(match => match[1]);
			if (quoted.length) candidates = quoted;
		}
		if (!candidates.length) candidates = parseText.split(/\n+|(?=\s*\d+\s*[.\):\-]\s+)/u);

		const unique = new Map();
		candidates.forEach(candidate => {
			let title = String(candidate || '').trim();
			const markdownLink = title.match(/^\[([^\]]+)\]\([^)]+\)$/u);
			if (markdownLink) title = markdownLink[1];
			title = title.replace(/\]\([^)]+\)$/u, '');
			title = title
				.replace(/^\s*(?:[-*•]+\s*|\d+\s*[.\):\-]\s*|title\s*\d*\s*[:\-]\s*)/iu, '')
				.replace(/["“”„‟]/g, '')
				.replace(/^[\s\[\]{}(),;|]+|[\s\[\]{}(),;|]+$/g, '')
				.replace(/\s+/g, ' ')
				.trim();
			if (!title || /^(?:here\s+are\b.*|suggested\s+titles?\b.*|titles?\s*:?)$/iu.test(title)) return;
			const key = title.toLocaleLowerCase();
			if (!unique.has(key)) unique.set(key, title);
		});
		return [...unique.values()].slice(0, 10);
	}

	function scWordAIRenderSuggestedTitleCandidates(titles) {
		const $dialog = jQuery('#suggest-titles-button-click-dialog');
		const $list = $dialog.find('.sc-wordai-suggested-titles-list').empty();
		(titles || []).forEach((title, index) => {
			const id = `WordAISuggesTitleRadioBox-${index + 1}`;
			const $input = jQuery('<input>', { type: 'radio', id: id, class: 'suggested-title-radio', name: 'suggested-title-radio', value: title });
			$list.append(jQuery('<li>').append(jQuery('<label>', { for: id }).append($input, document.createTextNode(' ' + title))));
		});
		$dialog.find('.scwordai-suggested-title-wrapper').toggle($list.children().length > 0);
	}

	// Suggest Title Modal: Write Suggest Titles - NON STREAMING
	jQuery('body').on('click', '.sc-wordai-write-suggest-titles-btn', function () {

		const $dialog         = jQuery('#suggest-titles-button-click-dialog');
		const $promptAlertMsg = $dialog.find('.prompt-alert-msg');
		const $waveRow        = $dialog.find('.wave-animation-row');

		const params = { prompt: $dialog.find('.scwordai-suggest-title-prompt').val() };

		if (!jQuery.trim(params.prompt)) {
			$promptAlertMsg.html('<span class="alert-remind">' + sftcy_wordai_metabox_script_obj.write_ur_prompt + '</span>');
			return;
		}

		// reset old results while starting new request
		window.scWordAISuggestTitleResetResultsUI();

		// lock provider + show busy UI
		if (typeof window.scWordAISetSuggestTitlePopupBusy === 'function') {
			window.scWordAISetSuggestTitlePopupBusy(true);
		}

		window.scWordAISuggestTitleToggleButtons(true);
		$waveRow.stop(true, true).show();

		window.scSuggestTitleXHR = jQuery.ajax({
			type: 'POST',
			cache: false,
			url: sftcy_wordai_metabox_script_obj.adminajax_url,
			data: {
				action: 'sc_wordai_write_suggest_titles',
				security: sftcy_wordai_metabox_script_obj.nonce,
				provider: window.SFTCY_WORDAI_ACTIVE_PROVIDER,
				params: params
			},
			success: function (data) {

				let jsonData = data;
				if (typeof data === 'string') {
					try { jsonData = JSON.parse(data); } catch (e) { jsonData = {}; }
				}

				// FAIL
				if (jsonData && jsonData.status === 'fail') {
					const msgRaw = jsonData.wordAIAPIKeyMissing || jsonData.errorMessage || sftcy_wordai_metabox_script_obj.something_went_wrong;
					const msg = jsonData.wordAIAPIKeyMissing ? '<i class="fa-solid fa-key"></i> ' + msgRaw : msgRaw;

					$promptAlertMsg.html('<span class="alert-error">' + msg + '</span>');

					window.scWordAISuggestTitleResetResultsUI();
					scWordAIHideWaveAnimationWithSuggesTitleButtonActivation();
					return;
				}

				// SUCCESS
				if (jsonData && jsonData.status === 'success') {
					$promptAlertMsg.html('<span class="alert-success">' + sftcy_wordai_metabox_script_obj.generated_title_success + '</span>');
					const titles = Array.isArray(jsonData.suggestedTitles)
						? jsonData.suggestedTitles
						: scWordAINormalizeSuggestedTitleCandidates(jsonData.responseText || '');
					scWordAIRenderSuggestedTitleCandidates(titles);

					scWordAIHideWaveAnimationWithSuggesTitleButtonActivation();
					return;
				}

				// Unknown
				$promptAlertMsg.html('<span class="alert-error">' + sftcy_wordai_metabox_script_obj.something_went_wrong + '</span>');
				window.scWordAISuggestTitleResetResultsUI();
				scWordAIHideWaveAnimationWithSuggesTitleButtonActivation();
			},
			error: function (xhr, status, error) {
				if (status === 'abort') return;

				console.error(xhr, status, error);
				$promptAlertMsg.html('<span class="alert-error">' + sftcy_wordai_metabox_script_obj.something_went_wrong + '</span>');

				window.scWordAISuggestTitleResetResultsUI();
				scWordAIHideWaveAnimationWithSuggesTitleButtonActivation();
			}
		});
	});

		
	// Suggest Title Modal: Write Suggest Titles - STREAMING
	jQuery('body').on('click', '.sc-wordai-write-suggest-titles-streaming-btn', function () {

		const $dialog         = jQuery('#suggest-titles-button-click-dialog');
		const $promptAlertMsg = $dialog.find('.prompt-alert-msg');
		const $waveRow        = $dialog.find('.wave-animation-row');

		const params = { prompt: $dialog.find('.scwordai-suggest-title-prompt').val() };

		if (!jQuery.trim(params.prompt)) {
			$promptAlertMsg.html('<span class="alert-remind">' + sftcy_wordai_metabox_script_obj.write_ur_prompt + '</span>');
			return;
		}

		// reset old results while starting new request
		window.scWordAISuggestTitleResetResultsUI();

		// lock provider + show busy UI
		if (typeof window.scWordAISetSuggestTitlePopupBusy === 'function') {
			window.scWordAISetSuggestTitlePopupBusy(true);
		}

		window.scWordAISuggestTitleToggleButtons(true);
		$waveRow.stop(true, true).show();

		// ✅ helper: key icon ONLY for API key missing
		const keyIcon = '<i class="fa-solid fa-key fas fa-key fa fa-key" aria-hidden="true"></i> ';
		const isApiKeyMsg = (msg) => /api\s*key/i.test(String(msg || ''));

		window.scSuggestTitleXHR = jQuery.ajax({
			type: 'POST',
			url: sftcy_wordai_metabox_script_obj.adminajax_url,
			cache: false,
			data: {
				action: 'sc_wordai_write_suggest_titles',
				security: sftcy_wordai_metabox_script_obj.nonce,
				provider: window.SFTCY_WORDAI_ACTIVE_PROVIDER,
				params: params
			},
			xhrFields: {
				onprogress: function (e) {

					const chunk = (e.target && typeof e.target.response === 'string') ? e.target.response : '';

					/* ==========================================================================
					✅ EARLY FAIL DETECTOR (Gemini missing API key often returns JSON directly)
					============================================================================= */
					const trimmed = chunk.trim();
					if (trimmed.charAt(0) === '{' && (trimmed.includes('"status"') || trimmed.includes('"wordAIAPIKeyMissing"'))) {
						try {
							const obj = JSON.parse(trimmed);
							if (obj && obj.status === 'fail') {
								const msgRaw = obj.wordAIAPIKeyMissing || obj.errorMessage || sftcy_wordai_metabox_script_obj.something_went_wrong;
								const msg    = isApiKeyMsg(msgRaw) ? (keyIcon + msgRaw) : msgRaw;

								$promptAlertMsg.html('<span class="alert-error">' + msg + '</span>');

								window.scWordAISuggestTitleResetResultsUI();
								scWordAIHideWaveAnimationWithSuggesTitleButtonActivation(); // this will abort → console shows "aborted" (expected)
								return;
							}
						} catch (err) {
							// not JSON, continue normal parsing
						}
					}

					// Normal streaming parse
					const parsed = scWordAIParseStreamingChunk(chunk, { preserveFormatting: true });

					// FAIL object (missing key etc.)
					if (typeof parsed === 'object' && parsed && parsed.status === 'fail') {
						const msgRaw = parsed.wordAIAPIKeyMissing || parsed.errorMessage || sftcy_wordai_metabox_script_obj.something_went_wrong;
						const msg    = parsed.wordAIAPIKeyMissing ? (keyIcon + msgRaw) : msgRaw;

						$promptAlertMsg.html('<span class="alert-error">' + msg + '</span>');

						window.scWordAISuggestTitleResetResultsUI();
						scWordAIHideWaveAnimationWithSuggesTitleButtonActivation();
						return;
					}

					// FAIL array
					if (Array.isArray(parsed) && parsed[0]?.errorData) {
						const msgRaw = parsed[0].errorData || sftcy_wordai_metabox_script_obj.something_went_wrong;
						const msg    = isApiKeyMsg(msgRaw) ? (keyIcon + msgRaw) : msgRaw;

						$promptAlertMsg.html('<span class="alert-error">' + msg + '</span>');

						window.scWordAISuggestTitleResetResultsUI();
						scWordAIHideWaveAnimationWithSuggesTitleButtonActivation();
						return;
					}

					if (typeof parsed !== 'string') return;

					const titles = scWordAINormalizeSuggestedTitleCandidates(parsed);
					if (titles.length) scWordAIRenderSuggestedTitleCandidates(titles);
				}
			},
			success: function (data) {

				let jsonData = null;
				if (typeof data === 'string' && data.trim().length) {
					try { jsonData = JSON.parse(data); } catch (e) {}
				} else if (typeof data === 'object' && data !== null) {
					jsonData = data;
				}

				if (jsonData && jsonData.status === 'fail') {
					const msgRaw = jsonData.wordAIAPIKeyMissing || jsonData.errorMessage || sftcy_wordai_metabox_script_obj.something_went_wrong;
					const msg    = jsonData.wordAIAPIKeyMissing ? (keyIcon + msgRaw) : msgRaw;

					$promptAlertMsg.html('<span class="alert-error">' + msg + '</span>');

					window.scWordAISuggestTitleResetResultsUI();
					scWordAIHideWaveAnimationWithSuggesTitleButtonActivation();
					return;
				}

				if (jsonData && jsonData.status === 'success') {
					const titles = Array.isArray(jsonData.suggestedTitles)
						? jsonData.suggestedTitles
						: scWordAINormalizeSuggestedTitleCandidates(jsonData.responseText || '');
					scWordAIRenderSuggestedTitleCandidates(titles);
				}

				$promptAlertMsg.html('<span class="alert-success">' + sftcy_wordai_metabox_script_obj.generated_title_success + '</span>');
				scWordAIHideWaveAnimationWithSuggesTitleButtonActivation();
			},
			error: function (xhr, status, error) {

				if (status === 'abort') return;

				console.error(xhr, status, error);
				$promptAlertMsg.html('<span class="alert-error">' + sftcy_wordai_metabox_script_obj.something_went_wrong + '</span>');

				window.scWordAISuggestTitleResetResultsUI();
				scWordAIHideWaveAnimationWithSuggesTitleButtonActivation();
			}
		});
	});

	// Suggest Title Modal: toggle buttons safely (no fade callback race)
	window.scWordAISuggestTitleToggleButtons = function (isBusy) {

		const $dialog = jQuery('#suggest-titles-button-click-dialog');

		const $cancel = $dialog.find('.sc-wordai-write-suggest-titles-cancel-btn');
		const $btnA   = $dialog.find('.sc-wordai-write-suggest-titles-btn');
		const $btnB   = $dialog.find('.sc-wordai-write-suggest-titles-streaming-btn');

		// kill any pending animations that can re-show cancel
		$cancel.stop(true, true);
		$btnA.stop(true, true);
		$btnB.stop(true, true);

		if (isBusy) {
			$btnA.hide();
			$btnB.hide();
			$cancel.show();
		} else {
			$cancel.hide();
			// show whichever exists (streaming OR non-streaming)
			if ($btnB.length) $btnB.show();
			if ($btnA.length) $btnA.show();
		}
	};

	// helper to reset “Generated Title(s)” UI on FAIL
	window.scWordAISuggestTitleResetResultsUI = function () {
		const $dialog = jQuery('#suggest-titles-button-click-dialog');
		$dialog.find('.sc-wordai-suggested-titles-list').empty();
		$dialog.find('.scwordai-suggested-title-wrapper').hide(); // hides Update Title button too
	};


	// Suggest Title Modal: Hide wave animation - with Button activation - when requests complete
	window.scWordAIHideWaveAnimationWithSuggesTitleButtonActivation = function () {

		const $dialog  = jQuery('#suggest-titles-button-click-dialog');
		const $waveRow = $dialog.find('.wave-animation-row');

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

		// ✅ Abort safely
		if (window.scSuggestTitleXHR && typeof window.scSuggestTitleXHR.abort === 'function') {
			try { window.scSuggestTitleXHR.abort(); } catch (e) {}
		}

		// ✅ Hide loader
		$waveRow.stop(true, true).hide();

		// ✅ Restore buttons (no race)
		window.scWordAISuggestTitleToggleButtons(false);
	};

	// Backward compatibility alias (if any older calls exist)
	function scWordAIHideWaveAnimationWithSuggesTitleButtonActivation() {
		return window.scWordAIHideWaveAnimationWithSuggesTitleButtonActivation();
	}

	
	
	// Suggest Title Modal: Write Suggest Titles Cancel button Click - Cancel Requests Button Click
	$('body').on("click", ".sc-wordai-write-suggest-titles-cancel-btn", function() {	
		window.scWordAIHideWaveAnimationWithSuggesTitleButtonActivation();
	});
	
	
	// Suggest Title Modal: Update Suggested Title - Button inside suggested title Modal popup window - Replace the old Title
	$('body').on("click", ".sc-wordai-suggested-title-update-btn", function() {
		let updateSuggestedtitleFeedback	= $('.update-suggested-title-msg');			
		let postID			=	$(this).data('scwordai-updatebtn-postid');
		let selectedTitle	= '';
		updateSuggestedtitleFeedback.html('');	
		$('.suggested-title-radio').each( function() {
			if ( $(this).is(":checked") ) {
				selectedTitle			=	$.trim($(this).val() || '');
				console.log('Selected Title: ' + selectedTitle);
				// console.log(postID);
				let params	=	{};
				params.selectedTitle	= selectedTitle;
				params.postID			= postID;

				$.ajax({
				  type:"POST",
				  cache: false,
				  url: sftcy_wordai_metabox_script_obj.adminajax_url,
				  data : {			    
						action 	 : 'sc_wordai_update_suggest_title',
						security : sftcy_wordai_metabox_script_obj.nonce,
						params   : params
						},		  
				  success: function(data) { 
					 console.log(data); 
					 let jsonData	= JSON.parse( data );
					  if ( jsonData.status == 'success' ) {
						$('#post-'+postID+' .row-title' ).html(selectedTitle).addClass('alert-change');  
						setTimeout(function() { $('#post-'+postID+' .row-title' ).html(selectedTitle).removeClass('alert-change');}, 3000);  
						updateSuggestedtitleFeedback.html('<span class="alert-success">'+sftcy_wordai_metabox_script_obj.updated_title_success+'</span>');						
					  }
					  else if ( jsonData.status == 'fail' ) {					  
						  updateSuggestedtitleFeedback.html( '<span class="alert-error">'+ jsonData.errorMessage +'</span>' );					  					  					  
					  }
					  else {
						  updateSuggestedtitleFeedback.html('<span class="alert-error">'+sftcy_wordai_metabox_script_obj.something_went_wrong+'</span>');						  
					  }
					},
				  error: function( xhr, status, error ) { 
					 console.log(xhr); 
					 console.log(status); 
					 console.log(error); 				 					 					 
					}
				});								
			}		 			
		});
		
		$('.suggested-title-radio').promise().done(function() {		
				// If not suggested Title is selected - Remind
				if ( selectedTitle.length == 0 ) {
					updateSuggestedtitleFeedback.html('<span class="alert-remind">'+sftcy_wordai_metabox_script_obj.updated_title_not_selected+'</span>');
				}
		});			
		
		// Reset / Empty updated messages
		setTimeout(function() { updateSuggestedtitleFeedback.html(''); }, 4000 );				
	});			
	
	// Upload image to media Gallery - Save to Gallery Button based on Click - Set featured image - Manually
	$('body').on( "click", ".sc-wordai-upload-image-btn", function() {
		let promptAlertMsg			= $('.prompt-alert-msg');
		let scWordAiUploadImgBtn	= $('.sc-wordai-upload-image-btn');
		let saveImageToGalleryIcon	= $('.save-image-to-gallery-icon');
		let setFeatureImageStatus	= $('.sc-wordai-generated-image-set-feature-status').val();
		let scWordAISelectedImageModelElement = $('.sc-wordai-generated-images-model-name');				


		promptAlertMsg.html("");
		let params 					= {};

		/**
		 * FIXED: postID logic
		 * -------------------------------------------------
		 * Old code always forced postID = 0 because `finally` always runs.
		 * This version only sets 0 if post ID truly cannot be resolved.
		 */
		params.postID				= scWordAIGetCurrentPostId();
		params.prompt				= $('.scwordai-prompt').val();	
		params.imgURLs				= $('.sc-wordai-generated-images-urls').val();
		params.imageModel           = scWordAISelectedImageModelElement.val();
		params.setFeatured          = setFeatureImageStatus;
		params.imageAltText         = $('.sc-wordai-generated-image-alt-text').val() || '';
		// params.postID				= wp.data.select("core/editor").getCurrentPostId();	
		// params.postTitle            = wp.data.select('core/editor').getEditedPostAttribute('title');
		//params.postType			= wp.data.select("core/editor").getCurrentPostType();			
		if ( $.trim( params.prompt).length == 0 ) {
			promptAlertMsg.html('<span class="alert-remind">'+sftcy_wordai_metabox_script_obj.write_ur_prompt+'</span>');
		} 
		else {		
			$(this).attr("disabled", "disabled" );
			saveImageToGalleryIcon.fadeIn(300);
			
			$.ajax({
			  type:"POST",
			  cache: false,
			  url: sftcy_wordai_metabox_script_obj.adminajax_url,
			  data : {			    
					action 	 : 'sc_wordai_upload_image_to_wp_media',
					security : sftcy_wordai_metabox_script_obj.nonce,
					params   : params
					},		  
			  success: function(data) { 
				//   console.log(data); 				  
				  let jsonData			= JSON.parse( data );
				  if ( jsonData.status == 'success' ) {
					promptAlertMsg.html('<span class="alert-success">'+sftcy_wordai_metabox_script_obj.images_saved_to_gallery+'</span>');										
					scWordAiUploadImgBtn.removeAttr('disabled');					
					saveImageToGalleryIcon.fadeOut(300);  	
					if (typeof window.scWordAIRefreshGeneratedImageThumbs === 'function') {
						window.scWordAIRefreshGeneratedImageThumbs(jsonData.imgaesUploadInfo, jsonData.featuredImageAttachmentID || jsonData.firstImageAttachmentID);
					}
					// Set Featured Image  
					if ( setFeatureImageStatus == 1 ) {  
						scWordAIApplyFeaturedImage(params.postID, jsonData.featuredImageAttachmentID || jsonData.firstImageAttachmentID);
					}					  					  
				  }
				  else if ( jsonData.status == 'fail' ) {					  
					  promptAlertMsg.html( '<span class="alert-error">'+ jsonData.errorMessage +'</span>' );					  					  					  
					  scWordAiUploadImgBtn.removeAttr('disabled');					  
					  saveImageToGalleryIcon.fadeOut(300);  
				  }
				  else {
					  promptAlertMsg.html('<span class="alert-error">'+sftcy_wordai_metabox_script_obj.something_went_wrong+'</span>');
					  saveImageToGalleryIcon.fadeOut(300);  
				  }
				},
			  error: function( xhr, status, error ) { 
				 console.log(xhr); 
				 console.log(status); 
				 console.log(error); 				 
				 scWordAiUploadImgBtn.removeAttr('disabled');
				 saveImageToGalleryIcon.fadeOut(300);  
				}
			});
		}
				
	});
		

	// Upload image to media button Click - Save to Gallery - Set Featured Image - Automatically
	scWordAIUploadImagesWithSavetoImageGallery = function () {

		let promptAlertMsg = $('.prompt-alert-msg');
		let scWordAISelectedImageModelElement = $('.sc-wordai-generated-images-model-name');

		// -----------------------------
		// Prepare request params
		// -----------------------------
		let params = {};
		params.prompt     = $('.scwordai-prompt').val();
		params.imageModel = scWordAISelectedImageModelElement.val();
		params.imgURLs    = $('.sc-wordai-generated-images-urls').val();
		params.imageAltText = $('.sc-wordai-generated-image-alt-text').val() || '';

		/**
		 * IMPORTANT SAFETY CHECK
		 * -------------------------------------------------
		 * If no images exist, do NOT attempt upload.
		 * Prevents:
		 * - unnecessary AJAX calls
		 * - server-side "fail" responses without errorMessage
		 * - accidental "undefined" UI output
		 */
		if (!params.imgURLs || !params.imgURLs.trim()) {
			return; // nothing to upload, exit silently (safe + expected)
		}

		/**
		 * FIXED: postID logic
		 * -------------------------------------------------
		 * Old code always forced postID = 0 because `finally` always runs.
		 * This version only sets 0 if post ID truly cannot be resolved.
		 */
		// params.postID = 0;
		// try {
		// 	const maybePostId = wp?.data?.select?.('core/editor')?.getCurrentPostId?.();
		// 	if (maybePostId) {
		// 		params.postID = maybePostId;
		// 	}
		// } catch (error) {
		// 	console.log(error?.message || error);
		// }

		params.postID = scWordAIGetCurrentPostId();



		// Feature image status
		let setFeatureImageStatus = $('.sc-wordai-generated-image-set-feature-status').val();
		params.setFeatured = setFeatureImageStatus;

		// -----------------------------
		// Safe UI helpers (NO undefined)
		// -----------------------------
		const safeText = (v) => (typeof v === 'string' ? v.trim() : '');

		const appendError = (msg, fallback) => {
			const text = safeText(msg) || safeText(fallback);
			if (text) {
				promptAlertMsg.append('<span class="alert-error">' + text + '</span><br/>');
			}
		};

		const appendSuccess = (msg) => {
			const text = safeText(msg);
			if (text) {
				promptAlertMsg.append('<span class="alert-success">' + text + '</span><br/>');
			}
		};

		// -----------------------------
		// AJAX: Upload images to WP media
		// -----------------------------
		$.ajax({
			type: "POST",
			url: sftcy_wordai_metabox_script_obj.adminajax_url,
			data: {
				action: 'sc_wordai_upload_image_to_wp_media',
				security: sftcy_wordai_metabox_script_obj.nonce,
				params: params
			},

			success: function (data) {

				let jsonData = {};
				try {
					jsonData = JSON.parse(data);
				} catch (e) {
					appendError(
						'',
						sftcy_wordai_metabox_script_obj?.something_went_wrong_images_save ??
						'Something went wrong while saving images.'
					);
					return;
				}

				// ==========================
				// SUCCESS
				// ==========================
				if (jsonData.status === 'success') {

					appendSuccess(
						sftcy_wordai_metabox_script_obj?.images_saved_to_gallery ??
						'Images saved to gallery.'
					);
					if (typeof window.scWordAIRefreshGeneratedImageThumbs === 'function') {
						window.scWordAIRefreshGeneratedImageThumbs(jsonData.imgaesUploadInfo, jsonData.featuredImageAttachmentID || jsonData.firstImageAttachmentID);
					}

					// Set Featured Image if enabled
					if (setFeatureImageStatus == 1) {
						scWordAIApplyFeaturedImage(params.postID, jsonData.featuredImageAttachmentID || jsonData.firstImageAttachmentID);
					}

					return;
				}

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

					const errMsg =
						jsonData?.errorMessage ??
						jsonData?.message ??
						jsonData?.error ??
						'';

					appendError(
						errMsg,
						sftcy_wordai_metabox_script_obj?.something_went_wrong_images_save ??
						'Something went wrong while saving images.'
					);
					return;
				}

				// ==========================
				// UNEXPECTED RESPONSE
				// ==========================
				appendError(
					'',
					sftcy_wordai_metabox_script_obj?.something_went_wrong_images_save ??
					'Something went wrong while saving images.'
				);
			},

			error: function (xhr, status, error) {
				console.log(xhr);
				console.log(status);
				console.log(error);

				appendError(
					error,
					sftcy_wordai_metabox_script_obj?.something_went_wrong_images_save ??
					'Something went wrong while saving images.'
				);
			}
		});
	};

	$('body').on('click', '.wordai-generated-image-thumb', function () {
		const $thumb = $(this);
		const attachmentId = parseInt($thumb.attr('data-attachment-id') || 0, 10);
		const postID = scWordAIGetCurrentPostId();
		const promptAlertMsg = $('.prompt-alert-msg');

		if (!attachmentId) {
			promptAlertMsg.html('<span class="alert-remind">Save the generated images to the Media Library before selecting a featured image.</span>');
			return;
		}

		if (!postID) {
			promptAlertMsg.html('<span class="alert-remind">Save the post first, then select a featured image.</span>');
			return;
		}

		$thumb.prop('disabled', true).addClass('is-updating');

		$.ajax({
			type: 'POST',
			cache: false,
			url: sftcy_wordai_metabox_script_obj.adminajax_url,
			data: {
				action: 'sc_wordai_set_featured_image',
				security: sftcy_wordai_metabox_script_obj.nonce,
				params: {
					postID: postID,
					attachmentID: attachmentId
				}
			},
			success: function (data) {
				let jsonData = {};
				try {
					jsonData = (typeof data === 'string') ? JSON.parse(data) : data;
				} catch (e) {}

				if (jsonData.status === 'success') {
					scWordAIApplyFeaturedImage(postID, attachmentId);
					scWordAISelectGeneratedImageThumb(attachmentId);
					promptAlertMsg.html('<span class="alert-success">' + (jsonData.statusMsg || 'Featured image updated.') + '</span>');
					return;
				}

				promptAlertMsg.html('<span class="alert-error">' + (jsonData.errorMessage || sftcy_wordai_metabox_script_obj.something_went_wrong) + '</span>');
			},
			error: function () {
				promptAlertMsg.html('<span class="alert-error">' + sftcy_wordai_metabox_script_obj.something_went_wrong + '</span>');
			},
			complete: function () {
				$thumb.prop('disabled', false).removeClass('is-updating');
			}
		});
	});

	$('body').on('click', '.sc-wordai-image-alt-text-insert-btn', function () {
		const $button = $(this);
		const promptAlertMsg = $('.prompt-alert-msg');
		const imageAltText = $.trim($('.sc-wordai-generated-image-alt-text').val() || '');
		const postID = scWordAIGetCurrentPostId();
		const attachmentIDs = [];

		$('.wordai-generated-image-thumb[data-attachment-id]').each(function () {
			const attachmentId = parseInt($(this).attr('data-attachment-id') || 0, 10);
			if (attachmentId && attachmentIDs.indexOf(attachmentId) === -1) {
				attachmentIDs.push(attachmentId);
			}
		});

		if (!imageAltText) {
			promptAlertMsg.html('<span class="alert-remind">Generate or enter image alt text first.</span>');
			return;
		}

		if (!attachmentIDs.length && !postID) {
			promptAlertMsg.html('<span class="alert-remind">Save generated images to the Media Library before inserting alt text.</span>');
			return;
		}

		$button.prop('disabled', true);

		$.ajax({
			type: 'POST',
			cache: false,
			url: sftcy_wordai_metabox_script_obj.adminajax_url,
			data: {
				action: 'sc_wordai_apply_image_alt_text',
				security: sftcy_wordai_metabox_script_obj.nonce,
				params: {
					postID: postID,
					imageAltText: imageAltText,
					attachmentIDs: attachmentIDs
				}
			},
			success: function (data) {
				let jsonData = {};
				try {
					jsonData = (typeof data === 'string') ? JSON.parse(data) : data;
				} catch (e) {}

				if (jsonData.status === 'success') {
					$('.wordai-generated-image-thumb[data-attachment-id]').attr('data-alt-text', imageAltText);
					promptAlertMsg.html('<span class="alert-success">' + (jsonData.statusMsg || 'Image alt text inserted.') + '</span>');
					return;
				}

				promptAlertMsg.html('<span class="alert-error">' + (jsonData.errorMessage || sftcy_wordai_metabox_script_obj.something_went_wrong) + '</span>');
			},
			error: function () {
				promptAlertMsg.html('<span class="alert-error">' + sftcy_wordai_metabox_script_obj.something_went_wrong + '</span>');
			},
			complete: function () {
				$button.prop('disabled', false);
			}
		});
	});

	$('body').on('click', '.wordai-option-lock-badge-link', function (event) {
		event.stopPropagation();
	});
	
	
	// Metabox content write button click to open popup dialog display
	$('body').on( "click", ".metabox-content-writer-btn", function(e) {
		// console.log('Metabox clicked');
		//e.preventDefault();
		//$('#metabox-button-click-dialog').dialog('open');
		$('#metabox-button-click-dialog').dialog('open');
		return false;
	});

	function scWordAIInsertEditorTopButton() {
		if ($('#sc-wordai-editor-top-button').length) {
			return true;
		}

		if (!$('#metabox-button-click-dialog').length) {
			return false;
		}

		const $toolbar = $(
			'.edit-post-header-toolbar, ' +
			'.edit-post-header__toolbar, ' +
			'.woocommerce-layout__header .woocommerce-layout__header-breadcrumbs'
		).first();

		if (!$toolbar.length) {
			return false;
		}

		const $button = $('<button/>', {
			type: 'button',
			id: 'sc-wordai-editor-top-button',
			class: 'button button-primary sc-wordai-editor-top-button',
			'aria-label': 'Open WordAI content generator'
		})
			.append($('<span/>', { class: 'sc-wordai-editor-top-button__icon', 'aria-hidden': 'true' }).html('<i class="sc-wordai-metabox-button-custom-icon"></i>'))
			.append($('<span/>', { class: 'sc-wordai-editor-top-button__label', text: 'WordAI' }));

		$toolbar.append($button);
		return true;
	}

	window.setInterval(scWordAIInsertEditorTopButton, 1000);
	scWordAIInsertEditorTopButton();

	$('body').on('click', '#sc-wordai-editor-top-button', function(e) {
		e.preventDefault();
		$('#metabox-button-click-dialog').dialog('open');
		return false;
	});
	
	// Test OpenAI API
	$('.test-openai-btn').click(function() {		
		$.ajax({
		  type:"POST",
		  cache: false,
		  url: sftcy_wordai_metabox_script_obj.adminajax_url,
		  data : {			    
                action 	 : 'sc_wordai_api_test',
                security : sftcy_wordai_metabox_script_obj.nonce,			    
                },		  
		  success: function(data) { 
		  	 console.log(data); 
			},
		  error: function( xhr, status, error ) { 
		  	 console.log(xhr); 
			 console.log(status); 
			 console.log(error); 
			}
		});
				
	});
	
	
	//=====================================================================
	// 🔐 API Settings: OpenAI API Key — Save
	//=====================================================================
	// =============================================================
	// 🔐 Unified API Key Save Handler (Safe, Mask-Protected)
	// =============================================================

	function getRealKey($input) {
		let real = $input.data('real') || '';
		let mask = $input.data('mask') || '';
		let current = $input.val().trim();

		// If current equals mask → it's NOT a real key
		if (current === mask) return '';

		// If current equals stored real → return real
		if (current === real) return real;

		// Otherwise, user typed something → return it
		return current;
	}

	// =============================================================
	// 🔹 OpenAI API Secret Key — Save API Key
	// =============================================================
	$('body').on("submit", "#wordai-openai-api-key-form", function () {

		const $input  = $('.wordai-openai-api-key-data');
		const realKey = $input.data('real') || '';
		const fieldVal = $input.val().trim();

		let feedback = $('.wordai-api-key-save-feedback-msg-td');
		feedback.removeClass('success-msg alert-msg error-msg').html('');

		$.ajax({
			type: 'POST',
			url: sftcy_wordai_metabox_script_obj.adminajax_url,
			data: {
				action: 'wordai_openai_api_key_data_save',
				security: sftcy_wordai_metabox_script_obj.nonce,
				realKey: fieldVal   // send actual input (mask or real)
			},
			success: function (res) {
				let json = (typeof res === 'string') ? JSON.parse(res) : res;

				if (json.status === 'success') {

					feedback.addClass('success-msg')
						.html(sftcy_wordai_metabox_script_obj.wordai_success_icon + ' ' + json.feedbackMsg);

					// Update UI (store new real key)
					$input.data('real', json.savedKey);
					$input.data('mask', json.savedMask);

					$('.wordai-openai-api-key-show').prop('checked', true);

					// Show raw after save
					$input.val(json.savedKey);
					$input.attr("placeholder", '');

				} else if (json.status === 'warning') {

					feedback.addClass('alert-msg')
						.html(sftcy_wordai_metabox_script_obj.wordai_info_icon + ' ' + json.feedbackMsg);

				} else {

					feedback.addClass('error-msg')
						.html(sftcy_wordai_metabox_script_obj.wordai_error_icon + ' ' + json.feedbackMsg);

				}
			}
		});

		return false;
	});


	// =============================================================
	// 🔹 Google Gemini — Save API Key
	// =============================================================
	$('body').on("submit", "#wordai-gemini-api-key-form", function () {

		const $input = $('.wordai-google-gemini-api-key-data');
		const realKey = getRealKey($input);

		let feedback = $('.wordai-gemini-api-key-feedback');
		feedback.removeClass('success-msg alert-msg error-msg').html('');

		$.ajax({
			type: 'POST',
			url: sftcy_wordai_metabox_script_obj.adminajax_url,
			data: {
				action: 'wordai_google_gemini_api_key_data_save',
				security: sftcy_wordai_metabox_script_obj.nonce,
				realKey: realKey
			},
			success: function (res) {
				let json = (typeof res === 'string') ? JSON.parse(res) : res;

				if (json.status === 'success') {

					// Update UI
					$input.data('real', json.savedKey);
					$input.data('mask', json.savedMask);
					$input.val(json.savedKey); // show real immediately
					$('.wordai-google-gemini-api-key-show').prop('checked', true);

					feedback.addClass('success-msg')
						.html(sftcy_wordai_metabox_script_obj.wordai_success_icon + ' ' + json.feedbackMsg);

				} else if (json.status === 'warning') {
					feedback.addClass('alert-msg')
						.html(sftcy_wordai_metabox_script_obj.wordai_info_icon + ' ' + json.feedbackMsg);

				} else {
					feedback.addClass('error-msg')
						.html(sftcy_wordai_metabox_script_obj.wordai_error_icon + ' ' + json.feedbackMsg);
				}
			}
		});

		return false;
	});

	// =============================================================
	// 🔹 Anthropic Claude — Save API Key
	// =============================================================
	$('body').on("submit", "#wordai-anthropic-api-key-form", function () {

		const $input = $('.wordai-anthropic-api-key-data');
		const realKey = getRealKey($input);

		let feedback = $('.wordai-anthropic-api-key-feedback');
		feedback.removeClass('success-msg alert-msg error-msg').html('');

		$.ajax({
			type: 'POST',
			url: sftcy_wordai_metabox_script_obj.adminajax_url,
			data: {
				action: 'wordai_anthropic_api_key_data_save',
				security: sftcy_wordai_metabox_script_obj.nonce,
				realKey: realKey
			},
			success: function (res) {
				let json = (typeof res === 'string') ? JSON.parse(res) : res;

				if (json.status === 'success') {

					$input.data('real', json.savedKey);
					$input.data('mask', json.savedMask);
					$input.val(json.savedKey);
					$('.wordai-anthropic-api-key-show').prop('checked', true);

					feedback.addClass('success-msg')
						.html(sftcy_wordai_metabox_script_obj.wordai_success_icon + ' ' + json.feedbackMsg);

				} else if (json.status === 'warning') {
					feedback.addClass('alert-msg')
						.html(sftcy_wordai_metabox_script_obj.wordai_info_icon + ' ' + json.feedbackMsg);

				} else {
					feedback.addClass('error-msg')
						.html(sftcy_wordai_metabox_script_obj.wordai_error_icon + ' ' + json.feedbackMsg);
				}
			}
		});

		return false;
	});

	// =============================================================
	// 🔹 xAI Grok — Save API Key
	// =============================================================
	$('body').on("submit", "#wordai-xai-api-key-form", function () {

		const $input = $('.wordai-xai-api-key-data');
		const realKey = getRealKey($input);

		let feedback = $('.wordai-xai-api-key-feedback');
		feedback.removeClass('success-msg alert-msg error-msg').html('');

		$.ajax({
			type: 'POST',
			url: sftcy_wordai_metabox_script_obj.adminajax_url,
			data: {
				action: 'wordai_xai_api_key_data_save',
				security: sftcy_wordai_metabox_script_obj.nonce,
				realKey: realKey
			},
			success: function (res) {
				let json = (typeof res === 'string') ? JSON.parse(res) : res;

				if (json.status === 'success') {
					$input.data('real', json.savedKey);
					$input.data('mask', json.savedMask);
					$input.val(json.savedKey);
					$('.wordai-xai-api-key-show').prop('checked', true);

					feedback.addClass('success-msg')
						.html(sftcy_wordai_metabox_script_obj.wordai_success_icon + ' ' + json.feedbackMsg);

				} else if (json.status === 'warning') {
					feedback.addClass('alert-msg')
						.html(sftcy_wordai_metabox_script_obj.wordai_info_icon + ' ' + json.feedbackMsg);

				} else {
					feedback.addClass('error-msg')
						.html(sftcy_wordai_metabox_script_obj.wordai_error_icon + ' ' + json.feedbackMsg);
				}
			}
		});

		return false;
	});
	
	
	//-------------------------------------------------------------
	// 🔐 SHOW / HIDE API KEYS (OpenAI & Gemini)
	//-------------------------------------------------------------

	/**
	 * Toggle API Key visibility (OpenAI & Gemini)
	 */
	function toggleKeyVisibility($checkbox, inputSelector) {

		let $input = $(inputSelector);
		let real   = $input.data('real') || '';      // raw saved key
		let mask   = $input.data('mask') || '';      // mask or placeholder

		// CASE A: Checkbox checked + real key exists → show REAL KEY
		if ($checkbox.is(':checked') && real.length > 0) {
			$input.val(real);           // show real key
			return;
		}

		// CASE B: Checkbox unchecked + real key exists → show MASKED KEY
		if (!$checkbox.is(':checked') && real.length > 0) {
			$input.val(mask);           // show mask only			
			return;
		}

		// CASE C: Checkbox checked + NO real key → show empty input
		if ($checkbox.is(':checked') && real.length === 0) {
			$input.val("");             // user must enter real key
			$input.attr("placeholder", '');     // remove placeholder to show empty field
			return;
		}

		// CASE D: Checkbox unchecked + NO real key → show placeholder only
		if (! $checkbox.is(':checked') && real.length === 0) {
			$input.val("");             // value empty
			$input.attr("placeholder", mask); // placeholder appears
			return;
		}
	}
	

	//-------------------------------------------------------------
	// 🔹 OPENAI toggle
	//-------------------------------------------------------------
	$(document).on("change", ".wordai-openai-api-key-show", function () {
		toggleKeyVisibility($(this), ".wordai-openai-api-key-data");
	});

	//-------------------------------------------------------------
	// 🔹 GEMINI toggle
	//-------------------------------------------------------------
	$(document).on('change', '.wordai-google-gemini-api-key-show', function () {
		toggleKeyVisibility($(this), '.wordai-google-gemini-api-key-data');
	});

	//-------------------------------------------------------------
	// 🔹 ANTHROPIC toggle
	//-------------------------------------------------------------
	$(document).on('change', '.wordai-anthropic-api-key-show', function () {
		toggleKeyVisibility($(this), '.wordai-anthropic-api-key-data');
	});

	//-------------------------------------------------------------
	// 🔹 xAI toggle
	//-------------------------------------------------------------
	$(document).on('change', '.wordai-xai-api-key-show', function () {
		toggleKeyVisibility($(this), '.wordai-xai-api-key-data');
	});

	function scWordAIGetSuggestDialogLayout() {
		const winW = jQuery(window).width();
		const winH = jQuery(window).height();
		const gutter = winW < 1024 ? 12 : 20;
		const $adminMenu = jQuery('#adminmenuwrap:visible');
		const adminMenuW = $adminMenu.length ? $adminMenu.outerWidth(true) : 0;
		const workspaceLeft = adminMenuW + gutter;
		const workspaceWidth = Math.max(420, winW - workspaceLeft - gutter);
		const widthCap = winW < 1180 ? 720 : 780;
		const modalWidth = Math.max(Math.min(560, workspaceWidth), Math.min(widthCap, workspaceWidth));
		const modalLeft = workspaceLeft + Math.max(0, Math.floor((workspaceWidth - modalWidth) / 2));

		return {
			width: Math.floor(modalWidth),
			left: Math.floor(modalLeft),
			top: winW < 1024 ? 8 : Math.max(12, Math.floor(winH * 0.08)),
			maxHeight: Math.max(520, Math.floor(winH - 42))
		};
	}

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

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

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



	// Suggest Titles Popup dialog config //	
	// console.log(sftcy_wordai_metabox_script_obj );
	// dialogClass: 'wordai-info-dialog', // or wordai-success-dialog, wordai-warning-dialog, wordai-error-dialog
	$('#suggest-titles-button-click-dialog').dialog({
			modal: true,
			title: sftcy_wordai_metabox_script_obj.popup_dialog_suggest_title,
			titleIsHtml: true,
			dialogClass: 'sc-wordai-global-dialog sc-wordai-suggest-dialog wordai-info-dialog',
			autoOpen: false,
			draggable: true,
			minWidth: 600,
			resizable: false,
			closeOnEscape: true,
			position: { my: 'left top', at: 'left+20 top+60', of: window, collision: 'fit' },

			buttons: [
				{
					text: sftcy_wordai_metabox_script_obj.close_text || 'Close',
					class: 'button button-secondary',
					click: function () {
						$(this).dialog('close');
					}
				}
			],

			open: function () {
				$('body').addClass('wordai-suggest-dialog-open');
				scWordAIApplySuggestDialogLayout($(this));

				// Allow closing by clicking the overlay
				$('.ui-widget-overlay').off('click').on('click', function () {
					$('#suggest-titles-button-click-dialog').dialog('close');
				});
			},

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

				// Add WordAI icon to title
				let w = $(this).dialog("widget");
				let t = $(".ui-dialog-title", w);
				t.html(
					sftcy_wordai_metabox_script_obj.sc_wordai_icon +
					sftcy_wordai_metabox_script_obj.popup_dialog_suggest_title
				);
				if (!w.find('.wordai-dialog-drag-hint').length) {
					w.find('.ui-dialog-titlebar').append('<span class="wordai-dialog-drag-hint" aria-hidden="true"><span class="dashicons dashicons-move"></span></span>');
				}
			}
	});

	$(window).on('resize', function () {
		const $suggestDialog = $('#suggest-titles-button-click-dialog');
		if ($suggestDialog.is(':visible')) {
			scWordAIApplySuggestDialogLayout($suggestDialog);
		}
	});

	
		  // Suggest Title Modal: Open Suggest Title Modal - 'WordAI Title' clickable link text in rows  - Initial open Modal popup dialog for suggest titles	
		  $('body').on( "click", ".sc-wordai-suggest-titles", function(e) {
			// console.log('Suggest titles button click');
			e.preventDefault();
			const $trigger = $(this);
			const $row = $trigger.closest('tr');
			$('.prompt-alert-msg').html('');  
			let postID		= $trigger.data('scwordai-post-id');
			// console.log(postID);
			//let chosenPostTitle	= $('#post-'+postID+' .title .row-title' ).html();
			//let chosenPostTitle	= $('#post-'+postID+' .row-title' ).html();  
			let chosenPostTitle	= $('#post-'+postID+' .row-title' ).text();    
			// console.log(chosenPostTitle);  
			$('.scwordai-suggest-title-prompt').val(chosenPostTitle);
			// Hide If previous Titles shown  
			$('.scwordai-suggested-title-wrapper').hide();  
			$('.sc-wordai-suggested-title-update-btn').attr('data-scwordai-updatebtn-postid', postID);
			$('#suggest-titles-button-click-dialog').dialog('open').promise().done( function() { 
				$trigger.trigger('blur');
				$row.removeClass('is-hover');
				// $('#suggest-titles-button-click-dialog').css( 'max-height', 'none');
				// $('#suggest-titles-button-click-dialog').css( 'max-height', 'none').prev(".ui-dialog-titlebar").css({'background':'#0693e3', 'border': 'none', 'color': 'white'});
			} );   
		  });

		  $('#suggest-titles-button-click-dialog').on('dialogclose', function () {
			$('body').removeClass('wordai-suggest-dialog-open');
			$('.sc-wordai-suggest-titles').blur();
			$('#the-list tr').removeClass('is-hover');
		  });



	     // Suggest Title Modal: Save suggest title number on select dropdown
	     $('body').on("change", "#scwordai-suggested-titles-number", function() {
			 const $suggestDialog = $('#suggest-titles-button-click-dialog');
			 let suggestedTitleNumber	=	$(this).val();
			 const provider = String($suggestDialog.find('#sc-wordai-ai-provider-suggest-popup').val() || window.SFTCY_WORDAI_ACTIVE_PROVIDER || 'openai');
			 console.log('Selected SuggestedTitleNumber:'+ suggestedTitleNumber );
			 $.ajax({
				type: 'POST',
			  url: sftcy_wordai_metabox_script_obj.adminajax_url,
			  data : {			    
					action 	 : 'sc_wordai_suggested_title_number_save',
					security : sftcy_wordai_metabox_script_obj.nonce,			    
					suggestedTitle : suggestedTitleNumber,
					provider : provider,
					},		  
			  success: function(data) { 
				//  console.log(data); 
				 let jsonData	= typeof data === 'string' ? JSON.parse( data ) : data;
				  if ( jsonData.status == 'success' ) {
					//   console.log('Saved suggested Title Number.')
				  }
				},
			  error: function( xhr, status, error ) { 
				 console.log(xhr); 
				 console.log(status); 
				 console.log(error); 						  
				}			
			});			 
		 });		
	
	
		// Image Settings: On change Image model show-hide related fields
		// $('body').on('change', '#sc-wordai-openai-image-model-slug', function() {
		// 	console.log('Image Settings: On change Image model show-hide related fields - select dropdown #sc-wordai-openai-image-model-slug  triggered.');

		// 	let selectedImageModelSlug = $(this).val();

		// 	// ✅ GPT Image family (all use the same UI rows)
		// 	// const gptImageFamily = ['gpt-image-1', 'gpt-image-1-mini', 'gpt-image-1.5'];
		// 	// const isGptImage = gptImageFamily.includes(selectedImageModelSlug);
		// 	const isGptImage = selectedImageModelSlug.startsWith('gpt-image-');


		// 	if (selectedImageModelSlug === 'dall-e-2') {

		// 		$('.sc-wordai-dalle3-row, .sc-wordai-gptimage1-row').stop(true, true).fadeOut(function() {
		// 			$('.sc-wordai-dalle2-row').stop(true, true).fadeIn(300);
		// 		});

		// 		return;
		// 	}

		// 	if (selectedImageModelSlug === 'dall-e-3') {

		// 		$('.sc-wordai-dalle2-row, .sc-wordai-gptimage1-row').stop(true, true).fadeOut(function() {
		// 			$('.sc-wordai-dalle3-row').stop(true, true).fadeIn(300);
		// 		});

		// 		return;
		// 	}

		// 	if (isGptImage) {

		// 		$('.sc-wordai-dalle2-row, .sc-wordai-dalle3-row').stop(true, true).fadeOut(function() {
		// 			$('.sc-wordai-gptimage1-row').stop(true, true).fadeIn(300);
		// 		});

		// 		return;
		// 	}

		// 	// ✅ Fallback (prevents stale UI if a new model is added later)
		// 	$('.sc-wordai-dalle2-row, .sc-wordai-dalle3-row, .sc-wordai-gptimage1-row').stop(true, true).fadeOut(200);
		// });

		// // on Page load - Image model change trigger to set image sizes correctly
		// $('#sc-wordai-openai-image-model-slug').trigger('change');


		// Image Settings: On change Image model show-hide related fields
		$('body').on('change', '#sc-wordai-openai-image-model-slug', function () {

			console.log('Image Settings: On change Image model show-hide related fields - select dropdown #sc-wordai-openai-image-model-slug triggered.');

			// ✅ Provider guard: NEVER show OpenAI rows if provider is Google
			const activeProvider =
				String($('#scwordai-image-settings-form').data('provider') || window.SFTCY_WORDAI_ACTIVE_PROVIDER || 'openai');

			if (activeProvider !== 'openai') {
				$('.sc-wordai-gptimage1-row').stop(true, true).hide();
				return;
			}

			let selectedImageModelSlug = $(this).val() || '';
			const isGptImage = selectedImageModelSlug.startsWith('gpt-image-');

			if (isGptImage) {
				$('.sc-wordai-gptimage1-row').stop(true, true).fadeIn(250);
				return;
			}

			$('.sc-wordai-gptimage1-row').stop(true, true).fadeOut(200);
		});

		// ✅ on Page load - ONLY trigger when provider is openai
		(function () {
			const activeProvider =
				String($('#scwordai-image-settings-form').data('provider') || window.SFTCY_WORDAI_ACTIVE_PROVIDER || 'openai');

			if (activeProvider === 'openai' && $('#sc-wordai-openai-image-model-slug').length) {
				$('#sc-wordai-openai-image-model-slug').trigger('change');
			} else {
				$('.sc-wordai-gptimage1-row').hide();
			}
		})();


		function scWordaiSyncGeminiImageMimeOptions() {
			const $model = $('#sc-wordai-gemini-image-model-slug');
			const $mime = $('#sc-wordai-gemini-image-mime');

			if (!$model.length || !$mime.length) {
				return;
			}

			const selectedModel = String($model.val() || '');
			const selectedMime = String($mime.val() || '');
			const isGemini3 = selectedModel === 'gemini-3.1-flash-image' || selectedModel === 'gemini-3.1-flash-lite-image' || selectedModel === 'gemini-3-pro-image';
			const options = isGemini3
				? { 'image/jpeg': 'JPEG (Required for Gemini 3 Image API)' }
				: {
					'image/png': 'PNG (Lossless, Best Quality)',
					'image/jpeg': 'JPEG (Compressed, Smaller Size)',
					'image/webp': 'WEBP (Modern, Lightweight)'
				};

			$mime.empty();
			Object.keys(options).forEach(function (value) {
				$mime.append($('<option>', {
					value: value,
					text: options[value],
					selected: selectedMime === value
				}));
			});

			if (!options[selectedMime]) {
				$mime.val(Object.keys(options)[0]);
			}
		}

		$('body').on('change', '#sc-wordai-gemini-image-model-slug', scWordaiSyncGeminiImageMimeOptions);
		scWordaiSyncGeminiImageMimeOptions();


	
	
	    // Placeholder texts for prompt input
	    // let placeHolderTexts	=	[ "Write your prompt / hints words...", "Ex - White Horse", "Ex - Beautiful Sky", "Ex - Summer Holidays", "Ex - Stormy Weather", "Ex - Blue Tshirt", "Ex - Artificial intelligence", "Ex - Autumn Memories" ];
	    // $('.scwordai-prompt').placeholderTypewriter({ text: placeHolderTexts, delay: 25, pause:700});

		// Placeholder texts for WordAI prompt input (WordPress-optimized)
		let placeHolderTexts = [
		"Write your prompt or content idea...",
		"Ex – Blog post about healthy morning routines",
		"Ex – SEO title for a WordPress tutorial post",
		"Ex – Product description for a leather backpack",
		"Ex – Engaging excerpt for travel blog article",
		"Ex – Meta description for WooCommerce product page",
		"Ex – Compelling headline for digital marketing post",
		"Ex – Paragraph about benefits of website speed optimization",
		"Ex – Creative intro for photography portfolio page",
		"Ex – Short ad copy for WordPress maintenance service",
		"Ex – Article about AI tools for content creators",
		"Ex – FAQ section for web design agency site",
		"Ex – Newsletter intro about upcoming product launch",
		"Ex – Social media caption for new blog release",
		"Ex – Step-by-step tutorial on installing WordPress plugins",
		"Ex – Informative paragraph for 'About Us' page",
		"Ex – Catchy title for WordPress SEO tips post",
		"Ex – Product benefits list for eCommerce landing page",
		"Ex – Conclusion paragraph for tech review post",
		"Ex – Summary text for educational course page"
		];
		$('.scwordai-prompt').placeholderTypewriter({
			text: placeHolderTexts,
			delay: 25,
			pause: 1000
		});



		// Start Minimal Mode Toggle //		
		const toggle = $('#scWordaiCompactToggle');
		const body = $('body');
		const storageKey = 'scWordaiMinimalMode';

		// Load previous state from localStorage
		if (localStorage.getItem(storageKey) === 'true') {
			body.addClass('sc-wordai-minimal-mode');
			toggle.prop('checked', true);
		}

		// Toggle behavior and persist state
		toggle.on('change', function() {
			const isMinimal = $(this).is(':checked');
			body.toggleClass('sc-wordai-minimal-mode', isMinimal);
			localStorage.setItem(storageKey, isMinimal);
		});		
		// End Minimal Mode Toggle //

		// Start Global Range Slider Enhancements //		

		$('input[type="range"]').each(function(){
			updateGradient($(this));
		}).on('input change', function(){
			updateGradient($(this));
		});

		function updateGradient($el){
			const val = ($el.val() - $el.attr('min')) / ($el.attr('max') - $el.attr('min'));
			const percent = val * 100;
			const isDark = $('body').hasClass('is-dark-theme');
			const fill = isDark ? '#3398db' : '#2271b1';
			const rest = isDark ? '#555' : '#ddd';
			$el.css('background', `linear-gradient(to right, ${fill} 0%, ${fill} ${percent}%, ${rest} ${percent}%, ${rest} 100%)`);
		}

		// Recalculate if theme mode changes
		const observer = new MutationObserver(() => {
			$('input[type="range"]').each(function(){ updateGradient($(this)); });
		});
		observer.observe(document.body, { attributes: true, attributeFilter: ['class'] });

		// End Global Range Slider Enhancements //


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



(function ($) {
  "use strict";

  $.fn.placeholderTypewriter = function (options) {

    // Plugin Settings
    var settings = $.extend({
      delay: 50,
      pause: 1000,
      text: []
    }, options);

    // Type given string in placeholder
    function typeString($target, index, cursorPosition, callback) {

      // Get text
      var text = settings.text[index];

      // Get placeholder, type next character
      var placeholder = $target.attr('placeholder');
      $target.attr('placeholder', placeholder + text[cursorPosition]);

      // Type next character
      if (cursorPosition < text.length - 1) {
        setTimeout(function () {
          typeString($target, index, cursorPosition + 1, callback);
        }, settings.delay);
        return true;
      }

      // Callback if animation is finished
      callback();
    }

    // Delete string in placeholder
    function deleteString($target, callback) {

      // Get placeholder
      var placeholder = $target.attr('placeholder');
      var length = placeholder.length;

      // Delete last character
      $target.attr('placeholder', placeholder.substr(0, length - 1));

      // Delete next character
      if (length > 1) {
        setTimeout(function () {
          deleteString($target, callback)
        }, settings.delay);
        return true;
      }

      // Callback if animation is finished
      callback();
    }

    // Loop typing animation
    function loopTyping($target, index) {

      // Clear Placeholder
      $target.attr('placeholder', '');

      // Type string
      typeString($target, index, 0, function () {

        // Pause before deleting string
        setTimeout(function () {

          // Delete string
          deleteString($target, function () {
            // Start loop over
            loopTyping($target, (index + 1) % settings.text.length)
          })

        }, settings.pause);
      })

    }

    // Run placeholderTypewriter on every given field
    return this.each(function () {
      loopTyping($(this), 0);
    });

  };

}(jQuery));
