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';
const INITIAL_MESSAGES: ChatMessage[] = [
{
id: '1',
role: 'assistant',
content: "👋 Hi there! I'm your **RIT AI Assistant**, powered by Google Gemini. 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('http://localhost:8081/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 http://localhost:8081.`;
}
}
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 (