import { useState, useEffect } from 'react'; import { X, Send, MessageCircle } from 'lucide-react'; import { useLocation } from 'wouter'; import { haptics } from '@/lib/haptics'; import { supabase } from '@/lib/supabase'; import { useAuth } from '@/lib/auth'; interface Message { id: string; sender: string; text: string; timestamp: string; unread?: boolean; created_at?: string; } export default function MobileMessaging() { const [, navigate] = useLocation(); const { user } = useAuth(); const [messages, setMessages] = useState([]); const [loading, setLoading] = useState(true); const [newMessage, setNewMessage] = useState(''); const fetchMessages = async () => { try { if (!user) { setMessages([ { id: 'demo', sender: 'AeThex Team', text: 'Sign in to view your messages', timestamp: 'now', unread: false } ]); setLoading(false); return; } // Query for messages where user is recipient or sender const { data, error } = await supabase .from('messages') .select('*') .or(`sender_id.eq.${user.id},recipient_id.eq.${user.id}`) .order('created_at', { ascending: false }) .limit(50); if (error) throw error; if (data && data.length > 0) { const mapped = data.map(m => ({ id: m.id.toString(), sender: m.sender_name || 'Unknown', text: m.content || '', timestamp: formatTime(m.created_at), unread: m.recipient_id === user.id && !m.read, created_at: m.created_at })); setMessages(mapped); } else { setMessages([]); } } catch (error) { console.error('Error fetching messages:', error); } finally { setLoading(false); } }; const formatTime = (timestamp: string) => { const now = new Date(); const created = new Date(timestamp); const diffMs = now.getTime() - created.getTime(); const diffMins = Math.floor(diffMs / 60000); if (diffMins < 1) return 'just now'; if (diffMins < 60) return `${diffMins}m ago`; const diffHours = Math.floor(diffMins / 60); if (diffHours < 24) return `${diffHours}h ago`; const diffDays = Math.floor(diffHours / 24); return `${diffDays}d ago`; }; useEffect(() => { fetchMessages(); }, [user]); const unreadCount = messages.filter(m => m.unread).length; const handleSend = () => { if (newMessage.trim()) { haptics.light(); setNewMessage(''); } }; return (
{/* Header */}

MESSAGES

{unreadCount > 0 && (

{unreadCount} unread

)}
{/* Messages List */}
{messages.map((message) => ( ))}
{/* Input */}
setNewMessage(e.target.value)} placeholder="Type a message..." className="flex-1 bg-gray-900 border border-gray-700 rounded-lg px-4 py-3 text-white placeholder-gray-500 focus:outline-none focus:border-cyan-500" onKeyPress={(e) => e.key === 'Enter' && handleSend()} />
); }