"use client"; import React, { useState, useEffect, useRef } from "react"; import { Send, Loader2 } from "lucide-react"; interface Message { id: string; text: string; sender: "user" | "bot"; timestamp: Date; } interface StoredMessage { id: string; text: string; sender: "user" | "bot"; timestamp: string; } export default function BentoChat() { const [messages, setMessages] = useState([]); const [inputValue, setInputValue] = useState(""); const [isLoading, setIsLoading] = useState(false); const [conversationId, setConversationId] = useState("default"); const containerRef = useRef(null); useEffect(() => { try { const storedId = localStorage.getItem("chatSessionId"); if (storedId) setConversationId(storedId); else { const newId = crypto.randomUUID(); localStorage.setItem("chatSessionId", newId); setConversationId(newId); } const storedMsgs = localStorage.getItem("chatMessages"); if (storedMsgs) { setMessages(JSON.parse(storedMsgs).map((m: StoredMessage) => ({ ...m, timestamp: new Date(m.timestamp) }))); } else { setMessages([{ id: "welcome", text: "Hi! Ask me anything about Dennis! 🚀", sender: "bot", timestamp: new Date() }]); } } catch {} }, []); useEffect(() => { if (messages.length > 0) { localStorage.setItem("chatMessages", JSON.stringify(messages)); } if (containerRef.current) { containerRef.current.scrollTop = containerRef.current.scrollHeight; } }, [messages]); const handleSend = async () => { if (!inputValue.trim() || isLoading) return; const userMsg: Message = { id: Date.now().toString(), text: inputValue.trim(), sender: "user", timestamp: new Date() }; setMessages(prev => [...prev, userMsg]); setInputValue(""); setIsLoading(true); try { const res = await fetch("/api/n8n/chat", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ message: userMsg.text, conversationId, history: messages.slice(-5).map(m => ({ role: m.sender === "user" ? "user" : "assistant", content: m.text })) }), }); const data = await res.json(); setMessages(prev => [...prev, { id: (Date.now() + 1).toString(), text: data.reply || "Error", sender: "bot", timestamp: new Date() }]); } catch { setMessages(prev => [...prev, { id: (Date.now() + 1).toString(), text: "Connection error.", sender: "bot", timestamp: new Date() }]); } finally { setIsLoading(true); setTimeout(() => setIsLoading(false), 500); // Small delay for feel } }; return (
{messages.map((m) => (
{m.text}
))} {isLoading && (
)}
setInputValue(e.target.value)} onKeyDown={(e) => e.key === "Enter" && handleSend()} placeholder="Ask me..." className="w-full bg-white dark:bg-stone-800 border border-stone-200 dark:border-stone-700 rounded-2xl py-3 pl-4 pr-12 text-sm focus:outline-none focus:ring-2 focus:ring-liquid-purple/30 transition-all shadow-inner dark:text-white" />
); }