diff --git a/components/dashboard/ChatDetail.tsx b/components/dashboard/ChatDetail.tsx index 25a9f94..4b45257 100644 --- a/components/dashboard/ChatDetail.tsx +++ b/components/dashboard/ChatDetail.tsx @@ -87,14 +87,33 @@ export default function ChatDetail({ chatId }: { chatId: string }) { const [loading, setLoading] = useState(true); const [message, setMessage] = useState(""); const [sending, setSending] = useState(false); + const [messages, setMessages] = useState([]); + const [chatData, setChatData] = useState(null); const messagesEndRef = useRef(null); const [previousMessageCount, setPreviousMessageCount] = useState(0); const audioRef = useRef(null); const markReadTimeoutRef = useRef(null); + const isPollingRef = useRef(false); const [selectedImage, setSelectedImage] = useState(null); const [selectedMessageIndex, setSelectedMessageIndex] = useState(null); const [selectedAttachmentIndex, setSelectedAttachmentIndex] = useState(null); + // Scroll to bottom utility functions + const scrollToBottom = () => { + messagesEndRef.current?.scrollIntoView({ behavior: "smooth" }); + }; + + const isNearBottom = () => { + if (!messagesEndRef.current) return true; + + const container = messagesEndRef.current.parentElement; + if (!container) return true; + + const { scrollTop, scrollHeight, clientHeight } = container; + // Consider "near bottom" if within 100px of the bottom + return scrollHeight - (scrollTop + clientHeight) < 100; + }; + // Initialize audio element useEffect(() => { // Create audio element for notification sound @@ -206,6 +225,7 @@ export default function ChatDetail({ chatId }: { chatId: string }) { const response = await clientFetch(`/chats/${chatId}`); setChatData(response); + setChat(response); // Set chat data to maintain compatibility setMessages(Array.isArray(response.messages) ? response.messages : []); // Scroll to bottom on initial load @@ -270,10 +290,13 @@ export default function ChatDetail({ chatId }: { chatId: string }) { const tempMessage = { _id: tempId, chatId, - sender: "vendor", - message: message.trim(), - timestamp: new Date().toISOString(), - isTemp: true, + sender: "vendor" as const, + content: message.trim(), + attachments: [], + read: false, + createdAt: new Date().toISOString(), + buyerId: chatData?.buyerId || "", + vendorId: chatData?.vendorId || "", }; setMessages(prev => [...prev, tempMessage]); @@ -303,6 +326,12 @@ export default function ChatDetail({ chatId }: { chatId: string }) { } }; + // Handle form submit for sending messages + const handleSendMessage = (e: React.FormEvent) => { + e.preventDefault(); + sendMessage(); + }; + const handleBackClick = () => { router.push("/dashboard/chats"); };