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);

            // 2. Simpan Score (Logic Anda)
            const pendingScore = localStorage.getItem('lastScore'); 
            if (pendingScore && typeof saveScore === "function") {
                console.log("Menyimpan skor pending: " + pendingScore);
                saveScore(pendingScore);
            } else if (typeof score !== 'undefined') {
                saveScore(score);
            }

            // --- 🔥 PERUBAHAN DI SINI 🔥 ---
            
            // Cari tombol OK pada modal.
            // PENTING: Pastikan ID ini ("modalOkBtn") sesuai dengan ID tombol OK di HTML/Modal Anda.
            // Jika ID-nya beda, ganti string di bawah ini.

            // --- 🔥 TAMBAHKAN KODE DI SINI (Bagian Tombol OK) 🔥 ---
            
            const okBtn = document.getElementById("modalOkBtn"); 

            if (okBtn) {
                okBtn.addEventListener("click", function() {
                    // [BARU] Simpan username ke sessionStorage AGAR TUTORIAL MUNCUL
                    // Ini penting supaya logic di 2048.js tahu ini user baru
                    sessionStorage.setItem("loggedInUser", username); 

                    // Setelah disimpan, baru pindah ke Homepage
                    window.location.href = "Homepage.html"; 
                }, { once: true });
                
            } else {
                // Fallback jika tombol error
                console.warn("Tombol OK tidak ditemukan, redirect otomatis.");
                setTimeout(() => {
                    // [BARU] Simpan juga disini buat jaga-jaga
                    sessionStorage.setItem("loggedInUser", username);
                    window.location.href = "Homepage.html";
                }, 2000);
            }

        } 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 = "";
}