'use client' import React, { useState, useRef, useEffect } from 'react' import { MessageCircle, X, Send, User, Bot, Heart } from 'lucide-react' import { useLanguage } from '@/components/providers/LanguageProvider' import { useAuth } from '@/components/providers/MockAuthProvider' type Message = { id: string text: string sender: 'user' | 'bot' timestamp: Date type?: 'general' | 'mental_health' } type ChatMode = 'general' | 'mental_health' export const ChatWidget: React.FC = () => { const [isOpen, setIsOpen] = useState(false) const [messages, setMessages] = useState([]) const [inputText, setInputText] = useState('') const [isTyping, setIsTyping] = useState(false) const [chatMode, setChatMode] = useState('general') const [showSurvey, setShowSurvey] = useState(false) const [surveyRating, setSurveyRating] = useState(0) const messagesEndRef = useRef(null) const { t, dir } = useLanguage() const { user, userProfile } = useAuth() useEffect(() => { messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' }) }, [messages]) const addMessage = (text: string, sender: 'user' | 'bot', type?: 'general' | 'mental_health') => { const newMessage: Message = { id: Date.now().toString(), text, sender, timestamp: new Date(), type, } setMessages(prev => [...prev, newMessage]) } const handleSendMessage = async () => { if (!inputText.trim()) return const userMessage = inputText.trim() setInputText('') addMessage(userMessage, 'user', chatMode) setIsTyping(true) try { // Create userContext if user is logged in const userContext = user ? { role: userProfile?.role || 'student', token: user.id, profile: userProfile ? { name: userProfile.name, email: userProfile.email, year: userProfile.year, faculty: userProfile.faculty, balance: userProfile.balance } : undefined } : undefined; const response = await fetch('/api/chat', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ message: userMessage, mode: chatMode, history: messages, userContext }), }) const data = await response.json() setIsTyping(false) addMessage(data.message || data.response, 'bot', chatMode) // Check for mental health escalation if (data.shouldEscalate) { setTimeout(() => { addMessage( `${t('mental_health_support')} - ${t('book_counselor')}: https://calendly.com/university-counseling`, 'bot', 'mental_health' ) }, 1000) } // Show survey after interaction if (Math.random() > 0.7) { setTimeout(() => { setShowSurvey(true) }, 2000) } } catch (error) { setIsTyping(false) addMessage('Sorry, I encountered an error. Please try again.', 'bot') console.error('Chat error:', error) } } const handleSurveySubmit = async () => { if (surveyRating > 0) { try { await fetch('/api/survey', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ rating: surveyRating, type: 'chat_satisfaction', sessionId: Date.now().toString(), }), }) } catch (error) { console.error('Survey submission error:', error) } } setShowSurvey(false) setSurveyRating(0) } const switchToMentalHealth = () => { setChatMode('mental_health') addMessage( 'I\'m here to provide support. How are you feeling today?', 'bot', 'mental_health' ) } const switchToGeneral = () => { setChatMode('general') addMessage( 'I can help you with general university questions. What would you like to know?', 'bot', 'general' ) } if (!isOpen) { return ( ) } return (
{/* Header */}
University Assistant
{/* Mode Toggle */}
{/* Messages */}
{messages.length === 0 && (

{t('ask_question')}

)} {messages.map((message) => (
{message.sender === 'user' ? ( ) : ( )} {message.timestamp.toLocaleTimeString()}

{message.text}

))} {isTyping && (
Typing...
)}
{/* Survey */} {showSurvey && (

{t('survey_rating')}

{[1, 2, 3, 4, 5].map((rating) => ( ))}
)} {/* Input */}
setInputText(e.target.value)} onKeyPress={(e) => e.key === 'Enter' && handleSendMessage()} placeholder={t('type_message')} className="flex-1 px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm" dir={dir} />
) }