// Add an input event listener to update password requirements
document.getElementById("password").addEventListener("input", (event) => {
    const password = event.target.value;

    // Check for uppercase letter
    const hasUppercase = /[A-Z]/.test(password);
    updateRequirement("uppercase-check", hasUppercase);

    // Check for a number
    const hasNumber = /[0-9]/.test(password);
    updateRequirement("number-check", hasNumber);

    // Check for a special character
    const hasSpecialChar = /[!@#$%^&*]/.test(password);
    updateRequirement("special-char-check", hasSpecialChar);

    // Check for minimum length
    const isLongEnough = password.length >= 8;
    updateRequirement("length-check", isLongEnough);
});

// Helper function to update the requirement status
function updateRequirement(requirementId, isValid) {
    const requirementElement = document.getElementById(requirementId);
    const icon = requirementElement.querySelector(".icon");

    if (isValid) {
        icon.textContent = "✔";
        requirementElement.classList.add("valid");
        requirementElement.classList.remove("invalid");
    } else {
        icon.textContent = "✘";
        requirementElement.classList.add("invalid");
        requirementElement.classList.remove("valid");
    }
}

// Handle form submission
document.getElementById("signupForm").addEventListener("submit", async (event) => {
    event.preventDefault(); // Prevent the default form submission behavior

    const name = document.getElementById("name").value.trim();
    const email = document.getElementById("email").value.trim();
    const password = document.getElementById("password").value.trim();

    // Perform client-side validation
    const hasUppercase = /[A-Z]/.test(password);
    const hasNumber = /[0-9]/.test(password);
    const hasSpecialChar = /[!@#$%^&*]/.test(password);
    const isLongEnough = password.length >= 8;

    if (!hasUppercase || !hasNumber || !hasSpecialChar || !isLongEnough) {
        showErrorPopup("Please meet all password requirements before signing up.");
        return;
    }

    try {
        // Send API call for signup
        const response = await fetch("php/signup.php", {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
            },
            body: JSON.stringify({ name, email, password }),
        });

        const result = await response.json();

        if (response.ok) {
            window.location.href = "landing.html"; // Redirect to landing page
        } else {
            showErrorPopup(result.error || "Sign up failed. Please try again.");
        }
    } catch (error) {
        console.error("Error signing up:", error);
        showErrorPopup("An error occurred. Please try again.");
    }
});

// Function to show error popup
function showErrorPopup(message) {
    const errorPopup = document.createElement("div");
    errorPopup.classList.add("error-popup");
    errorPopup.innerText = message;
    document.body.appendChild(errorPopup);

    // Auto-remove the popup after 3 seconds
    setTimeout(() => {
        errorPopup.remove();
    }, 3000);
}

// Toggle password visibility
const togglePassword = document.getElementById("togglePassword");
const passwordInput = document.getElementById("password");

togglePassword.addEventListener("click", () => {
    const type = passwordInput.getAttribute("type") === "password" ? "text" : "password";
    passwordInput.setAttribute("type", type);

    // Toggle the icon class without affecting layout
    togglePassword.querySelector("i").classList.toggle("fa-eye");
    togglePassword.querySelector("i").classList.toggle("fa-eye-slash");

    // Set the cursor position after toggling
    const cursorPosition = passwordInput.selectionStart;
    passwordInput.value = passwordInput.value; // Reset the value to trigger cursor update
    passwordInput.setSelectionRange(cursorPosition, cursorPosition);
});
