document.addEventListener('DOMContentLoaded', async (v) =>{
    await isAuth();
    let loginForm = document.getElementById('loginForm');

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

        login();
    })
})

// Async login function in vanilla JS
async function login() {
    // Set login running state
    let loginRunning = true;
    let loginError = false;

    // Get form data
    let username = document.getElementById('username').value;
    let password = document.getElementById('password').value;

    let postFields = {
        userData: {
            username: username,
            password: password
        },
        action: 'login'
    };

    try {
        // Send request
        const response = await fetch('https://api.stellaamor.com/users.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            credentials: 'include', // To handle cookies
            body: JSON.stringify(postFields)
        });

        const data = await response.json();

        if (data.status === 'fail') {
            // Display error if login fails
            loginError = true;
            document.getElementById('loginError').innerText = data.message;
            loginRunning = false;
        } else {
            // Successful login, redirect to /home
            loginRunning = false;
            setTimeout(() => {
                window.location.href = '/home';

                // Reset form fields and errors after login
                document.getElementById('username').value = '';
                document.getElementById('password').value = '';
                document.getElementById('loginError').innerText = '';
                loginRunning = false;
            }, 1500);
        }
    } catch (error) {
        console.error('Login error:', error);
        loginError = true;
        loginRunning = false;
    }
}

// Async authentication check function in vanilla JS
async function isAuth() {
    try {
        const response = await fetch('https://api.stellaamor.com/users.php?isAuth=true', {
            method: 'GET',
            credentials: 'include'
        });
        const data = await response.json();
        
        if (data.status === true) {
            window.location.href = '/home';
        } else {
            return false;
        }
    } catch (error) {
        return false;
    }
}
