import { useCallback, useEffect, useState } from 'react'; import { useAuth } from '../context/AuthContext'; import { acceptConnection, getMyConnections, getPublicProfiles, rejectConnection } from '../lib/api'; import type { Connection, PublicProfile } from '../lib/types'; import { Avatar, Empty, Spinner } from '../components/ui'; import { useToast } from '../context/ToastContext'; export function Connections() { const { profile } = useAuth(); const [tab, setTab] = useState<'mine' | 'req'>('mine'); const [conns, setConns] = useState([]); const [people, setPeople] = useState>(new Map()); const [loading, setLoading] = useState(true); const { toast } = useToast(); const load = useCallback(async () => { try { const [c, p] = await Promise.all([getMyConnections(), getPublicProfiles()]); setConns(c); setPeople(new Map(p.map((x) => [x.id, x]))); } catch { /* non-fatal */ } finally { setLoading(false); } }, []); useEffect(() => { void load(); }, [load]); if (!profile) return null; const me = profile.id; const nameOf = (id: string) => people.get(id)?.full_name ?? '…'; const companyOf = (id: string) => people.get(id)?.company ?? ''; const accepted = conns.filter((c) => c.status === 'accepted'); const incoming = conns.filter((c) => c.status === 'pending' && c.to_id === me); const outgoing = conns.filter((c) => c.status === 'pending' && c.from_id === me); async function resolve(id: string, accept: boolean) { try { if (accept) await acceptConnection(id); else await rejectConnection(id); toast(accept ? 'Connected! +5 pts 🤝' : 'Request declined', accept ? 'ok' : ''); await load(); } catch (e) { toast(e instanceof Error ? e.message : 'Could not update request', 'err'); } } if (loading) { return (
); } return (
Connections
{tab === 'mine' && (accepted.length === 0 ? ( ) : ( accepted.map((c) => { const otherId = c.from_id === me ? c.to_id : c.from_id; return (
{nameOf(otherId)}
{companyOf(otherId)}
Connected
); }) ))} {tab === 'req' && (
{incoming.length === 0 && outgoing.length === 0 && ( )} {incoming.length > 0 && (
Incoming
{incoming.map((c) => (
{nameOf(c.from_id)}
{companyOf(c.from_id)}
))}
)} {outgoing.length > 0 && (
Sent
{outgoing.map((c) => (
{nameOf(c.to_id)}
{companyOf(c.to_id)}
Pending
))}
)}
)}
); }