"use client";
import dynamic from "next/dynamic";
import { useState, useEffect, useRef, useCallback } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { useAuth } from "@/context/AuthContext";
import { createStompClient } from "@/lib/chatSocket";
const API_BASE = "";
function isImageFilename(name) {
return /\.(jpe?g|png|gif|webp|bmp|svg)$/i.test(name || "");
}
function AttachmentPreview({ url, name, token }) {
const [blobUrl, setBlobUrl] = useState(null);
const isImage = isImageFilename(name);
useEffect(() => {
if (!url || !token) return;
let objectUrl;
fetch(url, { headers: { Authorization: `Bearer ${token}` } })
.then((r) => (r.ok ? r.blob() : null))
.then((blob) => {
if (blob) {
objectUrl = URL.createObjectURL(blob);
setBlobUrl(objectUrl);
}
})
.catch(() => {});
return () => { if (objectUrl) URL.revokeObjectURL(objectUrl); };
}, [url, token]);
if (isImage) {
return (
{blobUrl ? (
window.open(blobUrl, "_blank")}
/>
) : (
📎 Loading image…
)}
);
}
return (
);
}
function AiChatPage() {
const { user, token, loading: authLoading } = useAuth();
const router = useRouter();
const searchParams = useSearchParams();
const conversationIdParam = searchParams.get("id");
const [conversation, setConversation] = useState(null);
const [messages, setMessages] = useState([]);
const [input, setInput] = useState("");
const [sending, setSending] = useState(false);
const [loadingConv, setLoadingConv] = useState(true);
const [error, setError] = useState(null);
const [conversations, setConversations] = useState([]);
const [convsLoading, setConvsLoading] = useState(false);
const [selectedFile, setSelectedFile] = useState(null);
const messagesEndRef = useRef(null);
const messagesAreaRef = useRef(null);
const inputRef = useRef(null);
const stompRef = useRef(null);
const lastMessageIdRef = useRef(null);
const fileInputRef = useRef(null);
const lastScrolledIdRef = useRef(null);
useEffect(() => {
if (!authLoading && !user) {
router.push("/login?next=" + encodeURIComponent("/ai-chat" + (conversationIdParam ? `?id=${conversationIdParam}` : "")));
}
}, [authLoading, user, router, conversationIdParam]);
useEffect(() => {
if (messages.length === 0) return;
const lastMsg = messages[messages.length - 1];
if (lastMsg.id === lastScrolledIdRef.current) return;
lastScrolledIdRef.current = lastMsg.id;
const area = messagesAreaRef.current;
if (!area) return;
const nearBottom = area.scrollHeight - area.scrollTop - area.clientHeight < 150;
if (nearBottom) {
messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
}
}, [messages]);
const fetchMessages = useCallback(async (convId) => {
if (!token || !convId) return;
try {
const res = await fetch(`${API_BASE}/api/v1/chat/conversations/${convId}/messages`, {
headers: { Authorization: `Bearer ${token}` },
});
if (!res.ok) return;
const data = await res.json();
if (Array.isArray(data)) {
setMessages(data);
if (data.length > 0) lastMessageIdRef.current = data[data.length - 1].id;
}
} catch {
// silent
}
}, [token]);
const fetchConversation = useCallback(async (convId) => {
if (!token || !convId) return null;
try {
const res = await fetch(`${API_BASE}/api/v1/chat/conversations/${convId}`, {
headers: { Authorization: `Bearer ${token}` },
});
if (!res.ok) return null;
const data = await res.json();
setConversation(data);
return data;
} catch {
return null;
}
}, [token]);
const fetchConversations = useCallback(async () => {
if (!token) return;
setConvsLoading(true);
try {
const res = await fetch(`${API_BASE}/api/v1/chat/conversations`, {
headers: { Authorization: `Bearer ${token}` },
});
if (!res.ok) return;
const data = await res.json();
setConversations(Array.isArray(data) ? data : (data.content ?? []));
} catch {
// silent
} finally {
setConvsLoading(false);
}
}, [token]);
const connectStomp = useCallback((convId) => {
if (stompRef.current) {
stompRef.current.deactivate();
stompRef.current = null;
}
const client = createStompClient(token);
client.onConnect = () => {
client.subscribe(`/topic/chat/conversations/${convId}`, (frame) => {
try {
const msg = JSON.parse(frame.body);
setMessages((prev) => prev.some((m) => m.id === msg.id) ? prev : [...prev, msg]);
lastMessageIdRef.current = msg.id;
} catch { /* silent */ }
});
const convTopic = user?.role === "CUSTOMER"
? `/user/queue/chat/conversations`
: `/topic/chat/conversations`;
client.subscribe(convTopic, (frame) => {
try {
const conv = JSON.parse(frame.body);
if (conv.id === convId) setConversation(conv);
setConversations((prev) => prev.map((c) => c.id === conv.id ? conv : c));
} catch { /* silent */ }
});
};
stompRef.current = client;
client.activate();
}, [token, user?.role]);
useEffect(() => {
if (!token || authLoading) return;
async function init() {
setLoadingConv(true);
setError(null);
let convId = conversationIdParam ? Number(conversationIdParam) : null;
if (!convId) {
try {
const res = await fetch(`${API_BASE}/api/v1/chat/conversations`, {
headers: { Authorization: `Bearer ${token}` },
});
if (res.ok) {
const list = await res.json();
const openAi = Array.isArray(list)
? list.find((c) => c.status === "OPEN" && c.mode === "AUTOMATED")
: null;
if (openAi) convId = openAi.id;
}
} catch {
setError("Failed to load conversations.");
}
}
if (!convId) {
// Auto-create a new AI conversation
try {
const res = await fetch(`${API_BASE}/api/v1/chat/conversations`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
body: JSON.stringify({ message: "Hello! I'd like to chat with the AI assistant." }),
});
if (res.ok) {
const conv = await res.json();
convId = conv.id;
}
} catch {
// silent
}
}
if (!convId) {
await fetchConversations();
setLoadingConv(false);
return;
}
await Promise.all([
fetchConversation(convId),
fetchMessages(convId),
fetchConversations(),
]);
setLoadingConv(false);
connectStomp(convId);
router.replace(`/ai-chat?id=${convId}`, { scroll: false });
}
init();
return () => {
if (stompRef.current) { stompRef.current.deactivate(); stompRef.current = null; }
};
}, [token, authLoading, conversationIdParam, fetchConversation, fetchMessages, connectStomp, fetchConversations, router]);
async function handleSend(e) {
e?.preventDefault();
const text = input.trim();
if ((!text && !selectedFile) || sending || !conversation) return;
if (selectedFile) {
await handleSendAttachment(text);
} else {
await handleSendText(text);
}
}
async function handleSendText(text) {
setInput("");
setSending(true);
setError(null);
try {
const res = await fetch(`${API_BASE}/api/v1/chat/conversations/${conversation.id}/messages`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
body: JSON.stringify({ content: text }),
});
if (res.status === 401) {
router.push("/login?next=" + encodeURIComponent("/ai-chat"));
return;
}
if (!res.ok) {
const data = await res.json().catch(() => null);
setError(data?.message || "Failed to send message.");
setInput(text);
return;
}
const msg = await res.json();
setMessages((prev) => prev.some((m) => m.id === msg.id) ? prev : [...prev, msg]);
lastMessageIdRef.current = msg.id;
} catch {
setError("Network error. Please try again.");
setInput(text);
} finally {
setSending(false);
inputRef.current?.focus();
}
}
async function handleSendAttachment(optionalText) {
setSending(true);
setError(null);
const file = selectedFile;
setSelectedFile(null);
setInput("");
try {
const formData = new FormData();
formData.append("file", file);
if (optionalText) formData.append("content", optionalText);
const res = await fetch(
`${API_BASE}/api/v1/chat/conversations/${conversation.id}/attachments`,
{
method: "POST",
headers: { Authorization: `Bearer ${token}` },
body: formData,
}
);
if (res.status === 401) {
router.push("/login?next=" + encodeURIComponent("/ai-chat"));
return;
}
if (!res.ok) {
const data = await res.json().catch(() => null);
setError(data?.message || "Failed to send attachment.");
setSelectedFile(file);
setInput(optionalText);
return;
}
const msg = await res.json();
setMessages((prev) => prev.some((m) => m.id === msg.id) ? prev : [...prev, msg]);
lastMessageIdRef.current = msg.id;
} catch {
setError("Network error. Please try again.");
setSelectedFile(file);
setInput(optionalText);
} finally {
setSending(false);
inputRef.current?.focus();
}
}
function handleFileChange(e) {
const file = e.target.files?.[0];
if (file) setSelectedFile(file);
e.target.value = "";
}
function handleKeyDown(e) {
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
handleSend();
}
}
async function handleNewConversation() {
if (stompRef.current) { stompRef.current.deactivate(); stompRef.current = null; }
setError(null);
setLoadingConv(true);
try {
const res = await fetch(`${API_BASE}/api/v1/chat/conversations`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
body: JSON.stringify({ message: "Hello! I'd like to chat with the AI assistant." }),
});
if (!res.ok) {
const data = await res.json().catch(() => null);
setError(data?.message || "Failed to start a conversation.");
setLoadingConv(false);
return;
}
const conv = await res.json();
setConversation(conv);
await Promise.all([fetchMessages(conv.id), fetchConversations()]);
setLoadingConv(false);
connectStomp(conv.id);
router.replace(`/ai-chat?id=${conv.id}`, { scroll: false });
} catch {
setError("Network error. Please try again.");
setLoadingConv(false);
}
}
async function switchConversation(convId) {
if (stompRef.current) { stompRef.current.deactivate(); stompRef.current = null; }
setMessages([]);
setError(null);
setLoadingConv(true);
await fetchConversation(convId);
await fetchMessages(convId);
setLoadingConv(false);
connectStomp(convId);
router.replace(`/ai-chat?id=${convId}`, { scroll: false });
}
async function handleSwitchToHuman() {
if (!conversation) return;
try {
await fetch(`${API_BASE}/api/v1/chat/conversations/${conversation.id}/request-human`, {
method: "POST",
headers: { Authorization: `Bearer ${token}` },
});
router.push(`/chat?id=${conversation.id}`);
} catch {
setError("Could not connect to live support. Please try again.");
}
}
if (authLoading || loadingConv) {
return (
Loading...
);
}
if (!user) return null;
const isEscalated = conversation?.mode === "HUMAN";
const isClosed = conversation?.status === "CLOSED";
return (
AI Pet Assistant
Ask me anything about pet care, adoption advice, or your pets!
All Conversations
{convsLoading &&
Loading...
}
{!convsLoading && conversations.length === 0 && (
No conversations yet.
)}
{conversations.map((conv) => (
switchConversation(conv.id)}
>
{conv.subject || `Conversation #${conv.id}`}
{conv.status}
{conv.mode === "HUMAN" ? "👤 Live" : "🤖 AI"}
{conv.createdAt ? new Date(conv.createdAt).toLocaleDateString() : ""}
))}
+ New Conversation
{!conversation ? (
🐾
No active conversation
Start a new conversation with the AI assistant.
{error &&
{error}
}
Start a Conversation
router.push("/chat")}>
Live Support
) : (
🐾
Leon's Pet Assistant
Online
{!isEscalated && !isClosed && (
Chat with a Real Person
)}
router.push("/chat")}
title="Go to Live Support"
>
Live Support
{messages.length === 0 && (
🐾
Hello{user.fullName ? `, ${user.fullName.split(" ")[0]}` : ""}! I'm your pet care assistant.
Ask me about pet recommendations, care tips, supplies, or anything pet-related!
)}
{messages.map((msg) => {
const isOwn = msg.senderId === user.id;
return (
{!isOwn &&
🐾
}
{msg.content && msg.content.split("\n").map((line, i, arr) => (
{line}
{i < arr.length - 1 && }
))}
{msg.attachmentUrl && (
)}
{msg.timestamp ? new Date(msg.timestamp).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }) : ""}
{isOwn && (
{user.fullName ? user.fullName.charAt(0).toUpperCase() : "U"}
)}
);
})}
{error && (
{error}
setError(null)}>✕
)}
{isClosed ? (
This conversation has been closed.
Start New Conversation
) : (
)}
)}
);
}
const s = {
page: {
minHeight: "100vh",
background: "#fafaf8",
fontFamily: "inherit",
},
loading: {
textAlign: "center",
padding: "4rem",
color: "#888",
fontSize: "1rem",
},
hero: {
background: "linear-gradient(135deg, #333 0%, #555 100%)",
padding: "2.5rem 1.5rem 2rem",
textAlign: "center",
color: "white",
},
heroTitle: {
fontSize: "clamp(1.6rem, 4vw, 2.4rem)",
fontWeight: 800,
margin: 0,
letterSpacing: "-0.5px",
},
heroSubtitle: {
fontSize: "clamp(0.9rem, 2vw, 1.1rem)",
marginTop: "0.5rem",
opacity: 0.85,
},
titleDecoration: {
width: 60,
height: 4,
background: "rgba(255,255,255,0.4)",
borderRadius: 2,
margin: "1rem auto 0",
},
chatSection: {
maxWidth: 1060,
margin: "0 auto",
padding: "1.5rem 1rem 2rem",
},
sidebar: {
width: 230,
flexShrink: 0,
background: "white",
borderRadius: 16,
boxShadow: "0 4px 24px rgba(0,0,0,0.08)",
display: "flex",
flexDirection: "column",
overflow: "hidden",
maxHeight: "calc(100vh - 220px)",
minHeight: 300,
},
sidebarHeader: {
display: "flex",
alignItems: "center",
padding: "0.85rem 1rem",
borderBottom: "1px solid #f0f0f0",
flexShrink: 0,
},
sidebarTitle: { fontWeight: 700, fontSize: "0.88rem", color: "#333" },
sidebarEmpty: {
color: "#aaa",
fontSize: "0.82rem",
padding: "1rem",
textAlign: "center",
margin: 0,
},
convItem: {
display: "flex",
flexDirection: "column",
gap: "0.2rem",
padding: "0.65rem 1rem",
background: "white",
border: "none",
borderBottomWidth: 1,
borderBottomStyle: "solid",
borderBottomColor: "#f0f0f0",
textAlign: "left",
cursor: "pointer",
width: "100%",
},
convItemActive: { background: "#f8f8f8" },
convItemTop: {
display: "flex",
alignItems: "center",
justifyContent: "space-between",
gap: "0.4rem",
},
convItemBottom: {
display: "flex",
alignItems: "center",
justifyContent: "space-between",
},
convItemSubject: {
fontSize: "0.82rem",
fontWeight: 600,
color: "#222",
overflow: "hidden",
textOverflow: "ellipsis",
whiteSpace: "nowrap",
flex: 1,
},
convItemMode: { fontSize: "0.7rem", color: "#999" },
convItemDate: { fontSize: "0.68rem", color: "#bbb" },
convStatusBadge: {
fontSize: "0.62rem",
fontWeight: 700,
borderRadius: 20,
padding: "0.1rem 0.45rem",
flexShrink: 0,
textTransform: "uppercase",
letterSpacing: "0.04em",
},
convStatusOpen: { background: "#e6f9ee", color: "#1a7a3c" },
convStatusClosed: { background: "#f0f0f0", color: "#888" },
newConvSidebarBtn: {
margin: "0.65rem 1rem",
background: "#333",
color: "white",
border: "none",
borderRadius: 8,
padding: "0.5rem 0.75rem",
fontSize: "0.8rem",
fontWeight: 600,
cursor: "pointer",
flexShrink: 0,
},
chatCard: {
background: "white",
borderRadius: 16,
boxShadow: "0 4px 24px rgba(0,0,0,0.08)",
overflow: "hidden",
display: "flex",
flexDirection: "column",
height: "calc(100vh - 220px)",
minHeight: 450,
},
chatHeader: {
display: "flex",
alignItems: "center",
justifyContent: "space-between",
padding: "1rem 1.25rem",
borderBottom: "1px solid #f0f0f0",
background: "#fff",
flexShrink: 0,
},
chatHeaderLeft: {
display: "flex",
alignItems: "center",
gap: "0.75rem",
},
aiAvatar: {
width: 44,
height: 44,
borderRadius: "50%",
background: "linear-gradient(135deg, #444, #666)",
display: "flex",
alignItems: "center",
justifyContent: "center",
fontSize: "1.3rem",
flexShrink: 0,
},
chatHeaderTitle: {
fontWeight: 700,
fontSize: "1rem",
color: "#1a1a1a",
},
chatHeaderStatus: {
display: "flex",
alignItems: "center",
gap: "0.35rem",
fontSize: "0.8rem",
color: "#4CAF50",
marginTop: 2,
},
statusDot: {
display: "inline-block",
width: 8,
height: 8,
borderRadius: "50%",
background: "#4CAF50",
},
humanBtn: {
background: "white",
border: "2px solid #ff8c00",
color: "#ff8c00",
borderRadius: 8,
padding: "0.45rem 0.9rem",
fontSize: "0.82rem",
fontWeight: 600,
cursor: "pointer",
whiteSpace: "nowrap",
},
liveBtn: {
background: "white",
border: "2px solid #555",
color: "#555",
borderRadius: 8,
padding: "0.45rem 0.9rem",
fontSize: "0.82rem",
fontWeight: 600,
cursor: "pointer",
whiteSpace: "nowrap",
},
noConvCard: {
background: "white",
borderRadius: 16,
boxShadow: "0 4px 24px rgba(0,0,0,0.08)",
padding: "3rem 2rem",
textAlign: "center",
display: "flex",
flexDirection: "column",
alignItems: "center",
gap: "1rem",
},
noConvIcon: { fontSize: "3rem" },
noConvTitle: { fontSize: "1.4rem", fontWeight: 700, color: "#1a1a1a", margin: 0 },
noConvText: { color: "#666", fontSize: "0.95rem", maxWidth: 360 },
errorInline: {
background: "#fff0f0",
color: "#c0392b",
border: "1px solid #ffd0d0",
borderRadius: 8,
padding: "0.6rem 1rem",
fontSize: "0.875rem",
width: "100%",
maxWidth: 360,
},
startBtn: {
background: "#333",
color: "white",
border: "none",
borderRadius: 10,
padding: "0.7rem 2rem",
fontSize: "0.95rem",
fontWeight: 600,
cursor: "pointer",
},
backBtn: {
background: "none",
border: "1.5px solid #ff8c00",
color: "#ff8c00",
borderRadius: 10,
padding: "0.6rem 1.5rem",
fontSize: "0.9rem",
fontWeight: 600,
cursor: "pointer",
},
messagesArea: {
flex: 1,
overflowY: "auto",
padding: "1.25rem",
display: "flex",
flexDirection: "column",
gap: "0.75rem",
},
emptyState: {
flex: 1,
display: "flex",
flexDirection: "column",
alignItems: "center",
justifyContent: "center",
textAlign: "center",
padding: "2rem",
margin: "auto",
},
emptyIcon: { fontSize: "3rem", marginBottom: "1rem" },
emptyText: {
color: "#666",
fontSize: "0.95rem",
maxWidth: 400,
lineHeight: 1.6,
},
messageRow: {
display: "flex",
alignItems: "flex-end",
gap: "0.5rem",
},
messageRowUser: { flexDirection: "row-reverse" },
messageRowAgent: { flexDirection: "row" },
aiAvatarSmall: {
width: 30,
height: 30,
borderRadius: "50%",
background: "linear-gradient(135deg, #444, #666)",
display: "flex",
alignItems: "center",
justifyContent: "center",
fontSize: "0.85rem",
flexShrink: 0,
},
userAvatarSmall: {
width: 30,
height: 30,
borderRadius: "50%",
background: "#ff8c00",
color: "white",
display: "flex",
alignItems: "center",
justifyContent: "center",
fontSize: "0.8rem",
fontWeight: 700,
flexShrink: 0,
},
messageBubble: {
maxWidth: "72%",
padding: "0.65rem 0.9rem",
borderRadius: 14,
fontSize: "0.92rem",
lineHeight: 1.55,
wordBreak: "break-word",
},
bubbleUser: {
background: "#ff8c00",
color: "white",
borderBottomRightRadius: 4,
},
bubbleAgent: {
background: "#f4f4f4",
color: "#1a1a1a",
borderBottomLeftRadius: 4,
},
timestamp: {
fontSize: "0.7rem",
color: "#aaa",
marginTop: "0.3rem",
textAlign: "left",
},
timestampUser: { textAlign: "right", color: "rgba(255,255,255,0.7)" },
attachment: { marginTop: "0.4rem" },
attachmentLink: {
color: "inherit",
fontSize: "0.85rem",
opacity: 0.85,
},
errorBar: {
background: "#fff0f0",
borderTop: "1px solid #ffd0d0",
color: "#c0392b",
padding: "0.65rem 1.25rem",
fontSize: "0.875rem",
display: "flex",
alignItems: "center",
justifyContent: "space-between",
flexShrink: 0,
},
errorClose: {
background: "none",
border: "none",
color: "#c0392b",
cursor: "pointer",
fontSize: "0.9rem",
padding: "0 0.25rem",
},
closedBanner: {
background: "#f5f5f5",
borderTop: "1px solid #e0e0e0",
color: "#666",
padding: "0.85rem 1.25rem",
fontSize: "0.875rem",
display: "flex",
alignItems: "center",
justifyContent: "space-between",
flexShrink: 0,
},
newConvBtn: {
background: "#333",
color: "white",
border: "none",
borderRadius: 8,
padding: "0.4rem 1rem",
fontSize: "0.82rem",
fontWeight: 600,
cursor: "pointer",
},
inputArea: {
display: "flex",
flexDirection: "column",
gap: "0.4rem",
padding: "0.85rem 1.25rem",
borderTop: "1px solid #f0f0f0",
background: "#fff",
flexShrink: 0,
},
inputRow: {
display: "flex",
gap: "0.6rem",
alignItems: "flex-end",
},
attachBtn: {
background: "none",
border: "1.5px solid #e0e0e0",
borderRadius: 8,
padding: "0.5rem 0.6rem",
fontSize: "1rem",
cursor: "pointer",
flexShrink: 0,
color: "#666",
lineHeight: 1,
},
filePreview: {
display: "flex",
alignItems: "center",
gap: "0.5rem",
background: "#f8f8f8",
border: "1px solid #e8e8e8",
borderRadius: 8,
padding: "0.35rem 0.75rem",
},
filePreviewName: {
fontSize: "0.82rem",
color: "#555",
flex: 1,
overflow: "hidden",
textOverflow: "ellipsis",
whiteSpace: "nowrap",
},
filePreviewRemove: {
background: "none",
border: "none",
cursor: "pointer",
color: "#999",
fontSize: "0.8rem",
padding: "0 0.15rem",
flexShrink: 0,
},
textarea: {
flex: 1,
border: "1.5px solid #e0e0e0",
borderRadius: 10,
padding: "0.6rem 0.85rem",
fontSize: "0.92rem",
resize: "none",
outline: "none",
fontFamily: "inherit",
lineHeight: 1.5,
maxHeight: 120,
overflowY: "auto",
},
sendBtn: {
background: "#333",
color: "white",
border: "none",
borderRadius: 10,
padding: "0.6rem 1.2rem",
fontSize: "0.92rem",
fontWeight: 600,
cursor: "pointer",
flexShrink: 0,
},
sendBtnDisabled: {
background: "#aaa",
cursor: "not-allowed",
},
};
export default dynamic(() => Promise.resolve(AiChatPage), { ssr: false });