(function() {
    // FUNCTION TO ADJUST TEXTAREA HEIGHT AND SUBMIT BUTTON VISIBILITY
    function adjustTextAreaAndButton(textarea, submitButton) {
        if (textarea.value.trim() === '') {
            textarea.style.height = '50px';
        } else {
            textarea.style.height = textarea.scrollHeight + 'px';
        }

        if (textarea.value.trim() === '') {
            submitButton.classList.add('hidden');
        } else {
            submitButton.classList.remove('hidden');
        }
    }

    // INITIALIZE ELEMENTS
    const form = document.querySelector('#sendMessage');
    const textarea = document.querySelector('#dynamicTextarea');
    const conversationContainer = document.getElementById('conversation');
    const submitButton = document.getElementById('submitMessageButton');
    const typingUserId = document.getElementById('userId').textContent.trim();
    let typingTimeout;
    let isTyping = false;

    // EVENT LISTENERS
    textarea.addEventListener('input', function () {
        // Adjust textarea and button
        adjustTextAreaAndButton(dynamicTextarea, submitButton);
        if (!isTyping){
            chatWebSocket.send(JSON.stringify({ 
                'event_type': 'typing',
                'user_id': typingUserId,
                'typing_status': 'typing' 
            }));
            isTyping = true;
        }
    
        clearTimeout(typingTimeout);
        typingTimeout = setTimeout(function() {
            chatWebSocket.send(JSON.stringify({ 
                'event_type': 'typing', 
                'user_id': typingUserId,
                'typing_status': 'stopped_typing' 
            }));
            isTyping = false;
        }, 3000); 
    });
    


    form.addEventListener('submit', (event) => {
        textarea.style.height = '50px';
        submitButton.classList.add('hidden');

        setTimeout(() => {
            conversationContainer.scrollTop = conversationContainer.scrollHeight;
        }, 100);
    });

})();
