document.addEventListener('DOMContentLoaded', function () {
    const loginForm = document.getElementById('loginForm');

    loginForm.addEventListener('submit', async function (e) {
        e.preventDefault();

        const formData = new FormData(loginForm);
        const email = formData.get('email');
        const password = formData.get('password');

        const data = { email, password };

        try {
            const response = await fetch('/login', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(data),
            });

            const result = await response.json();

            if (response.ok && result.success) {
                document.cookie = `id=${result.user.id};`;
                document.cookie = `email=${result.user.email};`;
                document.cookie = `name=${result.user.name};`;

                fadeOut('/');
            } else {
                alert('Incorrect credentials. Please try again.');
            }
        } catch (error) {
            console.error('Error during fetch:', error);
            alert('An error occurred. Please try again.');
        }
    });
});
