const loginForm = document.getElementById('auth-form');
const loginError = document.getElementById('auth-error');

loginForm.addEventListener('submit', async (event) => {
    event.preventDefault();

    const email = document.getElementById('email').value;
    const password = document.getElementById('password').value;

    const encodedData = new URLSearchParams();
    encodedData.append('username', email);
    encodedData.append('password', password);

    const response = await fetch(`/auth/cookie/login`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: encodedData,
    });

    if (response.ok) {
        document.cookie = 'ghostforge=' + response.headers.get('Set-Cookie');
        window.location.href = '/dashboard';
    } else {
        const errorMessage = "Invalid username or password.";
        let toast = document.getElementById("error-msg");
        if (!toast) {
            toast = document.createElement('div');
            toast.id = "error-msg";
            toast.classList.add("toast", "toast-error");
            loginError.appendChild(toast);
        }
        toast.innerText = errorMessage;
    }
});
