/**
* Conversation View - message thread with admin reply (human takeover).
*/
import { useState, useEffect, useCallback, useRef } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import { Button, TextareaControl, 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';
import { renderMarkdown } from '../../../../utils/renderMessage';
import sanitizeHtml from '../../../../utils/sanitizeHtml';
const SENDER_COLORS = {
visitor: '#e3f2fd',
ai: '#f3e5f5',
bot: '#f3e5f5',
agent: '#e8f5e9',
system: '#fff3e0',
};
const SENDER_LABELS = {
visitor: 'Visitor',
ai: 'AI Bot',
bot: 'AI Bot',
agent: 'Agent',
system: 'System',
};
const ConversationView = ( { id, onBack } ) => {
const { get, post, loading, error, clearError } = useApi();
const [ conversation, setConversation ] = useState( null );
const [ messages, setMessages ] = useState( [] );
const [ reply, setReply ] = useState( '' );
const [ sending, setSending ] = useState( false );
const [ takingOver, setTakingOver ] = useState( false );
const messagesEndRef = useRef( null );
const threadRef = useRef( null );
// Only auto-scroll when the admin is already near the bottom, so reading
// earlier messages is not interrupted by the 5s polling refresh.
const isNearBottomRef = useRef( true );
const prevCountRef = useRef( 0 );
const fetchConversation = useCallback( async () => {
try {
const res = await get( `/chatbot/conversations/${ id }` );
setConversation( res.conversation || res );
setMessages( res.messages || [] );
} catch ( e ) {
// silent
}
}, [ get, id ] );
useEffect( () => {
fetchConversation();
}, [ fetchConversation ] );
/* Auto-refresh messages every 5 seconds for live chat experience */
const fetchRef = useRef( fetchConversation );
fetchRef.current = fetchConversation;
useEffect( () => {
const interval = setInterval( () => {
fetchRef.current();
}, 5000 );
return () => clearInterval( interval );
}, [] );
const handleThreadScroll = useCallback( () => {
const el = threadRef.current;
if ( ! el ) return;
const distanceFromBottom =
el.scrollHeight - el.scrollTop - el.clientHeight;
isNearBottomRef.current = distanceFromBottom < 80;
}, [] );
useEffect( () => {
const grew = messages.length > prevCountRef.current;
const isFirstLoad = prevCountRef.current === 0;
prevCountRef.current = messages.length;
// Scroll on first load, or on new messages only while near the bottom.
if ( isFirstLoad || ( grew && isNearBottomRef.current ) ) {
messagesEndRef.current?.scrollIntoView( {
behavior: isFirstLoad ? 'auto' : 'smooth',
} );
}
}, [ messages ] );
const handleTakeover = async () => {
if ( takingOver ) return;
setTakingOver( true );
try {
await post( `/chatbot/conversations/${ id }/takeover` );
toast( __( 'You have taken over this conversation.', 'ai-marketing-expert' ) );
fetchConversation();
} catch ( e ) {
toast( e.message, 'error' );
} finally {
setTakingOver( false );
}
};
const handleClose = async () => {
try {
await post( `/chatbot/conversations/${ id }/close` );
toast( __( 'Conversation closed.', 'ai-marketing-expert' ) );
fetchConversation();
} catch ( e ) {
toast( e.message, 'error' );
}
};
const handleSendReply = async () => {
if ( ! reply.trim() ) return;
setSending( true );
try {
await post( `/chatbot/conversations/${ id }/message`, { content: reply } );
setReply( '' );
fetchConversation();
} catch ( e ) {
toast( e.message, 'error' );
} finally {
setSending( false );
}
};
const handleExport = async () => {
try {
const res = await get( `/chatbot/conversations/${ id }/export` );
const blob = new Blob( [ res.csv || '' ], { type: 'text/csv' } );
const url = URL.createObjectURL( blob );
const a = document.createElement( 'a' );
a.href = url;
a.download = `conversation-${ id }.csv`;
a.click();
URL.revokeObjectURL( url );
} catch ( e ) {
toast( e.message, 'error' );
}
};
if ( loading && ! conversation ) {
return
{ __( 'No messages in this conversation.', 'ai-marketing-expert' ) }
) : ( messages.map( ( msg ) => (