"use client"; import dynamic from "next/dynamic"; import { useState, useEffect, useRef, useCallback } from "react"; import { useRouter } from "next/navigation"; import { useAuth } from "@/context/AuthContext"; const API_BASE = ""; function AiChatPage() { const { user, token, loading: authLoading } = useAuth(); const router = useRouter(); const [messages, setMessages] = useState([]); const [input, setInput] = useState(""); const [sending, setSending] = useState(false); const [error, setError] = useState(null); const [switchingToHuman, setSwitchingToHuman] = useState(false); const [humanRequested, setHumanRequested] = useState(false); const messagesEndRef = useRef(null); const inputRef = useRef(null); useEffect(() => { if (!authLoading && !user) { router.push("/login?next=" + encodeURIComponent("/ai-chat")); } }, [authLoading, user, router]); useEffect(() => { messagesEndRef.current?.scrollIntoView({ behavior: "smooth" }); }, [messages]); const buildHistory = useCallback(() => { return messages.map((m) => ({ role: m.role, content: m.content, })); }, [messages]); async function handleSend(e) { e?.preventDefault(); const text = input.trim(); if (!text || sending) return; setInput(""); setError(null); setSending(true); const userMsg = { role: "user", content: text, id: Date.now() }; setMessages((prev) => [...prev, userMsg]); try { const res = await fetch(`${API_BASE}/api/v1/ai-chat/message`, { method: "POST", headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}`, }, body: JSON.stringify({ message: text, history: buildHistory(), }), }); if (res.status === 401 || res.status === 403) { router.push("/login?next=" + encodeURIComponent("/ai-chat")); return; } const data = await res.json(); if (!res.ok || !data.success) { setError(data.error || "Failed to get a response. Please try again."); return; } const aiMsg = { role: "assistant", content: data.message, id: Date.now() + 1 }; setMessages((prev) => [...prev, aiMsg]); } catch { setError("Network error. Please check your connection and try again."); } finally { setSending(false); inputRef.current?.focus(); } } async function handleHumanChat() { if (switchingToHuman || !token) return; setSwitchingToHuman(true); setError(null); 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: "Hi, I'd like to speak with a real support agent.", }), }); if (res.status === 401) { router.push("/login?next=" + encodeURIComponent("/ai-chat")); return; } const data = await res.json().catch(() => null); if (!res.ok) { setError(data?.message || "Could not connect to live support. Please try again."); return; } const conv = data; //Flag conversation staff, also should notify them await fetch(`${API_BASE}/api/v1/chat/conversations/${conv.id}/request-human`, { method: "POST", headers: { Authorization: `Bearer ${token}` }, }); setHumanRequested(true); router.push(`/chat?id=${conv.id}`); } catch { setError("Network error. Could not connect to live support."); } finally { setSwitchingToHuman(false); } } function handleKeyDown(e) { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); handleSend(); } } if (authLoading) { return (

Loading...

); } if (!user) return null; return (

AI Pet Assistant

Ask me anything about pet care, adoption advice, or your pets!

🐾
Leon's Pet Assistant
Online
{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) => (
{msg.role === "assistant" && (
🐾
)}
{msg.content.split("\n").map((line, i) => ( {line} {i < msg.content.split("\n").length - 1 &&
}
))}
{msg.role === "user" && (
{user.fullName ? user.fullName.charAt(0).toUpperCase() : "U"}
)}
))} {sending && (
🐾
)}
{error && (
{error}
)} {humanRequested && (
Connected to live support! Redirecting to chat...
)}