// Authentication JavaScript function showTab(tabName, buttonElement) { // Hide all tabs document.querySelectorAll(".tab-content").forEach((tab) => { tab.classList.remove("active"); }); document.querySelectorAll(".tab-btn").forEach((btn) => { btn.classList.remove("active"); }); // Show selected tab document.getElementById(tabName + "-tab").classList.add("active"); if (buttonElement) { buttonElement.classList.add("active"); } // Clear message hideMessage(); } function showMessage(message, type) { const messageDiv = document.getElementById("message"); messageDiv.textContent = message; messageDiv.className = "message " + type; messageDiv.style.display = "block"; } function hideMessage() { const messageDiv = document.getElementById("message"); messageDiv.style.display = "none"; } async function handleLogin(event) { event.preventDefault(); const username = document.getElementById("login-username").value; const password = document.getElementById("login-password").value; try { const response = await fetch("/login", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ username, password }), }); const data = await response.json(); if (data.success) { showMessage(data.message, "success"); setTimeout(() => { window.location.href = "/dashboard"; }, 1000); } else { showMessage(data.message, "error"); } } catch (error) { showMessage("An error occurred. Please try again.", "error"); console.error("Login error:", error); } } async function handleRegister(event) { event.preventDefault(); const username = document.getElementById("register-username").value; const email = document.getElementById("register-email").value; const password = document.getElementById("register-password").value; const confirmPassword = document.getElementById( "register-confirm-password", ).value; // Validate password match if (password !== confirmPassword) { showMessage("Passwords do not match!", "error"); return; } // Validate password length if (password.length < 6) { showMessage("Password must be at least 6 characters long!", "error"); return; } try { const response = await fetch("/register", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ username, email, password }), }); const data = await response.json(); if (data.success) { showMessage(data.message, "success"); // Switch to login tab after successful registration setTimeout(() => { document.querySelector(".tab-btn").click(); document.getElementById("register-form").reset(); }, 2000); } else { showMessage(data.message, "error"); } } catch (error) { showMessage("An error occurred. Please try again.", "error"); console.error("Registration error:", error); } }