// this js should run last

// DOM is ready (stylesheets, images, and subframes may not have been loaded yet)
window.addEventListener('DOMContentLoaded', () => {
    'use strict'
    handleLogoutButton();
    onSubmitWithEnter();
    onFormSubmit();
});

function handleLogoutButton() {
    const logoutButton = document.getElementById("logout-btn");
    if (logoutButton) {
        logoutButton.addEventListener("click", function (event) {
            event.preventDefault();
            event.stopPropagation();

            const url = new URL(window.location.href);

            // Parse raw query string, split into key=value or key-only
            const rawParams = window.location.search.substring(1).split("&").filter(Boolean);

            // Keep only params that are not 'login' or 'logout'
            const remainingParams = rawParams.filter(p => {
                const key = p.split("=")[0];
                return key !== "login" && key !== "logout";
            });

            // Add 'logout' first
            const finalParams = ["logout", ...remainingParams];

            const newQuery = finalParams.length ? `?${finalParams.join("&")}` : "";

            // Redirect
            window.location.href = url.origin + url.pathname + newQuery;
        });
    }
}

/**
 * Trigger to submit the button with name 'submit' and prevent other buttons to submission on 'Enter' keypress
 */
function onSubmitWithEnter() {
    'use strict'

    document.addEventListener('keypress', function (event) {
        if (event.key === 'Enter') {
            if (['TEXTAREA', 'INPUT'].includes(event.target.tagName) && event.target.type !== 'submit') {
                return; // allow pressing Enter inside text fields
            }

            event.preventDefault();
            event.stopPropagation();

            const submitButton = getSubmitButton();
            if (submitButton !== null) {
                submitButton.click();
            }
        }
    });
}

/*
 * Setup form submit event handler for form with a required input.
 * Manages the submission in case triggered by:
 *   - non-genuine submit button: clear invalid required inputs and proceed the submission
 *   - real submit button: if there is an invalid field prevent submission and trigger validation class addition
 */
function onFormSubmit() {
    'use strict';

    const form = document.querySelector('form');
    if (!form) return;

    form.addEventListener('submit', function onSubmit(event) {
        const submitter = event.submitter || event.target;

        // Check form validity once at the beginning
        const isValid = form.checkValidity();

        if (!submitter || !submitter.name.startsWith('submit')) {
            // Clear invalid required inputs before submit
            if (!isValid) {
                document.querySelectorAll('input[required]:invalid').forEach(input => {
                    if (input.value.length) {
                        input.value = '';
                    }
                });
            }
            return event;
        }

        if (!isValid) {
            console.log('Form is invalid');
            event.preventDefault();
            event.stopPropagation();
        }

        form.classList.add('was-validated'); // Add validation styling
    }, false);
}
