(function() {
    function handleChatRoomClick(event) {
        const sessionId = event.currentTarget.getAttribute('data-session');
        const chatId = event.currentTarget.getAttribute('data-roomid');
        if (sessionId && chatId) {
            openConversation(sessionId, chatId);
        } else {
            console.error('Session ID not found for this chat room.');
        }
    }


    document.querySelectorAll('.chat-room').forEach(div => {
        div.addEventListener('click', handleChatRoomClick);
    });

    function appendTextAreaScript(domain, conversationContainer) {
        if (!document.querySelector(`script[src="${protocol}://${admin_chat_domain}/static/js/osichat-admin/textarea.js"]`)) {
            const textareaScript = document.createElement('script');
            textareaScript.type = 'text/javascript';
            textareaScript.src = `${protocol}://${admin_chat_domain}/static/js/osichat-admin/textarea.js`;
            conversationContainer.appendChild(textareaScript);
        }
    }


    function openConversation(sessionid, chatid) {
            if (osichatadminroomSocket && osichatadminroomSocket.readyState !== WebSocket.CLOSED) { //Close previous sockets
                osichatadminroomSocket.close();
            }
            osichatadminroomSocket = new WebSocket(`${admin_chat_ws_scheme}://${admin_chat_domain}/ws/osichat-admin/${sessionid}/${chatid}/`);
            osichatadminroomSocket.onopen = function () {
                console.log('WebSocket connection to osichat established');
                osichatadminroomSocket.send(JSON.stringify({ 'event_type': 'load_chat', 'client_type': 'website_admin' }));
                osichatadminroomSocket.send(JSON.stringify({ 'event_type': 'update_read_messages', 'user_id': userId, 'chat_state': 'open' }));
            };
            function handleLoadChatEvent(data, osichatadminroomSocket) {
                let chatDiv = document.getElementById('widgetRightSide'); 
                chatDiv.innerHTML = data.html;
                appendTextAreaScript(admin_chat_domain, chatDiv);

                const sendMessageForm = document.querySelector('#sendMessage');
                sendMessageForm.addEventListener('submit', function (event) {
                    event.preventDefault();
                    const message = event.target.elements.message.value;
                    const eventMessage = {
                        'event_type': 'send_message',
                        'message': message,
                        'user_id': userId
                    };

                    osichatadminroomSocket.send(JSON.stringify(eventMessage));
                    event.target.reset();
                });
            }

            osichatadminroomSocket.onmessage = function (e) {
                const data = JSON.parse(e.data);
                const typingDiv = document.getElementById('typing');
                const messagesDiv = document.getElementById('messages_container');
                switch (data.event_type) {
                    case 'load_chat':
                        handleLoadChatEvent(data, osichatadminroomSocket);
                        break;
                    case 'typing': 
                        if(!typingDiv && data.user != userId){
                            messagesDiv.insertAdjacentHTML('beforeend', data.html);
                        }
                        break;
                    case 'stopped_typing':
                        if (typingDiv) {
                            typingDiv.remove();
                        }
                        break;
                    case 'send_message':
                        osichatadminroomSocket.send(JSON.stringify({ 'event_type': 'update_read_messages', 'user_id': userId, 'chat_state': 'open' }));
                        messagesDiv.insertAdjacentHTML('beforeend', data.html);
                        if (!data.user) { // If it is sent by a guest play a notification sound for the guest
                            const notificationSound = document.getElementById('notification-sound');
                            notificationSound.play();
                            if (typingDiv) {
                                typingDiv.remove();
                            }
                            break;
                        }
                        break;
                    default:
                        console.log('Unknown event type:', data.event_type);
                }
            };

            osichatadminroomSocket.onclose = function () {
                console.log('WebSocket connection to osichat closed');
            };

            osichatadminroomSocket.onerror = function (error) {
                console.error('WebSocket error:', error);
            };
    }
})();