/*
* This script is used to dismiss the alert message
*/

// Function to remove specific query parameter from URL
function removeQueryParameter(url, parameter) {
    var urlParts = url.split('?');
    if (urlParts.length >= 2) {
        var prefix = encodeURIComponent(parameter) + '=';
        var queryStrings = urlParts[1].split('&');
        for (var i = 0; i < queryStrings.length; i++) {
            if (queryStrings[i].lastIndexOf(prefix, 0) !== -1) {
                queryStrings.splice(i, 1);
            }
        }
        return urlParts[0] + (queryStrings.length > 0 ? '?' + queryStrings.join('&') : '');
    }
    return url;
}

// Dismiss alert message when close button is clicked
document.getElementById('removeMessageButton').addEventListener('click', function() {
    var url = window.location.href;
    if (url.indexOf('?message=') !== -1) {
        var newUrl = removeQueryParameter(url, 'message');
        window.history.replaceState({}, document.title, newUrl);
        window.location.href = newUrl; // Update window location
    } else if (url.indexOf('?errorMessage=') !== -1) {
        var newUrl = removeQueryParameter(url, 'errorMessage');
        window.history.replaceState({}, document.title, newUrl);
        window.location.href = newUrl; // Update window location
    }
});

// Escape key alert close
document.addEventListener('DOMContentLoaded', function() {
    document.addEventListener('keydown', function(event) {
        if (event.key === 'Escape') {
            var alert = document.querySelector('.alert');
            if (alert) {
                alert.classList.add('hidden');
                var url = window.location.href;
                if (url.indexOf('?message=') !== -1) {
                    var newUrl = removeQueryParameter(url, 'message');
                    window.history.replaceState({}, document.title, newUrl);
                    window.location.href = newUrl; // Update window location
                } else if (url.indexOf('?errorMessage=') !== -1) {
                    var newUrl = removeQueryParameter(url, 'errorMessage');
                    window.history.replaceState({}, document.title, newUrl);
                    window.location.href = newUrl; // Update window location
                }
            }
        }
    });
});
