document.addEventListener("DOMContentLoaded", () => {
    const form = document.getElementById("loginForm") as HTMLFormElement;
    const message = document.getElementById("message") as HTMLParagraphElement;

    form.addEventListener("submit", async (e) => {
        e.preventDefault();
        message.textContent = "";

        const email = (document.getElementById("email") as HTMLInputElement).value;
        const password = (document.getElementById("password") as HTMLInputElement).value;

        try {
            const response = await fetch("/api/auth/login", {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                },
                body: JSON.stringify({ email, password }),
            });

            const data = await response.json();

            if (!response.ok) {
                message.textContent = data.message || "Login failed.";
                return;
            }

            document.cookie = `token=${data.token}; path=/; SameSite=Lax; Secure`;
            message.style.color = "green";
            message.textContent = "Login successful!";

             window.location.href = "/index.html";
        } catch (error) {
            message.textContent = "Something went wrong.";
            console.error(error);
        }
    });
});