function openPopup(name) {
    const popup = document.getElementById(name + 'Popup');
    const backdrop = document.getElementById('popupBackdrop');

    if (!popup || !backdrop) return;

    backdrop.hidden = false;
    popup.hidden = false;
}

function closePopups() {
    document.querySelectorAll('.kiln-popup').forEach((popup) => {
        popup.hidden = true;
    });

    if (typeof resetTaskPopup === 'function') {
        resetTaskPopup();
    }

    if (typeof resetVersionPopup === 'function') {
        resetVersionPopup();
    }

    if (typeof resetProjectPopup === 'function') {
        resetProjectPopup();
    }

    const backdrop = document.getElementById('popupBackdrop');

    if (backdrop) {
        backdrop.hidden = true;
    }
}

document.addEventListener('click', (event) => {
    const openButton = event.target.closest('[data-popup-open]');
    const closeButton = event.target.closest('[data-popup-close]');
    const backdrop = event.target.closest('#popupBackdrop');

    if (openButton) {
        if (openButton.dataset.popupOpen === 'createTask' && typeof openTaskCreatePopup === 'function') {
            openTaskCreatePopup();
        } else if (openButton.dataset.popupOpen === 'createProject' && typeof openProjectCreatePopup === 'function') {
            openProjectCreatePopup();
        } else {
            openPopup(openButton.dataset.popupOpen);
        }
    }

    if (closeButton || backdrop) {
        closePopups();
    }
});

document.addEventListener('keydown', (event) => {
    if (event.key === 'Escape') {
        closePopups();
    }
});
