import React, { useState, useEffect, useRef } from 'react'; import { apiClient } from 'app'; import { MessageResponse } from 'types'; import { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; import { ScrollArea } from '@/components/ui/scroll-area'; import { MessageCircle, Send, X } from 'lucide-react'; interface Props { tableId: string; userId: string; isOpen: boolean; onToggle: () => void; } export const ChatPanel: React.FC = ({ tableId, userId, isOpen, onToggle }) => { const [messages, setMessages] = useState([]); const [newMessage, setNewMessage] = useState(''); const [sending, setSending] = useState(false); const scrollRef = useRef(null); useEffect(() => { loadMessages(); const interval = setInterval(loadMessages, 2000); // Poll every 2s return () => clearInterval(interval); }, [tableId]); useEffect(() => { if (scrollRef.current) { scrollRef.current.scrollTop = scrollRef.current.scrollHeight; } }, [messages]); const loadMessages = async () => { try { const response = await apiClient.get_messages({ table_id: tableId }); const data = await response.json(); setMessages(data.messages || []); } catch (error) { console.error('Failed to load messages:', error); } }; const sendMessage = async () => { if (!newMessage.trim() || sending) return; setSending(true); try { await apiClient.send_message({ table_id: tableId, message: newMessage.trim() }); setNewMessage(''); await loadMessages(); } catch (error) { console.error('Failed to send message:', error); } finally { setSending(false); } }; const handleKeyPress = (e: React.KeyboardEvent) => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); sendMessage(); } }; return ( <> {/* Toggle Button */} {!isOpen && ( )} {/* Chat Sidebar */} {isOpen && (
{/* Header */}

Table Chat

{/* Messages */}
{messages.map((msg) => (
{!msg.is_system && (
{msg.user_id === userId ? 'You' : msg.user_email?.split('@')[0] || 'Player'} {msg.private_to && (Private)}
)}
{msg.message}
{new Date(msg.created_at).toLocaleTimeString()}
))}
{/* Input */}
setNewMessage(e.target.value)} onKeyPress={handleKeyPress} placeholder="Type a message..." disabled={sending} className="flex-1 bg-slate-900 border-slate-700 text-white" />
)} ); };