const API_BASE = "http://127.0.0.1:5000/api"; let currentUser = null; async function checkAuth() { try { const res = await fetch(`${API_BASE}/me`, { credentials: "include" }); if (res.ok) { currentUser = await res.json(); return true; } return false; } catch (err) { return false; } } async function checkAuthAndRedirect() { const ok = await checkAuth(); if (!ok) { window.location.href = "login.html"; return false; } return true; } function updateUserMenu() { const container = document.getElementById("user-menu"); if (!container) return; if (currentUser) { container.innerHTML = ` ${escapeHtml(currentUser.username)} `; document.getElementById("logout-btn")?.addEventListener("click", logout); } else { container.innerHTML = ``; document.getElementById("login-open-btn")?.addEventListener("click", () => { window.location.href = "login.html"; }); } } async function logout() { await fetch(`${API_BASE}/logout`, { method: "POST", credentials: "include" }); window.location.href = "login.html"; } function escapeHtml(str) { if (!str) return ""; return str.replace(/[&<>]/g, function (m) { if (m === "&") return "&"; if (m === "<") return "<"; if (m === ">") return ">"; return m; }); } function showToast(msg, isError = false) { const toast = document.getElementById("toast"); if (!toast) return; toast.textContent = msg; toast.style.backgroundColor = isError ? "var(--red-7)" : "var(--green-7)"; toast.style.display = "block"; setTimeout(() => { toast.style.display = "none"; }, 3000); }