const submit = document.getElementById('submit');
const username = document.getElementById('username');
const password = document.getElementById('password');
const form = document.forms.form;
const loader = document.getElementById('loader');
const statusMessage = document.getElementById('status-message');

getAllEvent();
showStatusFromQuery();

function getAllEvent() {
    username.addEventListener('keypress', handleKeyPress);
    password.addEventListener('keypress', handleKeyPress);
    submit.addEventListener('click', handleSubmitAction);
    form.addEventListener('submit', function (e) {
        e.preventDefault();
        handleSubmitAction();
    });
}

function handleKeyPress(e) {
    if (e.key === 'Enter') {
        e.preventDefault();
        handleSubmitAction();
    }
}

function handleSubmitAction() {
    if (username.value.trim() === '' || password.value.trim() === '') {
        showStatus('Please enter both your username and password.');
        return;
    }

    submitCredentials();
}

async function submitCredentials() {
    showLoading(true);

    try {
        const formData = new FormData(form);
        const response = await fetch('auth.php', {
            method: 'POST',
            body: formData
        });

        const data = await response.json();

        if (data && data.redirect) {
            window.location.href = data.redirect;
        } else {
            showLoading(false);
            showStatus('Something went wrong. Please try again.');
        }
    } catch (error) {
        showLoading(false);
        showStatus('Unable to reach the login handler. Please try again.');
    }
}

function showLoading(isLoading) {
    if (loader) {
        loader.style.display = isLoading ? 'flex' : 'none';
    }

    if (form) {
        form.classList.toggle('is-submitting', isLoading);
    }

    if (submit) {
        submit.classList.toggle('is-disabled', isLoading);
    }
}

function showStatusFromQuery() {
    const params = new URLSearchParams(window.location.search);

    if (params.get('status') === 'error') {
        showStatus('Those credentials did not match. Please try again.');
    }
}

function showStatus(message) {
    if (statusMessage) {
        statusMessage.textContent = message;
    }
}

