import { useState, useRef, useEffect } from 'react'; import { motion, AnimatePresence } from 'framer-motion'; import { Bot, Send, Sparkles, RefreshCw, Mic, X, ChevronRight } from 'lucide-react'; import { AI_SUGGESTED_PROMPTS } from '@/constants'; import type { ChatMessage } from '@/types'; import { getChatbotUrl } from '@/lib/utils'; const INITIAL_MESSAGES: ChatMessage[] = [ { id: '1', role: 'assistant', content: "👋 Hi there! I'm your **RIT Chatbot**. I have comprehensive knowledge about Rajalakshmi Institute of Technology — from admission procedures to campus facilities.\n\nHow can I help you today?", timestamp: new Date().toISOString(), }, ]; function formatContent(text: string) { return text .replace(/\*\*(.*?)\*\*/g, '$1') .replace(/\n/g, '
'); } export default function AIAssistant() { const [messages, setMessages] = useState(INITIAL_MESSAGES); const [input, setInput] = useState(''); const [isTyping, setIsTyping] = useState(false); const messagesEndRef = useRef(null); const inputRef = useRef(null); useEffect(() => { messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' }); }, [messages, isTyping]); const sendMessage = async (text: string) => { if (!text.trim()) return; const userMsg: ChatMessage = { id: Date.now().toString(), role: 'user', content: text, timestamp: new Date().toISOString(), }; setMessages((prev) => [...prev, userMsg]); setInput(''); setIsTyping(true); // Call the Go chatbot microservice let responseText = ''; try { const res = await fetch(getChatbotUrl('/api/chat'), { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ message: text }), }); if (res.ok) { const data = await res.json(); responseText = data.answer; } else { throw new Error('API server returned error status'); } } catch (error) { console.warn('Could not connect to Go chatbot service, using local mock responses:', error); const responses: Record = { hostel: "**RIT Hostel Facilities:**\n\n• Separate hostels for boys and girls\n• Wi-Fi connectivity in all rooms\n• 24/7 security and CCTV\n• Hygienic canteen with vegetarian & non-vegetarian options\n• Common rooms with TV and recreation\n• In-house medical facility\n\nFor hostel admission, contact the hostel office.", bus: "**RIT Bus Routes:**\n\nRIT operates **29 bus routes** covering major areas of Chennai. For queries, contact Mr. Venkatesan at +91 63807 51700 or visit http://www.rittransport.com/.", library: "**RIT Library Information:**\n\n• **Timings:** Mon-Fri 8:00 AM – 5:00 PM, Saturday 10:00 AM – 2:00 PM\n• **Collection:** Over 18,328 volumes of textbooks and reference books\n• **Digital Access:** Computerized OPAC, 25 computer systems in Digital Library, and Wi-Fi enabled online access.", }; const lower = text.toLowerCase(); if (lower.includes('hostel')) { responseText = responses.hostel; } else if (lower.includes('bus') || lower.includes('route')) { responseText = responses.bus; } else if (lower.includes('library')) { responseText = responses.library; } else { responseText = `Thank you for your question about **"${text}"**!\n\nI couldn't reach the chatbot API server. Please make sure the Go service is running on ${getChatbotUrl()}.`; } } setIsTyping(false); const aiMsg: ChatMessage = { id: (Date.now() + 1).toString(), role: 'assistant', content: responseText, timestamp: new Date().toISOString(), }; setMessages((prev) => [...prev, aiMsg]); }; const handleKeyDown = (e: React.KeyboardEvent) => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); sendMessage(input); } }; const clearChat = () => { setMessages(INITIAL_MESSAGES); }; return (
{/* Header */}

RIT Chatbot

Campus Knowledge Enabled
{/* Features strip */} {[ { icon: Sparkles, label: 'Gemini AI' }, { icon: Bot, label: 'RAG Enabled' }, { icon: ChevronRight, label: 'Campus Knowledge' }, ].map((item, i) => (
{item.label}
))}
{/* Messages */}
{messages.map((msg) => ( {msg.role === 'assistant' && (
)}
))} {/* Typing */} {isTyping && (
{[0, 1, 2].map((i) => ( ))}
)}
{/* Suggested Prompts */}
{AI_SUGGESTED_PROMPTS.slice(0, 4).map((prompt, i) => ( sendMessage(prompt)} className="px-3.5 py-2 rounded-xl border border-[#E5E7EB] text-xs text-[#475569] bg-white transition-all hover:border-[#F97316] hover:text-[#F97316]" style={{ fontFamily: 'Inter, sans-serif' }} > {prompt} ))}
{/* Input */}
setInput(e.target.value)} onKeyDown={handleKeyDown} placeholder="Ask anything about RIT..." className="flex-1 text-sm text-[#1E293B] placeholder-[#94A3B8] focus:outline-none bg-transparent" style={{ fontFamily: 'Inter, sans-serif' }} /> {input && ( setInput('')} className="w-8 h-8 rounded-xl flex items-center justify-center text-[#94A3B8] hover:bg-gray-100 transition-all" > )} sendMessage(input)} disabled={!input.trim()} className="w-10 h-10 rounded-xl flex items-center justify-center text-white transition-all disabled:opacity-50" style={{ background: 'linear-gradient(135deg, #F97316, #FB923C)' }} >

⚠️ Chatbot responses may not always be accurate. Please cross-reference critical academic or administrative details with official sources.

); }