document.getElementById("registerForm").addEventListener("submit", function (e) {
    e.preventDefault();

    let username = document.getElementById("username").value.trim();
    let email = document.getElementById("email").value.trim();
    let password = document.getElementById("password").value.trim();
    let confirmPassword = document.getElementById("confirmPassword").value.trim();
    let errorBox = document.getElementById("errorBox");

    errorBox.style.display = "none";

    // Validasi
    if (!username || !email || !password || !confirmPassword) {
        showError("Semua field harus diisi");
        return;
    }

    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
        showError("Format email tidak valid");
        return;
    }

    if (password.length < 6) {
        showError("Password minimal 6 karakter");
        return;
    }

    if (password !== confirmPassword) {
        showError("Password dan konfirmasi password tidak cocok");
        return;
    }

    let users = JSON.parse(localStorage.getItem("users") || "[]");

    if (users.some(u => u.username === username)) {
        showError("Username sudah digunakan");
        return;
    }

    if (users.some(u => u.email === email)) {
        showError("Email sudah digunakan");
        return;
    }

    // Simpan user baru
    users.push({
        id: Date.now().toString(),
        username,
        email,
        password,
        role: "player"
    });

    localStorage.setItem("users", JSON.stringify(users));

    alert("Registrasi berhasil! Silakan login.");
    window.location.href = "login.html";
});

function showError(msg) {
    let box = document.getElementById("errorBox");
    box.innerText = msg;
    box.style.display = "block";
}
