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

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

// Async login function in vanilla JS
async function login() {
    // Set login running state
    let loginRunning = true;
    let loginError = false;
    document.getElementById('loginError').innerText = '';
    document.getElementById('loginError').classList.add('d-none');


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

    const 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',
            body: JSON.stringify(postFields)
        });

        const data = await response.json();

        if (data.status === 'fail') {
            loginError = true;
            document.getElementById('loginError').innerText = data.message;
            document.getElementById('loginError').classList.remove('d-none');
            loginRunning = false;
        } else {
            loginRunning = false;
            setTimeout(() => {
                window.location.href = '/home';

                document.getElementById('username').value = '';
                document.getElementById('password').value = '';
                document.getElementById('loginError').innerText = '';
                loginRunning = false;
            }, 1500);
        }
    } catch (error) {
        loginError = true;
        loginRunning = false;
    }
}

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;
    }
}
