const ws = new WebSocket('ws://localhost:8080'); ws.onopen = () => { console.log('WebSocket verbunden'); ws.send(JSON.stringify({ type: 'init', userId: currentUserId })); }; ws.onmessage = (event) => { const data = JSON.parse(event.data); if (data.type === 'new_message') { // Wenn Chat offen für den Sender if (currentChatUserId === data.senderId) { addMessage(data.message, 'left'); // links = empfänger } else { // Badge hochzählen const badge = document.getElementById(`contact-badge-${data.senderId}`); badge.style.display = 'inline-block'; badge.textContent = parseInt(badge.textContent || 0) + 1; } } }; // Kontakt anklicken document.querySelectorAll('.contact').forEach(contact => { contact.addEventListener('click', () => { const userId = parseInt(contact.dataset.userid); currentChatUserId = userId; // Badge zurücksetzen const badge = document.getElementById(`contact-badge-${userId}`); badge.style.display = 'none'; badge.textContent = '0'; // Chatfenster leeren document.getElementById('chat-window').innerHTML = ''; // Option: Alte Nachrichten vom Server laden (via AJAX) }); }); // Formular senden document.getElementById('chat-form').addEventListener('submit', (e) => { e.preventDefault(); const input = document.getElementById('chat-input'); const message = input.value.trim(); if (!message || !currentChatUserId) return; ws.send(JSON.stringify({ type: 'message', senderId: currentUserId, receiverId: currentChatUserId, message: message })); addMessage(message, 'right'); // rechts = aktuell eigener User input.value = ''; }); // Nachrichten hinzufügen function addMessage(text, side) { const chatWindow = document.getElementById('chat-window'); const msgDiv = document.createElement('div'); msgDiv.className = side === 'right' ? 'text-right mb-2' : 'text-left mb-2'; msgDiv.innerHTML = `${text}`; chatWindow.appendChild(msgDiv); chatWindow.scrollTop = chatWindow.scrollHeight; }