document.querySelectorAll(".toggle-password").forEach(icon => {
    icon.addEventListener("click", () => {
        let input = icon.previousElementSibling;
        if (input.type === "password") {
            input.type = "text";
            icon.classList.replace("fa-eye", "fa-eye-slash");
        } else {
            input.type = "password";
            icon.classList.replace("fa-eye-slash", "fa-eye");
        }
    });
});

function showError(input, msg){
    const errorEl = input.closest(".field")?.querySelector(".error-msg");
    if(errorEl) errorEl.textContent = msg;
}

function clearError(input){
    const errorEl = input.closest(".field")?.querySelector(".error-msg");
    if (errorEl) errorEl.textContent = "";
}

function validateEmailPhone(value){
    let gmail = /^[a-zA-Z0-9._%+-]+@gmail\.com$/;
    return gmail.test(value);
}

document.querySelectorAll(".auth-form").forEach(form => {
    form.addEventListener("submit", e => {
        e.preventDefault();

        let emailPhone = form.querySelector(".email-phone");
        let pass = form.querySelector(".password-input");
        let confirm = form.querySelector(".confirm-password");

        clearError(emailPhone);
        clearError(pass);
        if (confirm) clearError(confirm);

        let valid = true;

        if (!validateEmailPhone(emailPhone.value.trim())) {
            showError(emailPhone, "Only @gmail.com emial is allowed");
        }

        if (pass.value.length < 6) {
            showError(pass, "Password must be at least 6 characters");
            valid = false;
        }

        if (confirm && pass.value !== confirm.value) {
            showError(confirm, "Passwords do not match");
            valid = false;
        }

        if (valid) {
            fetch("http://localhost:5000/api/auth/login", {
                method: "POST",
                headers:{
                    "Content-Type": "application/json"
                },
                body: JSON.stringify({
                    email: emailPhone.value.trim(),
                    password: pass.value
                })
            })
            .then(res => res.json())
            .then(data => {
                if(data.token) {
                    localStorage.setItem("token", data.token);
                    location.href = "index.html"
                } else{
                    alert("Login failed");
                }
            })
            .catch(() => {
                alert("Server error");
            });
        }
    });
});
