
(function() {
    const openChatButton = document.getElementById('openChatContainer');
    const openChatButton2 = document.getElementById('openChatContainer2');
    const chatWidget = document.getElementById('chatWidget');
    const closeChatButton = document.getElementById('closeChatContainer');
    const closeMobileChatButton = document.getElementById('closeMobileChatContainer');
    const conversation = document.getElementById('conversation');

    const unreadMessages = document.getElementById('unreadMessages');
    const closeNewMesagePopup = document.getElementById('closeNewMesagePopup');

    function scrollToBottom() {
        conversation.scrollTop = conversation.scrollHeight;
    }

    function toggleBodyScroll(preventScroll) {
        if (preventScroll) {
            document.body.classList.add('no-scroll');
        } else {
            document.body.classList.remove('no-scroll');
        }
    }

    function checkScreenSize() {
        if (chatWidget.classList.contains('hidden')) {
            return;
        }
        if (window.innerWidth < 798) {
            toggleBodyScroll(true);
        } else {
            toggleBodyScroll(false);
        }
    }

    function openChat() {
        isOpen = true;
        chatWidget.classList.remove('hidden');
        openChatButton.classList.add('hidden');
        closeChatButton.classList.remove('hidden');
        if (unreadMessages) {
            unreadMessages.classList.add('hidden');
        }
        osichatSocket.send(JSON.stringify({ 'event_type': 'update_read_messages', 'chat_state': 'open' }));
        scrollToBottom();
        checkScreenSize();
    }

    function closeChat() {
        isOpen = false;
        chatWidget.classList.add('hidden');
        openChatButton.classList.remove('hidden');
        if (closeChatButton) {
            closeChatButton.classList.add('hidden');
        } else if (closeMobileChatButton) {
            closeMobileChatButton.classList.add('hidden');
        }
        toggleBodyScroll(false);
    }

    // Attach event listeners
    openChatButton.addEventListener('click', openChat);
    if (openChatButton2) {
        openChatButton2.addEventListener('click', openChat);
    }
    closeChatButton.addEventListener('click', closeChat);
    closeMobileChatButton.addEventListener('click', closeChat);
    window.addEventListener('resize', checkScreenSize);

    // CSS class to prevent scrolling
    const style = document.createElement('style');
    style.innerHTML = `
        .no-scroll {
            overflow: hidden;
        }
    `;
    document.head.appendChild(style);

    // To close the unread messages popup
    if (closeNewMesagePopup) {
        closeNewMesagePopup.addEventListener('click', function() {
            if (unreadMessages) {
                unreadMessages.classList.add('hidden')
            }
        });
    }
})();
