/**
 * EasySite Pro – AI helper (OpenAI integration)
 */
window.easysiteAI = {
	suggest: function (type, target) {
		if (!window.easysiteAdmin) {
			console.warn('EasySite AI: admin config missing');
			return;
		}

		var original = target.value;
		var notice = target.parentNode.querySelector('.easysite-ai-notice');
		if (!notice) {
			notice = document.createElement('p');
			notice.className = 'easysite-ai-notice description';
			target.parentNode.appendChild(notice);
		}

		target.value = '…';
		target.disabled = true;
		notice.textContent = easysiteAdmin.i18n.saving || 'Generating…';

		jQuery.post(easysiteAdmin.ajaxUrl, {
			action: 'easysite_ai_suggest',
			nonce: easysiteAdmin.nonce,
			suggest_type: type,
			context: original
		}).done(function (res) {
			if (res.success && res.data.text) {
				target.value = res.data.text;
				notice.textContent = res.data.message || '';
			} else {
				target.value = original;
				notice.textContent = easysiteAdmin.i18n.error || 'Error';
			}
		}).fail(function () {
			target.value = original;
			notice.textContent = easysiteAdmin.i18n.error || 'Error';
		}).always(function () {
			target.disabled = false;
		});
	}
};
