document.addEventListener('DOMContentLoaded', () => { const config = document.getElementById('game-lobby-config'); if (!config) { return; } const publicUrl = config.dataset.mercurePublicUrl; const topic = config.dataset.topic; const chatLog = document.getElementById('lobby-chat-log'); function appendLobbyMessage(username, content, createdAt) { if (!chatLog) { return; } const emptyNotice = document.getElementById('lobby-chat-empty'); if (emptyNotice) { emptyNotice.remove(); } const time = createdAt ? new Date(createdAt).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }) : ''; const wrapper = document.createElement('div'); wrapper.className = 'lobby-message'; const author = document.createElement('strong'); author.textContent = username; const timestamp = document.createElement('span'); timestamp.className = 'text-muted small'; timestamp.textContent = ' ' + time; const body = document.createElement('div'); body.textContent = content; wrapper.appendChild(author); wrapper.appendChild(timestamp); wrapper.appendChild(body); chatLog.appendChild(wrapper); chatLog.scrollTop = chatLog.scrollHeight; } if (publicUrl && topic) { const url = new URL(publicUrl); url.searchParams.append('topic', topic); const eventSource = new EventSource(url); eventSource.onmessage = event => { const data = JSON.parse(event.data); if (data.type === 'lobby_message') { appendLobbyMessage(data.username, data.content, data.createdAt); } else if (data.type === 'player_joined' || data.type === 'session_started') { window.location.reload(); } }; } if (chatLog) { chatLog.scrollTop = chatLog.scrollHeight; } });