import React, { createContext, useContext, useMemo } from 'react';
import usePresence from '../hooks/usePresence.js';
import { api } from '../../../../convex/_generated/api';

const PresenceContext = createContext({
    onlineUsers: new Set(),
    resolveStatus: (storedStatus, userId) => storedStatus || 'offline',
});

export const useOnlineUsers = () => useContext(PresenceContext);

/**
 * Status resolution logic:
 * - If user is NOT connected (no heartbeat) → "offline"
 * - If user IS connected and chose "invisible" → "offline"
 * - If user IS connected → show their chosen status (online/idle/dnd)
 */
function resolveStatusFn(onlineUsers, storedStatus, userId) {
    if (!onlineUsers.has(userId)) return 'offline';
    if (storedStatus === 'invisible') return 'offline';
    return storedStatus || 'online';
}

export const PresenceProvider = ({ userId, children }) => {
    const presenceState = usePresence(api.presence, 'global', userId);

    const onlineUsers = useMemo(() => {
        const set = new Set();
        if (presenceState) {
            for (const p of presenceState) {
                if (p.online) set.add(p.userId);
            }
        }
        return set;
    }, [presenceState]);

    const value = useMemo(() => ({
        onlineUsers,
        resolveStatus: (storedStatus, uid) => resolveStatusFn(onlineUsers, storedStatus, uid),
    }), [onlineUsers]);

    return (
        <PresenceContext.Provider value={value}>
            {children}
        </PresenceContext.Provider>
    );
};
