import { showModal, closeModal, setupModalOk, setupOutsideClose } from "./Modal_Register.js";
import { registerRequest } from "./Register_Request.js";

// Aktifkan tombol modal
setupModalOk();
setupOutsideClose();

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

    const username = document.getElementById("username").value.trim();
    const password = document.getElementById("password").value.trim();
    const confirmPassword = document.getElementById("confirmPassword").value.trim();

    // Validasi kosong
    if (!username || !password || !confirmPassword) {
        showModal("error", "Register Failed!", "All fields are required.");
        return;
    }

    // Validasi password tidak sama
    if (password !== confirmPassword) {
        showModal("error", "Password Mismatch!", "Password and Confirm Password must match.");
        setInputError("password");
        setInputError("confirmPassword");
        return;
    }

    // Button loading state
    const submitBtn = this.querySelector("button[type='submit']");
    submitBtn.disabled = true;

    try {
        const data = await registerRequest(username, password);

        if (data.status === "success") {
            // 1. Tampilkan modal sukses
            showModal("success", "Register Successful!", data.message);

            // 🔥 PERBAIKAN: SAVE SCORE & REDIRECT 🔥
            
            // Coba simpan skor jika variable 'score' atau 'gameScore' tersedia di global scope
            // Atau jika kamu menyimpan skor sementara di localStorage
            const pendingScore = localStorage.getItem('lastScore'); // Contoh jika pakai localStorage
            
            if (pendingScore && typeof saveScore === "function") {
                console.log("Menyimpan skor pending: " + pendingScore);
                saveScore(pendingScore);
            } else if (typeof score !== 'undefined') {
                // Jika variabel global 'score' ada (dari file game logic)
                saveScore(score);
            }

            // Redirect ke halaman utama setelah 1.5 detik
            setTimeout(() => {
                window.location.href = "index.html"; // Ubah sesuai halaman game/menu kamu
            }, 1500);

        } else {
            showModal("error", "Register Failed!", data.message || "An error occurred.");
            setInputError("username");
        }

    } catch (error) {
        console.error("Register Error:", error);

        let msg = "A connection error occurred.";
        if (error.message === "Failed to fetch") {
            msg = "Unable to connect to server.";
        }
        showModal("error", "Error!", msg);

    } finally {
        submitBtn.disabled = false;
    }
});

// Hilangkan efek error saat user mengetik
document.getElementById("username").addEventListener("input", clearInputStyle);
document.getElementById("password").addEventListener("input", clearInputStyle);
document.getElementById("confirmPassword").addEventListener("input", clearInputStyle);

// Efek error merah neon
function setInputError(id) {
    const el = document.getElementById(id);
    if(el) {
        el.style.borderColor = "#ff0080";
        el.style.boxShadow = "0 0 20px rgba(255, 0, 128, 0.3)";
    }
}

// Hilangkan error visual
function clearInputStyle() {
    this.style.borderColor = "";
    this.style.boxShadow = "";
}