import { useState, useEffect } from 'react';
import { useWebSocketContext } from '@/context/WebSocketContext';

interface UseUserPresenceReturn {
  isOnline: (userId: string) => boolean;
  onlineUsers: Set<string>;
}

export const useUserPresence = (): UseUserPresenceReturn => {
  const [onlineUsers, setOnlineUsers] = useState<Set<string>>(new Set());

  const { isConnected, lastMessage } = useWebSocketContext();

  useEffect(() => {
    if (lastMessage) {
      switch (lastMessage.type) {
        case 'user_joined':
          if (lastMessage.userId) {
            setOnlineUsers(prev => new Set([...prev, lastMessage.userId]));
          }
          break;
        case 'user_left':
          if (lastMessage.userId) {
            setOnlineUsers(prev => {
              const newSet = new Set(prev);
              newSet.delete(lastMessage.userId);
              return newSet;
            });
          }
          break;
        case 'online_users':
          if (lastMessage.users && Array.isArray(lastMessage.users)) {
            setOnlineUsers(new Set(lastMessage.users));
          }
          break;
      }
    }
  }, [lastMessage]);

  const isOnline = (userId: string): boolean => {
    return onlineUsers.has(userId);
  };

  // Request online users list when connected
  useEffect(() => {
    if (isConnected) {
      // Request current online users
      // This would need to be implemented in the WebSocket server
    }
  }, [isConnected]);

  return {
    isOnline,
    onlineUsers
  };
};