Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x | 'use client';
/**
* ChatbotWindow - Main chat window component
*/
import React, { useState, useRef, useEffect, useCallback } from 'react';
import { clientLogger } from '@/lib/logging/clientLogger';
import ChatMessage from './ChatMessage';
import ChatInput from './ChatInput';
import QuickActions from './QuickActions';
import { ChatbotMessage, ChatbotQuickAction, SupportArticle } from '@/types/support';
import { CHATBOT } from '@/constants/support';
import { Icon } from '@/components/ui/icons';
export interface ChatbotWindowProps {
/** Close handler */
onClose: () => void;
}
export default function ChatbotWindow({ onClose }: ChatbotWindowProps) {
const [messages, setMessages] = useState<ChatbotMessage[]>([]);
const [isLoading, setIsLoading] = useState(false);
const [showQuickActions, setShowQuickActions] = useState(true);
const messagesEndRef = useRef<HTMLDivElement>(null);
// Scroll to bottom when messages change
const scrollToBottom = useCallback(() => {
messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
}, []);
useEffect(() => {
scrollToBottom();
}, [messages, scrollToBottom]);
// Load welcome message on mount
useEffect(() => {
const loadWelcome = async () => {
try {
const response = await fetch('/api/support/chatbot', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ welcome: true })});
const data = await response.json();
if (data.success) {
const welcomeMessage: ChatbotMessage = {
id: 'welcome',
type: 'bot',
content: data.data.message,
timestamp: new Date(),
quickActions: data.data.quickActions};
setMessages([welcomeMessage]);
}
} catch (error) {
clientLogger.error('Failed to load welcome message', error instanceof Error ? error : new Error(String(error)));
// Use fallback welcome message
setMessages([
{
id: 'welcome',
type: 'bot',
content: CHATBOT.welcomeMessage,
timestamp: new Date()},
]);
}
};
loadWelcome();
}, []);
const handleSendMessage = async (content: string) => {
// Add user message
const userMessage: ChatbotMessage = {
id: `user-${Date.now()}`,
type: 'user',
content,
timestamp: new Date()};
setMessages((prev) => [...prev, userMessage]);
setShowQuickActions(false);
setIsLoading(true);
try {
const response = await fetch('/api/support/chatbot', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ message: content })});
const data = await response.json();
if (data.success) {
const botMessage: ChatbotMessage = {
id: `bot-${Date.now()}`,
type: 'bot',
content: data.data.message,
timestamp: new Date(),
suggestedArticles: data.data.suggestedArticles,
quickActions: data.data.quickActions};
setMessages((prev) => [...prev, botMessage]);
} else {
throw new Error(data.error || 'Failed to get response');
}
} catch (error) {
clientLogger.error('Chatbot error', error instanceof Error ? error : new Error(String(error)), { userMessage: content });
const errorMessage: ChatbotMessage = {
id: `error-${Date.now()}`,
type: 'bot',
content: 'Sorry, I encountered an error. Please try again or create a support ticket.',
timestamp: new Date(),
quickActions: [{ label: 'Create Ticket', action: 'create_ticket' }]};
setMessages((prev) => [...prev, errorMessage]);
} finally {
setIsLoading(false);
}
};
const handleQuickAction = (action: ChatbotQuickAction) => {
switch (action.action) {
case 'create_ticket':
window.location.href = '/support/tickets/new';
break;
case 'track_order':
window.location.href = '/account/orders';
break;
case 'view_faq':
window.location.href = '/support/articles';
break;
case 'contact_agent':
window.location.href = '/support/tickets/new';
break;
default:
// Send as message if unknown action
handleSendMessage(action.label);
}
};
const handleArticleClick = (article: SupportArticle) => {
window.location.href = `/support/articles/${article.slug}`;
};
return (
<div
className="
absolute bottom-16 right-0
w-[350px] sm:w-[400px] h-[500px]
bg-white rounded-lg shadow-2xl
flex flex-col
border border-gray-200
overflow-hidden
"
>
{/* Header */}
<div className="bg-blue-600 text-white px-4 py-3 flex items-center justify-between">
<div className="flex items-center gap-2">
<div className="w-2 h-2 bg-green-400 rounded-full" />
<span className="font-medium">Support Assistant</span>
</div>
<button
type="button"
onClick={onClose}
className="p-1 hover:bg-blue-700 rounded transition-colors"
aria-label="Close chat"
>
<Icon name="close" size={20} />
</button>
</div>
{/* Messages */}
<div className="flex-1 overflow-y-auto p-4 space-y-4 bg-gray-50">
{messages.map((message) => (
<ChatMessage
key={message.id}
message={message}
onQuickAction={handleQuickAction}
onArticleClick={handleArticleClick}
/>
))}
{isLoading && (
<div className="flex items-center gap-2 text-gray-500">
<div className="flex space-x-1">
<div className="w-2 h-2 bg-gray-400 rounded-full animate-bounce" />
<div
className="w-2 h-2 bg-gray-400 rounded-full animate-bounce"
style={{ animationDelay: '0.1s' }}
/>
<div
className="w-2 h-2 bg-gray-400 rounded-full animate-bounce"
style={{ animationDelay: '0.2s' }}
/>
</div>
<span className="text-sm">Typing...</span>
</div>
)}
<div ref={messagesEndRef} />
</div>
{/* Quick Actions (shown initially) */}
{showQuickActions && messages.length > 0 && messages[0].quickActions && (
<QuickActions
actions={messages[0].quickActions}
onAction={handleQuickAction}
/>
)}
{/* Input */}
<ChatInput onSend={handleSendMessage} disabled={isLoading} />
</div>
);
}
|