document.addEventListener("DOMContentLoaded", async () => { const username = localStorage.getItem('username'); const userKey = localStorage.getItem('userKey'); if (!username || !userKey) { window.location.href = '/'; return; } try { const response = await fetch('/validate', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username, key: userKey }) }); if (!response.ok) { localStorage.clear(); window.location.href = '/'; return; } } catch (err) { console.error('Validation failed:', err); localStorage.clear(); window.location.href = '/'; return; } function escapeHtml(text) { if (!text) return text; return text .replace(/&/g, "&") .replace(//g, ">") .replace(/"/g, """) .replace(/'/g, "'"); } // User header bar const userInfoEl = document.getElementById('user-info'); const logoutBtn = document.createElement('button'); logoutBtn.textContent = 'Logout'; logoutBtn.className = 'logout-btn'; logoutBtn.onclick = async () => { if (confirm("Are you sure you want to logout? This releases your username.")) { try { await fetch('/logout', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username, key: userKey }) }); } catch (e) { console.error("Logout request failed:", e); } localStorage.clear(); sessionStorage.clear(); window.location.href = '/'; } }; const userSpan = document.createElement('span'); userSpan.innerHTML = `Logged in as: ${escapeHtml(username)}`; userInfoEl.append(logoutBtn, userSpan); const activeRoomsContainer = document.getElementById('active-rooms-container'); const statsBadge = document.getElementById('stats-badge'); // Modal elements const joinModal = document.getElementById('join-modal'); const joinModalForm = document.getElementById('join-modal-form'); const modalRoomTitle = document.getElementById('modal-room-title'); const modalPasswordInput = document.getElementById('modal-room-password'); const modalCancelBtn = document.getElementById('modal-cancel-btn'); let pendingJoinRoom = null; let pendingJoinHasWP = false; function openJoinModal(roomName, hasWP) { pendingJoinRoom = roomName; pendingJoinHasWP = hasWP; modalRoomTitle.textContent = `🔒 Join "${roomName}"`; modalPasswordInput.value = ''; joinModal.classList.remove('hidden'); modalPasswordInput.focus(); } function closeJoinModal() { joinModal.classList.add('hidden'); pendingJoinRoom = null; } if (modalCancelBtn) { modalCancelBtn.addEventListener('click', closeJoinModal); } if (joinModalForm) { joinModalForm.addEventListener('submit', async (e) => { e.preventDefault(); const password = modalPasswordInput.value.trim(); if (!password || !pendingJoinRoom) return; const joinBtn = document.getElementById('modal-join-btn'); if (joinBtn) joinBtn.disabled = true; try { const res = await fetch('/rooms/join', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ room: pendingJoinRoom, password: password, username: username, key: userKey }) }); if (joinBtn) joinBtn.disabled = false; if (!res.ok) { const err = await res.json().catch(() => ({})); alert(err.error || 'Incorrect room password.'); modalPasswordInput.value = ''; modalPasswordInput.focus(); return; } // Success sessionStorage.setItem(`room_password_${pendingJoinRoom}`, password); const wpParam = pendingJoinHasWP ? '&watchparty=1' : ''; window.location.href = `/chat.html?room=${encodeURIComponent(pendingJoinRoom)}${wpParam}`; } catch (err) { if (joinBtn) joinBtn.disabled = false; console.error('Join error:', err); alert('Network error while joining room.'); } }); } async function loadActiveRooms() { try { const res = await fetch('/rooms'); if (!res.ok) throw new Error('Failed to fetch rooms'); const data = await res.json(); const rooms = data.active_rooms || []; const uniqueUsers = data.unique_users || 0; statsBadge.innerHTML = `🟢 Active Rooms: ${rooms.length} • 👥 Online Users: ${uniqueUsers}`; activeRoomsContainer.innerHTML = ''; if (rooms.length === 0) { activeRoomsContainer.innerHTML = `