/**
* Article Editor - core UX for AI-powered article generation and editing.
*/
import { useState, useEffect, useCallback, useRef } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import {
Button,
TextControl,
TextareaControl,
SelectControl,
TabPanel,
Spinner,
RangeControl,
FormTokenField,
CheckboxControl,
ToggleControl,
Panel,
PanelBody,
} from '@aime/wp-components';
import { Icon, chevronLeft } from '@wordpress/icons';
import useApi from '../../../hooks/useApi';
import useSlowWarning from '../../../hooks/useSlowWarning';
import Card from '../../common/Card';
import LoadingBtn from '../../common/LoadingBtn';
import Loader from '../../common/Loader';
import { toast } from '../../common/Toast';
import { ARTICLE_STATUS_LABELS } from '../../../utils/constants';
import { consumePrefillData } from '../../../utils/seoContentBridge';
const TONES = [
{ label: 'Professional', value: 'professional' },
{ label: 'Casual', value: 'casual' },
{ label: 'Friendly', value: 'friendly' },
{ label: 'Authoritative', value: 'authoritative' },
{ label: 'Humorous', value: 'humorous' },
{ label: 'Formal', value: 'formal' },
{ label: 'Conversational', value: 'conversational' },
];
const PRO_TONES = [ 'humorous', 'formal', 'conversational' ];
const LANGUAGES = [
{ label: 'English', value: 'en' },
{ label: 'Bengali', value: 'bn' },
{ label: 'Spanish', value: 'es' },
{ label: 'French', value: 'fr' },
{ label: 'German', value: 'de' },
{ label: 'Hindi', value: 'hi' },
{ label: 'Arabic', value: 'ar' },
{ label: 'Portuguese', value: 'pt' },
{ label: 'Chinese', value: 'zh' },
{ label: 'Japanese', value: 'ja' },
{ label: 'Korean', value: 'ko' },
{ label: 'Russian', value: 'ru' },
{ label: 'Italian', value: 'it' },
{ label: 'Dutch', value: 'nl' },
{ label: 'Turkish', value: 'tr' },
{ label: 'Indonesian', value: 'id' },
{ label: 'Vietnamese', value: 'vi' },
{ label: 'Thai', value: 'th' },
{ label: 'Polish', value: 'pl' },
{ label: 'Swedish', value: 'sv' },
{ label: 'Urdu', value: 'ur' },
{ label: 'Malay', value: 'ms' },
];
const defaultArticle = {
title: '',
topic: '',
keywords: [],
tone: 'professional',
language: 'en',
word_count_target: 1000,
content: '',
excerpt: '',
outline: '',
meta_title: '',
meta_description: '',
categories: [],
tags: [],
featured_image_url: '',
featured_image_id: 0,
post_type: 'post',
default_post_status: 'draft',
brand_voice_id: '',
serp_outline_context: '',
include_table_of_contents: false,
include_quick_answer: true,
include_faq: true,
scheduled_publish_at: '',
preset_id: '',
status: 'draft',
};
const toDateTimeLocalValue = ( value ) => ( value ? value.replace( ' ', 'T' ).slice( 0, 16 ) : '' );
/* Inline icons — emoji get swapped for remote twemoji images by wp-emoji. */
const ICON_CAMERA = (
);
const ICON_SPARKLE = (
);
const ICON_UPLOAD = (
);
const ArticleEditor = ( { id, onBack, onNavigate } ) => {
const { get, post, put, del, loading } = useApi( { toastErrors: true } );
const slowWarning = useSlowWarning();
const toneOptions = TONES.map( ( tone ) => ( {
...tone,
label: tone.label,
} ) );
const aiConfigured = window.aimeData?.aiConfigured ?? false;
const aiDisabledTitle = __( 'Please set up an AI provider API key in Settings first.', 'ai-marketing-expert' );
// Validate required fields before saving.
const validateSaveFields = () => {
const e = {};
if ( ! article.topic.trim() ) {
e.topic = __( 'Topic / Subject is required.', 'ai-marketing-expert' );
}
setErrors( e );
return Object.keys( e ).length === 0;
};
const [ article, setArticle ] = useState( { ...defaultArticle } );
const [ presets, setPresets ] = useState( [] );
const [ brandVoices, setBrandVoices ] = useState( [] );
const [ versions, setVersions ] = useState( [] );
const [ taxonomies, setTaxonomies ] = useState( { categories: [], tags: [], post_types: [] } );
const [ vaultKeywords, setVaultKeywords ] = useState( [] );
const [ generating, setGenerating ] = useState( false );
const [ generatingOutline, setGeneratingOutline ] = useState( false );
const [ generatingMeta, setGeneratingMeta ] = useState( false );
const [ humanizing, setHumanizing ] = useState( false );
const [ saving, setSaving ] = useState( false );
const [ publishing, setPublishing ] = useState( false );
const [ scheduling, setScheduling ] = useState( false );
const [ showSchedule, setShowSchedule ] = useState( false );
const [ scheduleValue, setScheduleValue ] = useState( '' );
const [ loaded, setLoaded ] = useState( false );
const [ seoResult, setSeoResult ] = useState( null );
const [ activeTab, setActiveTab ] = useState( 'compose' );
const [ generatingImage, setGeneratingImage ] = useState( false );
const [ imageTab, setImageTab ] = useState( 'stock' );
// null = not checked yet, true = provider key present, false = needs setup.
const [ stockReady, setStockReady ] = useState( null );
const [ imageProgress, setImageProgress ] = useState( '' );
const [ imageError, setImageError ] = useState( '' );
const [ stockQuery, setStockQuery ] = useState( '' );
const [ stockResults, setStockResults ] = useState( [] );
const [ stockSearching, setStockSearching ] = useState( false );
const [ stockImporting, setStockImporting ] = useState( '' );
const [ stockError, setStockError ] = useState( '' );
const [ stockSearched, setStockSearched ] = useState( false );
const [ generateError, setGenerateError ] = useState( '' );
const [ errors, setErrors ] = useState( {} );
const [ showThinkingHint, setShowThinkingHint ] = useState( true );
const editorId = 'aime-tinymce-editor';
const editorReady = useRef( false );
const editorWrapRef = useRef( null );
const contentRef = useRef( '' ); // tracks article.content for imperative syncing
// Validate required fields before AI generation.
const validateGenFields = () => {
const e = {};
if ( ! article.topic.trim() ) {
e.topic = __( 'Topic / Subject is required.', 'ai-marketing-expert' );
}
if ( ! article.keywords || article.keywords.length === 0 ) {
e.keywords = __( 'Add at least one keyword.', 'ai-marketing-expert' );
}
setErrors( e );
return Object.keys( e ).length === 0;
};
// Load existing article, presets, taxonomies.
useEffect( () => {
const init = async () => {
try {
const [ presetsRes, taxRes, voiceRes ] = await Promise.all( [
get( '/content/presets' ),
get( '/content/wp-taxonomies' ),
get( '/content/brand-voices' ),
] );
setPresets( presetsRes || [] );
setTaxonomies( taxRes || { categories: [], tags: [], post_types: [] } );
setBrandVoices( voiceRes.items || [] );
// Fetch keyword vault items for suggestions dropdown.
try {
const kwRes = await get( '/seo/keywords', { per_page: 200 } );
const kwItems = ( kwRes.items || kwRes.data || [] ).map( ( kw ) => kw.keyword ).filter( Boolean );
setVaultKeywords( kwItems );
} catch ( e ) {
// SEO module may not be active - silent.
}
if ( id ) {
const res = await get( `/content/articles/${ id }` );
try {
const versionRes = await get( `/content/articles/${ id }/versions` );
setVersions( versionRes.items || [] );
} catch ( e ) {}
setArticle( {
...defaultArticle,
...res,
word_count_target: parseInt( res.word_count_target ) || defaultArticle.word_count_target,
keywords: ( Array.isArray( res.keywords ) ? res.keywords : [] ).filter( ( k ) => typeof k === 'string' && k !== '' ),
categories: ( Array.isArray( res.category_ids ) ? res.category_ids : [] ).map( Number ).filter( Boolean ),
tags: ( Array.isArray( res.tag_ids ) ? res.tag_ids : [] ).filter( ( t ) => typeof t === 'string' && t !== '' ),
featured_image_url: res.featured_image_url || '',
featured_image_id: res.featured_image_id || 0,
brand_voice_id: res.brand_voice_id || '',
outline: typeof res.outline === 'object' ? JSON.stringify( res.outline, null, 2 ) : ( res.outline || '' ),
} );
} else {
// Apply saved settings defaults for new articles.
try {
const settings = await get( '/content/settings' );
if ( settings ) {
setArticle( ( prev ) => ( {
...prev,
tone: settings.default_tone || prev.tone,
language: settings.default_language || prev.language,
word_count_target: parseInt( settings.default_word_count ) || prev.word_count_target,
post_type: settings.default_post_type || prev.post_type,
default_post_status: settings.default_post_status || prev.default_post_status,
categories: settings.default_category_id ? [ Number( settings.default_category_id ) ] : prev.categories,
brand_voice_id: ( voiceRes.items || [] ).find( ( voice ) => Number( voice.is_default ) === 1 )?.id || prev.brand_voice_id,
} ) );
}
} catch ( e ) {
// Use hardcoded defaults on failure.
}
// Apply SEO module prefill data (keyword vault, content calendar, topic map).
const prefill = consumePrefillData();
if ( prefill ) {
setArticle( ( prev ) => ( {
...prev,
...( prefill.topic && { topic: prefill.topic } ),
...( prefill.title && { title: prefill.title } ),
...( prefill.keywords?.length && { keywords: prefill.keywords } ),
...( prefill.outline && { outline: prefill.outline } ),
...( prefill.word_count_target && { word_count_target: parseInt( prefill.word_count_target, 10 ) || prev.word_count_target } ),
...( prefill.meta_title && { meta_title: prefill.meta_title } ),
...( prefill.meta_description && { meta_description: prefill.meta_description } ),
...( prefill.excerpt && { excerpt: prefill.excerpt } ),
} ) );
}
}
} catch ( e ) {
// silent
} finally {
setLoaded( true );
}
};
init();
}, [ get, id ] );
// TinyMCE lifecycle (init + cleanup in one effect)
useEffect( () => {
const wrap = editorWrapRef.current;
if ( ! wrap || editorReady.current ) return;
// Safety: remove any stale TinyMCE instance with the same ID.
try {
const api = window.wp?.oldEditor || window.wp?.editor;
if ( api && window.tinymce?.get( editorId ) ) {
api.remove( editorId );
}
} catch ( e ) { /* */ }
wrap.innerHTML = '';
// Create textarea imperatively so React doesn't track it.
const ta = document.createElement( 'textarea' );
ta.id = editorId;
ta.className = 'wp-editor-area';
ta.rows = 20;
ta.value = contentRef.current || '';
wrap.appendChild( ta );
const api = window.wp?.oldEditor || window.wp?.editor;
if ( api ) {
api.initialize( editorId, {
tinymce: {
wpautop: true,
plugins: 'charmap colorpicker hr lists media paste tabfocus textcolor wordpress wpautoresize wpeditimage wpemoji wpgallery wplink wptextpattern',
toolbar1: 'formatselect | bold italic underline strikethrough | bullist numlist | blockquote hr | alignleft aligncenter alignright | link unlink | wp_adv',
toolbar2: 'strikethrough hr forecolor pastetext removeformat charmap outdent indent undo redo wp_help',
height: 400,
statusbar: false,
setup( editor ) {
editor.on( 'change keyup', () => {
const content = editor.getContent();
contentRef.current = content;
setField( 'content', content );
} );
},
},
quicktags: true,
mediaButtons: true,
} );
editorReady.current = true;
}
return () => {
const cleanApi = window.wp?.oldEditor || window.wp?.editor;
if ( cleanApi && editorReady.current ) {
try { cleanApi.remove( editorId ); } catch ( e ) { /* */ }
}
try {
const inst = window.tinymce?.get( editorId );
if ( inst ) inst.remove();
} catch ( e ) { /* */ }
editorReady.current = false;
if ( wrap ) wrap.innerHTML = '';
};
}, [ loaded ] );
// Keep contentRef in sync so the imperative textarea gets the right initial value.
useEffect( () => {
contentRef.current = article.content || '';
}, [ article.content ] );
useEffect( () => {
setScheduleValue( toDateTimeLocalValue( article.scheduled_publish_at ) );
}, [ article.scheduled_publish_at ] );
// Sync React state -> TinyMCE when content changes externally (e.g. AI generation).
useEffect( () => {
if ( ! editorReady.current ) return;
const tinymceInst = window.tinymce?.get( editorId );
if ( tinymceInst && tinymceInst.getContent() !== article.content ) {
tinymceInst.setContent( article.content || '' );
}
}, [ article.content ] );
const setField = ( key, value ) => {
setArticle( ( prev ) => ( { ...prev, [ key ]: value } ) );
};
// Save article
const handleSave = async () => {
if ( ! validateSaveFields() ) {
toast( __( 'Please fill in all required fields before saving.', 'ai-marketing-expert' ), 'error' );
return;
}
setSaving( true );
try {
// Parse outline back to object to prevent double-encoding on the server.
let outlineParsed = article.outline || [];
if ( typeof outlineParsed === 'string' ) {
try { outlineParsed = JSON.parse( outlineParsed ); } catch ( e ) { outlineParsed = []; }
}
const payload = {
...article,
word_count_target: article.word_count_target,
keywords: article.keywords,
category_ids: ( article.categories || [] ).map( Number ),
tag_ids: article.tags,
outline: outlineParsed,
featured_image_url: article.featured_image_url || '',
featured_image_id: article.featured_image_id || 0,
};
delete payload.categories;
delete payload.tags;
delete payload.category_ids_raw;
delete payload.tag_ids_raw;
if ( id ) {
await put( `/content/articles/${ id }`, payload );
toast( __( 'Article saved.', 'ai-marketing-expert' ) );
const versionRes = await get( `/content/articles/${ id }/versions` );
setVersions( versionRes.items || [] );
} else {
const res = await post( '/content/articles', payload );
toast( __( 'Article created.', 'ai-marketing-expert' ) );
if ( res?.id ) {
onNavigate( 'edit-article', { id: res.id } );
}
}
} catch ( e ) {
toast( e.message, 'error' );
} finally {
setSaving( false );
}
};
// Generate full article with AI
const handleGenerate = async () => {
if ( ! validateGenFields() ) {
toast( __( 'Please fill in all required fields.', 'ai-marketing-expert' ), 'error' );
return;
}
setGenerating( true );
setGenerateError( '' );
// Warn immediately — article generation can take up to 5 minutes.
// The toast auto-hides after 10s (user can dismiss earlier with ×),
// and slowWarning.start() below fires another reminder after 15s.
toast(
__( 'Article generation started. This may take up to 5 minutes depending on your AI model and word count. Please keep this page open.', 'ai-marketing-expert' ),
'warning',
10000
);
slowWarning.start();
try {
const payload = {
topic: article.topic,
keywords: article.keywords,
tone: article.tone,
word_count: article.word_count_target,
language: article.language,
outline: article.outline,
serp_context: article.serp_outline_context,
include_table_of_contents: !! article.include_table_of_contents,
include_quick_answer: article.include_quick_answer !== false,
include_faq: article.include_faq !== false,
post_type: article.post_type || 'post',
category_ids: ( article.categories || [] ).map( Number ),
tag_ids: article.tags || [],
brand_voice_id: article.brand_voice_id || 0,
preset_id: article.preset_id || undefined,
};
const res = await post( '/content/generate', payload );
if ( res?.id ) {
// Article is auto-saved by the API. Navigate to edit it.
if ( res.partial ) {
// A provider ran out of capacity mid-article — say so instead
// of claiming success on a short article.
toast( res.message || __( 'Article saved, but it may be incomplete.', 'ai-marketing-expert' ), 'warning' );
} else if ( res.continued > 0 ) {
toast( res.message || __( 'Article generated successfully! Redirecting...', 'ai-marketing-expert' ), 'success' );
} else {
toast( __( 'Article generated successfully! Redirecting...', 'ai-marketing-expert' ) );
}
onNavigate( 'edit-article', { id: res.id } );
return;
}
// Fallback: populate inline if no id returned.
if ( res?.parsed ) {
setField( 'title', res.parsed.title || article.title );
setField( 'content', res.parsed.body || res.content || '' );
setField( 'excerpt', res.parsed.excerpt || '' );
if ( res.parsed.outline ) {
setField( 'outline', JSON.stringify( res.parsed.outline, null, 2 ) );
}
} else if ( res?.content ) {
setField( 'content', res.content );
}
toast( __( 'Article generated! Review and save.', 'ai-marketing-expert' ) );
} catch ( e ) {
const msg = e?.message || __( 'AI generation failed. Check your AI provider settings.', 'ai-marketing-expert' );
setGenerateError( msg );
toast( msg, 'error' );
} finally {
slowWarning.stop();
setGenerating( false );
}
};
// Search free stock photos (Pexels / Pixabay via plugin settings).
// Stock search needs a Pexels/Pixabay key; check once so the tab can point
// the user at Settings instead of failing on the first search.
useEffect( () => {
let cancelled = false;
( async () => {
try {
const s = await get( '/content/settings' );
if ( cancelled ) return;
const provider = s?.stock_provider || 'pexels';
setStockReady( provider === 'pixabay' ? !! s?.has_pixabay_key : !! s?.has_pexels_key );
} catch ( e ) {
if ( ! cancelled ) setStockReady( true ); // Don't block on a failed probe.
}
} )();
return () => { cancelled = true; };
}, [ get ] );
const handleStockSearch = async ( queryOverride ) => {
const q = ( queryOverride ?? stockQuery ?? '' ).trim() || article.topic || article.title || '';
if ( ! q ) {
setStockError( __( 'Enter a search term (or set a topic/title first).', 'ai-marketing-expert' ) );
return;
}
setStockQuery( q );
setStockSearching( true );
setStockError( '' );
try {
const res = await get( `/content/stock-images/search?query=${ encodeURIComponent( q ) }&per_page=12` );
setStockResults( res?.images || [] );
setStockSearched( true );
} catch ( e ) {
setStockResults( [] );
setStockError( e?.message || __( 'Stock image search failed.', 'ai-marketing-expert' ) );
} finally {
setStockSearching( false );
}
};
// Import a chosen stock photo into the media library and set as featured.
const handleStockPick = async ( image ) => {
setStockImporting( String( image.id ) );
setStockError( '' );
try {
const res = await post( '/content/stock-images/import', {
url: image.full,
alt: image.alt || article.title || '',
article_id: id || 0,
} );
if ( res?.attachment_id ) {
setField( 'featured_image_url', res.url );
setField( 'featured_image_id', res.attachment_id );
toast( __( 'Featured image set from stock photo!', 'ai-marketing-expert' ) );
}
} catch ( e ) {
const msg = e?.message || __( 'Image import failed.', 'ai-marketing-expert' );
setStockError( msg );
toast( msg, 'error' );
} finally {
setStockImporting( '' );
}
};
// Humanize content (rewrite to sound natural)
const handleHumanize = async () => {
const activeContent = ( editorReady.current && window.tinymce?.get( editorId )?.getContent() ) || article.content;
if ( ! activeContent || ! activeContent.trim() ) {
toast( __( 'Generate or write content first before humanizing.', 'ai-marketing-expert' ), 'error' );
return;
}
setHumanizing( true );
slowWarning.start();
try {
const instruction = 'Deeply humanize this content to sound completely natural, as if written by an experienced human writer. '
+ 'CRITICAL RULES: 1) Preserve the ENTIRE article from the very beginning — keep all opening introductory paragraphs, lead-in text, and all sections. '
+ '2) Do NOT delete or skip the introduction or any paragraphs before headings or images. '
+ '3) Keep approximately the same word count — do NOT shorten or truncate the content. '
+ '4) Keep the same HTML structure (h2, h3, p, ul, ol, li, strong, em, a tags). '
+ '5) Copy all placeholder markers (like [[AIME_...]]) in their exact places. '
+ '6) Vary sentence length, use natural transitions, and remove AI-like patterns. '
+ '7) Preserve the original meaning and all key points. '
+ 'Return ONLY the improved HTML content.';
const res = await post( '/content/generate/improve', {
content: activeContent,
instruction,
tone: article.tone || 'professional',
article_id: id || undefined,
} );
if ( res?.content ) {
setField( 'content', res.content );
if ( editorReady.current ) {
const inst = window.tinymce?.get( editorId );
if ( inst ) {
inst.setContent( res.content );
}
}
if ( id ) {
get( `/content/articles/${ id }/versions` ).then( ( vRes ) => {
if ( vRes?.items ) {
setVersions( vRes.items );
}
} ).catch( () => {} );
}
toast( __( 'Content deeply humanized!', 'ai-marketing-expert' ), 'success' );
}
} catch ( e ) {
toast( e?.message || __( 'Humanize failed. Please try again.', 'ai-marketing-expert' ), 'error' );
} finally {
slowWarning.stop();
setHumanizing( false );
}
};
// Generate outline
const handleGenerateOutline = async () => {
if ( ! validateGenFields() ) {
toast( __( 'Please fill in all required fields.', 'ai-marketing-expert' ), 'error' );
return;
}
setGeneratingOutline( true );
slowWarning.start();
try {
const res = await post( '/content/generate/outline', {
topic: article.topic,
keywords: article.keywords,
tone: article.tone,
style: 'blog_post',
serp_context: article.serp_outline_context,
} );
if ( res?.outline ) {
setField( 'outline', JSON.stringify( res.outline, null, 2 ) );
if ( res.outline.title && ! article.title ) {
setField( 'title', res.outline.title );
}
}
toast( __( 'Outline generated!', 'ai-marketing-expert' ) );
} catch ( e ) {
toast( e.message, 'error' );
} finally {
slowWarning.stop();
setGeneratingOutline( false );
}
};
// Generate meta
const handleGenerateMeta = async () => {
if ( ! article.content ) {
toast( __( 'Generate or write content first.', 'ai-marketing-expert' ), 'error' );
return;
}
setGeneratingMeta( true );
slowWarning.start();
try {
const res = await post( '/content/generate/meta', {
title: article.title,
content: article.content,
keywords: article.keywords,
} );
if ( res?.meta ) {
setField( 'meta_title', res.meta.meta_title || '' );
setField( 'meta_description', res.meta.meta_description || '' );
}
toast( __( 'Meta generated!', 'ai-marketing-expert' ) );
} catch ( e ) {
toast( e.message, 'error' );
} finally {
slowWarning.stop();
setGeneratingMeta( false );
}
};
// SEO optimize
const handleSeoOptimize = async () => {
slowWarning.start();
try {
const res = await post( '/content/generate/seo-optimize', {
content: article.content,
keywords: article.keywords,
title: article.title,
article_id: id || undefined,
} );
if ( res?.analysis ) {
setSeoResult( res.analysis );
if ( res.analysis.seo_score !== undefined ) {
setField( 'seo_score', res.analysis.seo_score );
}
if ( res.analysis.readability_score !== undefined ) {
setField( 'readability_score', res.analysis.readability_score );
}
}
toast( __( 'SEO analysis complete!', 'ai-marketing-expert' ) );
} catch ( e ) {
toast( e.message, 'error' );
} finally {
slowWarning.stop();
}
};
// Publish to WordPress
const handlePublish = async ( postStatus = article.default_post_status || 'draft' ) => {
if ( ! validateSaveFields() ) {
toast( __( 'Please fill in all required fields before publishing.', 'ai-marketing-expert' ), 'error' );
return;
}
setPublishing( postStatus );
try {
// Auto-save first if article has no id yet.
let articleId = id;
if ( ! articleId ) {
let outlineParsed = article.outline || [];
if ( typeof outlineParsed === 'string' ) {
try { outlineParsed = JSON.parse( outlineParsed ); } catch ( e ) { outlineParsed = []; }
}
const payload = {
...article,
word_count_target: article.word_count_target,
keywords: article.keywords,
category_ids: ( article.categories || [] ).map( Number ),
tag_ids: article.tags,
outline: outlineParsed,
featured_image_url: article.featured_image_url || '',
featured_image_id: article.featured_image_id || 0,
};
delete payload.categories;
delete payload.tags;
const saved = await post( '/content/articles', payload );
if ( saved?.id ) {
articleId = saved.id;
onNavigate( 'edit-article', { id: saved.id } );
} else {
toast( __( 'Could not save article before publishing.', 'ai-marketing-expert' ), 'error' );
return;
}
}
const res = await post( `/content/articles/${ articleId }/publish`, { post_status: postStatus } );
const successMessages = {
draft: __( 'Saved as draft in WordPress!', 'ai-marketing-expert' ),
publish: __( 'Published to WordPress!', 'ai-marketing-expert' ),
pending: __( 'Submitted for review in WordPress!', 'ai-marketing-expert' ),
private: __( 'Saved as private in WordPress!', 'ai-marketing-expert' ),
};
toast( successMessages[ postStatus ] || __( 'Sent to WordPress!', 'ai-marketing-expert' ), 'success' );
if ( res?.edit_url ) {
setField( 'wp_edit_url', res.edit_url );
}
if ( res?.view_url ) {
setField( 'view_url', res.view_url );
}
if ( res?.wp_post_id ) {
setField( 'wp_post_id', res.wp_post_id );
}
if ( res?.status ) {
setField( 'status', res.status );
}
} catch ( e ) {
toast( e.message || __( 'Publishing failed.', 'ai-marketing-expert' ), 'error' );
} finally {
setPublishing( false );
}
};
const handleSchedulePublish = async () => {
if ( ! validateSaveFields() ) {
toast( __( 'Please fill in all required fields before scheduling.', 'ai-marketing-expert' ), 'error' );
return;
}
if ( ! scheduleValue ) {
toast( __( 'Select a publish date and time.', 'ai-marketing-expert' ), 'error' );
return;
}
setScheduling( true );
try {
let articleId = id;
if ( ! articleId ) {
let outlineParsed = article.outline || [];
if ( typeof outlineParsed === 'string' ) {
try { outlineParsed = JSON.parse( outlineParsed ); } catch ( e ) { outlineParsed = []; }
}
const payload = {
...article,
word_count_target: article.word_count_target,
keywords: article.keywords,
category_ids: ( article.categories || [] ).map( Number ),
tag_ids: article.tags,
outline: outlineParsed,
featured_image_url: article.featured_image_url || '',
featured_image_id: article.featured_image_id || 0,
scheduled_publish_at: scheduleValue,
};
delete payload.categories;
delete payload.tags;
const saved = await post( '/content/articles', payload );
if ( saved?.id ) {
articleId = saved.id;
onNavigate( 'edit-article', { id: saved.id } );
} else {
toast( __( 'Could not save article before scheduling.', 'ai-marketing-expert' ), 'error' );
return;
}
}
const res = await post( `/content/articles/${ articleId }/schedule`, {
scheduled_publish_at: scheduleValue,
} );
setField( 'status', res?.status || 'scheduled' );
setField( 'scheduled_publish_at', res?.scheduled_publish_at || scheduleValue.replace( 'T', ' ' ) + ':00' );
setShowSchedule( false );
toast( __( 'Article scheduled in WordPress.', 'ai-marketing-expert' ), 'success' );
} catch ( e ) {
toast( e.message || __( 'Scheduling failed.', 'ai-marketing-expert' ), 'error' );
} finally {
setScheduling( false );
}
};
if ( ! loaded ) {
return
{ generateError }
) } { ! aiConfigured && ({ __( '\u26A0 AI features are disabled. Please configure an AI provider API key in', 'ai-marketing-expert' ) }{ ' ' } { __( 'Settings', 'ai-marketing-expert' ) } .
) }{ __( '\u2139 Content length and quality depend on your AI model. Larger models produce more accurate word counts and higher-quality content.', 'ai-marketing-expert' ) }
{ article.outline }
{ __( 'A title will be auto-generated by AI, or you can type one manually.', 'ai-marketing-expert' ) }
) }{ __( 'AI is writing your article...', 'ai-marketing-expert' ) }
{ __( 'Some AI models emit internal reasoning before the actual article. The plugin automatically stripped it from this output.', 'ai-marketing-expert' ) }
{ __( '\u26A0 Configure an AI provider key in Settings to enable AI features.', 'ai-marketing-expert' ) }
) } { /* SEO scores */ } { ( article.seo_score !== undefined && article.seo_score !== null && article.seo_score !== '' ) ? ({ issue.suggestion }
}\u2022 { s }
) ) }{ __( 'Stock photo search needs a provider API key. Add one first — both Pexels and Pixabay are free and take about a minute to set up.', 'ai-marketing-expert' ) }
> ) : ( <>{ __( 'Search free stock photos and set one as the featured image. Photos are saved to your Media Library.', 'ai-marketing-expert' ) }
{ stockError }
} { ! stockError && stockSearched && stockResults.length === 0 && ! stockSearching && ({ __( 'No photos found. Try a broader search term.', 'ai-marketing-expert' ) }
) } { stockResults.length > 0 && ({ __( 'Generate a featured image from your article content using AI.', 'ai-marketing-expert' ) }
{ generatingImage ? ({ __( 'Image generation may take 30-60 seconds depending on your AI model.', 'ai-marketing-expert' ) }
{ imageError }
) } { ( ! article.title && ! article.content ) && ({ __( 'Write or generate article content first, then generate a featured image.', 'ai-marketing-expert' ) }
) }{ __( 'Upload an image or pick one from your WordPress Media Library.', 'ai-marketing-expert' ) }
{ __( 'No saved versions yet.', 'ai-marketing-expert' ) }
) : (