import { useState, useEffect } from 'react'; import { MessageSquare, X, Send } from 'lucide-react'; import { useStore } from '../store'; import { motion, AnimatePresence } from 'framer-motion'; export function HelpOverlay() { const [isOpen, setIsOpen] = useState(false); const [message, setMessage] = useState(''); const [history, setHistory] = useState([]); const [unreadCount, setUnreadCount] = useState(0); const { currentUser, deviceId } = useStore(); const fetchUnreadCount = async () => { const id = currentUser ? currentUser.id.split('_')[0] : deviceId; if (!id) return; try { const res = await fetch(`/api/support/unread/${id}`); if (res.ok) setUnreadCount((await res.json()).count); } catch {} }; const markAsRead = async () => { const id = currentUser ? currentUser.id.split('_')[0] : deviceId; if (!id) return; try { await fetch(`/api/support/read/${id}`, { method: 'PATCH' }); setUnreadCount(0); } catch {} }; useEffect(() => { if (isOpen) { if (currentUser || deviceId) { fetchHistory(); markAsRead(); } } else if (currentUser || deviceId) { fetchUnreadCount(); } // eslint-disable-next-line react-hooks/exhaustive-deps }, [isOpen, currentUser, deviceId]); useEffect(() => { if (!currentUser && !deviceId) return; import('../socket').then(({ socket }) => { const handler = () => { if (isOpen) { fetchHistory(); markAsRead(); } else { fetchUnreadCount(); } }; socket.on('support-ticket-updated', handler); return () => socket.off('support-ticket-updated', handler); }); // eslint-disable-next-line react-hooks/exhaustive-deps }, [isOpen, currentUser, deviceId]); const fetchHistory = async () => { try { const id = currentUser ? currentUser.id.split('_')[0] : deviceId; if (!id) return; const res = await fetch(`/api/support/history/${id}`); if (res.ok) { const data = await res.json(); setHistory(data); } } catch (err) { console.error(err); } }; const handleSubmit = async (e) => { e.preventDefault(); const senderId = currentUser ? currentUser.id : deviceId; if (!message.trim() || !senderId) return; try { const res = await fetch(`/api/support`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ senderId, message }) }); if (res.ok) { setMessage(''); fetchHistory(); } } catch (err) { console.error(err); } }; return ( <> {isOpen && (

Support

{history.length === 0 ? (
No previous tickets.
How can we help you today?
) : ( history.map(msg => (
{msg.message}
{msg.adminReply && (
Admin: {msg.adminReply}
)}
{new Date(msg.timestamp).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })} {msg.isResolved ? 'Resolved' : 'Pending'}
)) )}
setMessage(e.target.value)} style={{ flex: 1, padding: '10px 12px', borderRadius: '20px', border: '1px solid #333', background: '#111', color: 'white', outline: 'none' }} required />
)}
); }