/**
* Bot Editor - tabbed form for creating / editing a chatbot.
* Tabs: General, Appearance, Lead Capture, Page Rules, Advanced.
*/
import { useState, useEffect, useCallback } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import {
Button,
TextControl,
TextareaControl,
SelectControl,
ToggleControl,
TabPanel,
Spinner,
} from '@aime/wp-components';
import useApi from '../../../../hooks/useApi';
import Card from '../../../common/Card';
import Loader from '../../../common/Loader';
import Notice from '../../../common/Notice';
import { toast } from '../../../common/Toast';
const THEME_OPTIONS = [
{ label: 'Default (Indigo)', value: 'default' },
{ label: 'Modern (Dark)', value: 'modern' },
{ label: 'Minimal (Green)', value: 'minimal' },
];
const POSITION_OPTIONS = [
{ label: 'Bottom Right', value: 'bottom-right' },
{ label: 'Bottom Left', value: 'bottom-left' },
];
const FREE_LEAD_TRIGGERS = [ 'start', 'after_messages', 'ai_intent' ];
const VALID_LEAD_TRIGGERS = [ 'start', 'after_messages', 'ai_intent' ];
const getLeadTriggerOptions = () => [
{ label: __( 'Start with lead form', 'ai-marketing-expert' ), value: 'start' },
{ label: __( 'After X messages', 'ai-marketing-expert' ), value: 'after_messages' },
{ label: __( 'On AI detection', 'ai-marketing-expert' ), value: 'ai_intent' },
];
const RESPONSE_TONE_OPTIONS = [
{ label: 'Friendly', value: 'friendly' },
{ label: 'Professional', value: 'professional' },
{ label: 'Neutral', value: 'neutral' },
];
const RESPONSE_LENGTH_OPTIONS = [
{ label: 'Short', value: 'short' },
{ label: 'Balanced', value: 'balanced' },
{ label: 'Detailed', value: 'detailed' },
];
const RESPONSE_STYLE_OPTIONS = [
{ label: 'Confident', value: 'confident' },
{ label: 'Careful', value: 'careful' },
{ label: 'Sales-focused', value: 'sales' },
];
const TABS = [
{ name: 'general', title: __( 'General', 'ai-marketing-expert' ) },
{ name: 'appearance', title: __( 'Appearance', 'ai-marketing-expert' ) },
{ name: 'lead-capture', title: __( 'Lead Capture', 'ai-marketing-expert' ) },
{ name: 'page-rules', title: __( 'Page Rules', 'ai-marketing-expert' ) },
{ name: 'advanced', title: __( 'Advanced', 'ai-marketing-expert' ) },
];
const DEFAULT_BOT = {
name: '',
welcome_message: 'Hi! How can I help you today?',
system_prompt: '',
status: 'active',
theme_id: 'default',
position: 'bottom-right',
offset_y: 0,
offset_x: 0,
primary_color: '#4f46e5',
bubble_icon: 'chat',
page_rules: '[]',
lead_capture_config: JSON.stringify( {
enabled: true,
trigger: 'after_messages',
trigger_count: 3,
fields: [ 'email', 'name' ],
heading: 'Get in touch',
} ),
banned_words: '',
max_history_messages: 20,
response_tone: 'friendly',
response_length: 'short',
response_style: 'confident',
sales_focused: false,
custom_response_style: '',
};
const BotEditor = ( { id, onBack, onNavigate } ) => {
const { get, post, put, loading, error, clearError } = useApi();
const [ bot, setBot ] = useState( null );
const [ saving, setSaving ] = useState( false );
const [ success, setSuccess ] = useState( '' );
const isNew = ! id;
const fetchBot = useCallback( async () => {
if ( isNew ) {
setBot( { ...DEFAULT_BOT } );
return;
}
try {
const res = await get( `/chatbot/bots/${ id }` );
// Unpack theme_config to flat fields for editing.
const tc = res.theme_config || {};
const kc = res.knowledge_config || {};
setBot( {
...res,
theme_id: res.theme_id || 'default',
position: tc.position || 'bottom-right',
offset_y: Number( tc.offset_y || 0 ),
offset_x: Number( tc.offset_x || 0 ),
primary_color: tc.primary_color || '#4f46e5',
bubble_icon: tc.bubble_icon || 'chat',
max_history_messages: kc.max_history_messages || 20,
response_tone: kc.response_tone || 'friendly',
response_length: kc.response_length || 'short',
response_style: kc.response_style || 'confident',
sales_focused: !! kc.sales_focused,
custom_response_style: kc.custom_response_style || '',
} );
} catch ( e ) {
// silent
}
}, [ get, id, isNew ] );
useEffect( () => {
fetchBot();
}, [ fetchBot ] );
const setField = ( key, value ) => {
setBot( ( prev ) => ( { ...prev, [ key ]: value } ) );
};
const renderOffsetControl = ( { field, label, help, negativeLabel, positiveLabel } ) => {
const value = Number( bot?.[ field ] ?? 0 );
return (
{ value }px
setField( field, 0 ) }
disabled={ value === 0 }
style={ { whiteSpace: 'nowrap' } }
>
{ __( 'Reset 0', 'ai-marketing-expert' ) }
setField( field, parseInt( e.target.value, 10 ) || 0 ) }
style={ { width: '100%', accentColor: '#4f46e5', margin: '4px 0 8px' } }
/>
{ negativeLabel }
{ __( '0 center', 'ai-marketing-expert' ) }
{ positiveLabel }
);
};
const getLeadConfig = () => {
try {
return typeof bot.lead_capture_config === 'string'
? JSON.parse( bot.lead_capture_config )
: ( bot.lead_capture_config || {} );
} catch {
return { enabled: true, trigger: 'after_messages', trigger_count: 3, fields: [ 'email', 'name' ], heading: 'Get in touch' };
}
};
const setLeadField = ( key, value ) => {
const config = getLeadConfig();
config[ key ] = value;
setField( 'lead_capture_config', JSON.stringify( config ) );
};
const getPageRules = () => {
try {
return typeof bot.page_rules === 'string'
? JSON.parse( bot.page_rules )
: ( bot.page_rules || [] );
} catch {
return [];
}
};
const setPageRules = ( rules ) => {
setField( 'page_rules', JSON.stringify( rules ) );
};
const addPageRule = () => {
const rules = getPageRules();
rules.push( { type: 'include', pattern: '/*' } );
setPageRules( rules );
};
const normalizeLeadFields = ( fields ) => {
return Array.isArray( fields ) ? fields : [];
};
const updatePageRule = ( index, key, value ) => {
const rules = getPageRules();
rules[ index ][ key ] = value;
setPageRules( rules );
};
const removePageRule = ( index ) => {
const rules = getPageRules();
rules.splice( index, 1 );
setPageRules( rules );
};
const handleSave = async () => {
if ( ! bot.name?.trim() ) {
toast( __( 'Bot name is required.', 'ai-marketing-expert' ), 'error' );
return;
}
setSaving( true );
setSuccess( '' );
try {
// Build payload that matches PHP data structure.
const payload = {
name: bot.name,
status: bot.status || 'active',
system_prompt: bot.system_prompt || '',
welcome_message: bot.welcome_message || '',
theme_id: bot.theme_id || 'default',
theme_config: {
position: bot.position || 'bottom-right',
offset_y: Math.max( -200, Math.min( 200, parseInt( bot.offset_y, 10 ) || 0 ) ),
offset_x: Math.max( -200, Math.min( 200, parseInt( bot.offset_x, 10 ) || 0 ) ),
primary_color: bot.primary_color || '#4f46e5',
bubble_icon: bot.bubble_icon || 'chat',
},
lead_capture_config: {
...getLeadConfig(),
trigger: getLeadConfig().trigger || 'after_messages',
fields: normalizeLeadFields( getLeadConfig().fields || [ 'email', 'name' ] ),
},
knowledge_config: {
max_history_messages: Math.max( 1, parseInt( bot.max_history_messages, 10 ) || 20 ),
response_tone: bot.response_tone || 'friendly',
response_length: bot.response_length || 'short',
response_style: bot.response_style || 'confident',
sales_focused: !! bot.sales_focused,
custom_response_style: bot.custom_response_style || '',
},
page_rules: getPageRules(),
offline_message: bot.offline_message || '',
business_hours: typeof bot.business_hours === 'string'
? JSON.parse( bot.business_hours || '{}' )
: ( bot.business_hours || {} ),
banned_words: bot.banned_words || '',
};
if ( isNew ) {
const res = await post( '/chatbot/bots', payload );
toast( __( 'Chatbot created!', 'ai-marketing-expert' ) );
onNavigate( 'edit-bot', { id: res.id } );
} else {
await put( `/chatbot/bots/${ id }`, payload );
setSuccess( __( 'Chatbot saved.', 'ai-marketing-expert' ) );
}
} catch ( e ) {
toast( e.message, 'error' );
} finally {
setSaving( false );
}
};
if ( loading && ! bot ) {
return ;
}
if ( ! bot ) return null;
const leadConfig = getLeadConfig();
const pageRules = getPageRules();
return (
{ error &&
}
{ success &&
setSuccess( '' ) } /> }
{ '\u2190' } { __( 'Back', 'ai-marketing-expert' ) }
{ isNew ? __( 'New Chatbot', 'ai-marketing-expert' ) : bot.name || __( 'Edit Chatbot', 'ai-marketing-expert' ) }
{ saving
? <> { __( 'Saving...', 'ai-marketing-expert' ) }>
: isNew ? __( 'Create Chatbot', 'ai-marketing-expert' ) : __( 'Save Changes', 'ai-marketing-expert' )
}
{ ( tab ) => {
/* General tab */
if ( tab.name === 'general' ) {
return (
setField( 'name', v ) }
placeholder={ __( 'e.g. Support Bot', 'ai-marketing-expert' ) }
__nextHasNoMarginBottom
/>
setField( 'status', v ) }
__nextHasNoMarginBottom
/>
setField( 'welcome_message', v ) }
rows={ 3 }
/>
setField( 'system_prompt', v ) }
placeholder={ __( 'Example: You are {bot_name} for {site_name}. Give clear, helpful answers and guide visitors using the current page context from {page_url}.', 'ai-marketing-expert' ) }
rows={ 6 }
/>
setField( 'response_tone', v ) }
__nextHasNoMarginBottom
/>
setField( 'response_length', v ) }
__nextHasNoMarginBottom
/>
setField( 'response_style', v ) }
__nextHasNoMarginBottom
/>
setField( 'sales_focused', v ) }
/>
setField( 'custom_response_style', v ) }
placeholder={ __( 'Example: Answer with the direct result first, then add a short helpful recommendation at the end.', 'ai-marketing-expert' ) }
rows={ 3 }
/>
);
}
/* Appearance tab */
if ( tab.name === 'appearance' ) {
return (
setField( 'theme_id', v ) }
__nextHasNoMarginBottom
/>
setField( 'position', v ) }
__nextHasNoMarginBottom
/>
{ renderOffsetControl( {
field: 'offset_y',
label: __( 'Top / Bottom Offset', 'ai-marketing-expert' ),
help: __( 'Move the widget vertically from its selected corner, up to +/- 200px.', 'ai-marketing-expert' ),
negativeLabel: __( '-200 up', 'ai-marketing-expert' ),
positiveLabel: __( '+200 down', 'ai-marketing-expert' ),
} ) }
{ renderOffsetControl( {
field: 'offset_x',
label: __( 'Left / Right Offset', 'ai-marketing-expert' ),
help: __( 'Move the widget horizontally from its selected corner, up to +/- 200px.', 'ai-marketing-expert' ),
negativeLabel: __( '-200 left', 'ai-marketing-expert' ),
positiveLabel: __( '+200 right', 'ai-marketing-expert' ),
} ) }
setField( 'bubble_icon', v ) }
__nextHasNoMarginBottom
/>
);
}
/* Lead capture tab */
if ( tab.name === 'lead-capture' ) {
return (
setLeadField( 'enabled', v ) }
/>
{ leadConfig.enabled && (
<>
setLeadField( 'trigger', v ) }
__nextHasNoMarginBottom
/>
{ ( leadConfig.trigger || 'after_messages' ) === 'after_messages' && (
setLeadField( 'trigger_count', Math.max( 1, parseInt( v, 10 ) || 3 ) ) }
__nextHasNoMarginBottom
/>
) }
setLeadField( 'heading', v ) }
__nextHasNoMarginBottom
/>
>
) }
);
}
/* Page rules tab */
if ( tab.name === 'page-rules' ) {
return (
{ __( 'Control on which pages this chatbot is displayed. Leave empty to show on all pages. Use patterns like /products/* or /contact.', 'ai-marketing-expert' ) }
{ pageRules.map( ( rule, index ) => (
updatePageRule( index, 'type', v ) }
__nextHasNoMarginBottom
/>
updatePageRule( index, 'pattern', v ) }
placeholder="/products/*"
__nextHasNoMarginBottom
/>
removePageRule( index ) }
style={ { color: '#d63638', whiteSpace: 'nowrap', alignSelf: 'center' } }
>
{ __( 'Remove', 'ai-marketing-expert' ) }
) ) }
{ __( '+ Add Rule', 'ai-marketing-expert' ) }
);
}
/* Advanced tab */
return (
setField( 'banned_words', v ) }
rows={ 3 }
/>
setField( 'max_history_messages', parseInt( v ) || 20 ) }
__nextHasNoMarginBottom
/>
);
} }
);
};
export default BotEditor;