document.addEventListener("DOMContentLoaded", function () {
    const ws_scheme = window.location.protocol === "https:" ? "wss" : "ws";
    const webSocketUrl = `${ws_scheme}://${window.location.host}/ws/online-users/`;

    const webSocket = new WebSocket(webSocketUrl);

    webSocket.onopen = function (event) {
        console.log("WebSocket connection to online established");
    };

    webSocket.onmessage = function (event) {
        const data = JSON.parse(event.data);
        if (data.event_type === "online_user_status") {
            // Update connected users containers
            const connectedUsersContainers = document.querySelectorAll(".connected-users");
            connectedUsersContainers.forEach(container => {
                container.innerHTML = data.html;
            });

            // Rebind event listeners to switch between containers
            const customerButtons = document.querySelectorAll('.customerButton');
            const staffButtons = document.querySelectorAll('.staffButton');
            const customerContainers = document.querySelectorAll('.recentltLoggedCustomersContainer');
            const staffContainers = document.querySelectorAll('.recentltLoggedStaffsContainer');

            customerButtons.forEach(button => {
                button.addEventListener('click', function () {
                    customerContainers.forEach(container => container.classList.remove('hidden'));
                    staffContainers.forEach(container => container.classList.add('hidden'));
                });
            });

            staffButtons.forEach(button => {
                button.addEventListener('click', function () {
                    staffContainers.forEach(container => container.classList.remove('hidden'));
                    customerContainers.forEach(container => container.classList.add('hidden'));
                });
            });

            const onlineUsersIds = data.online_users_ids || [];

            // Update user activity containers based on online status
            const userActivityContainers = document.querySelectorAll(".users-activities");
            userActivityContainers.forEach(container => {
                const userId = container.getAttribute("data-userId");

                if (onlineUsersIds.map(id => id.toString()).includes(userId)) {
                    container.querySelector("#connected").classList.remove("hidden");
                    container.querySelector("#not-connected").classList.add("hidden");
                } else {
                    container.querySelector("#connected").classList.add("hidden");
                    container.querySelector("#not-connected").classList.remove("hidden");
                }
            });
        }
    };

    webSocket.onclose = function(event) {
        console.log("WebSocket connection to online closed");
    };

    webSocket.onerror = function (error) {
        console.error("WebSocket error:", error);
    };
});
