(function() {
    function handleChatRoomClick(event) {
        const chatId = event.currentTarget.getAttribute('data-roomid');
        if (chatId && chatId !== currentChatId) {
            showLoader();
            openConversation(chatId);
            currentChatId = chatId;
        }
    }

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


    function markCurrentChatRead(chatid) {
        const unreadElement = document.querySelector(`.unread[data-roomid='${chatid}']`);
        if (unreadElement) {
            unreadElement.classList.add('hidden');
        }
    }

    // FUNCTIONS TO SHOW & HIDE THE LOADER
    function showLoader() {
        const roomLoader = document.getElementById('roomLoader');
        if (roomLoader) {
            roomLoader.classList.remove('hidden');
        }

        const widgetLeftSide = document.getElementById('widgetLeftSide');
        widgetLeftSide.classList.remove('overflow-y-auto');
        widgetLeftSide.classList.add('overflow-hidden');
    }

    function hideLoader() {
        const roomLoader = document.getElementById('roomLoader');
        if (roomLoader) {
            roomLoader.classList.add('hidden');
        }

        const widgetLeftSide = document.getElementById('widgetLeftSide');
        widgetLeftSide.classList.remove('overflow-hidden');
        widgetLeftSide.classList.add('overflow-y-auto');
    }

    function appendTextAreaScript(conversationContainer) {
        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 scrollBottom() {
    //     const conversationContainer = document.getElementById('messages_container');
    //     if (conversationContainer) {
    //         conversationContainer.scrollTo({
    //             top: conversationContainer.scrollHeight,
    //             behavior: 'smooth'
    //         });
    //     }
    // }

    function scrollBottom() {
        const conversationContainer = document.getElementById('messages_container');
        if (conversationContainer) {
            conversationContainer.scrollTop = conversationContainer.scrollHeight; // Instantly scroll to the bottom
        }
    }
    

    function openConversation(chatId) {
        if (osichatadminroomSocket) {
            osichatadminroomSocket.close();
        }

        osichatadminroomSocket = new WebSocket(`${admin_chat_ws_scheme}://${admin_chat_domain}/ws/osichat-admin/${chatId}/`);

        osichatadminroomSocket.onopen = function () {
            hideLoader();
            markCurrentChatRead(chatId)
            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) {
            let chatDiv = document.getElementById('widgetRightSide'); 
            chatDiv.innerHTML = data.html;
            appendTextAreaScript(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();
            });

            scrollBottom();
        }

        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);
                    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 (typingDiv) {
                            typingDiv.remove();
                        }
                    }
                    break;
                default:
                    console.log('Unknown event type:', data.event_type);
            }
        };

        osichatadminroomSocket.onclose = function () {
            console.log('WebSocket connection closed');
            if (currentChatId === chatId) { //Attempt to reconnect only if same chat 
                setTimeout(() => {
                    console.log('Attempting to reconnect to WebSocket...');
                    openConversation(chatId);
                }, 2000);
            }
        };

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

    window.addEventListener('offline', () => {
        showLoader();
        if (osichatadminroomSocket) {
            osichatadminroomSocket.close();
        }
    });

})();
