'use client';
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useEffect, useState, useRef } from 'react';
const COLORS = ['#3b82f6', '#ef4444', '#10b981', '#f59e0b', '#8b5cf6', '#ec4899'];
export function PresenceIndicator({ documentId, currentUserId }) {
    const [users, setUsers] = useState([]);
    const eventSourceRef = useRef(null);
    const heartbeatRef = useRef(undefined);
    useEffect(() => {
        if (!documentId)
            return;
        const es = new EventSource(`/api/cms/presence/${documentId}`);
        eventSourceRef.current = es;
        es.addEventListener('presence', (event) => {
            try {
                const data = JSON.parse(event.data);
                setUsers(data.filter((u) => u.userId !== currentUserId));
            }
            catch { }
        });
        es.onerror = () => {
            es.close();
        };
        heartbeatRef.current = setInterval(() => {
            fetch(`/api/cms/presence/${documentId}/heartbeat`, {
                method: 'POST',
                credentials: 'include',
            }).catch(() => { });
        }, 30_000);
        return () => {
            es.close();
            if (heartbeatRef.current)
                clearInterval(heartbeatRef.current);
        };
    }, [documentId, currentUserId]);
    if (users.length === 0)
        return null;
    return (_jsxs("div", { className: "flex items-center gap-1", title: `${users.length} other editor(s) active`, children: [users.slice(0, 5).map((user, i) => (_jsx("div", { className: "flex h-7 w-7 items-center justify-center rounded-full text-xs font-medium text-white ring-2 ring-white", style: { backgroundColor: COLORS[i % COLORS.length] }, title: user.name, children: user.name.charAt(0).toUpperCase() }, user.userId))), users.length > 5 && (_jsxs("div", { className: "bg-muted text-muted-foreground flex h-7 w-7 items-center justify-center rounded-full text-xs font-medium ring-2 ring-white", children: ["+", users.length - 5] }))] }));
}
//# sourceMappingURL=PresenceIndicator.js.map