import { useState, useEffect } from 'react';

export function OnlineCount() {
    // Get the online count from /api/online using WebSocket
    const [onlineCount, setOnlineCount] = useState(0);

    const [connected, setConnected] = useState(false);

    useEffect(() => {
        let socket
        const connectWebSocket = () => {
            socket = new WebSocket('/api/online'); // Replace with your WebSocket URL

            socket.onopen = () => {
                setConnected(true);
            }

            socket.onmessage = (event) => {
                setOnlineCount(event.data);
            };

            socket.onclose = () => {
                setConnected(false);
                setOnlineCount(0); // Reset count on close
                // Reconnect after a delay when the connection is closed
                setTimeout(connectWebSocket, 3000);
            };
        };

        connectWebSocket();

        return () => {
            if (socket) {
                setConnected(false);
                setOnlineCount(0);
                socket.close();
            }
        };
    }, []);

    return (
        connected ? onlineCount : <span>Connecting...</span>
    );
}