const initGearMenus = () => {
    document.querySelectorAll('.gear-btn').forEach(gear => {
        const menuId = gear.dataset.menuTarget;

        gear.addEventListener('click', (e) => {
            e.stopPropagation();
            const menu = document.getElementById(menuId);
            if (!menu) return;
            const opening = menu.style.display === 'none' || menu.style.display === '';
            menu.style.display = opening ? 'block' : 'none';
            gear.classList.toggle('active', opening);
        });

        document.addEventListener('click', (e) => {
            const menu = document.getElementById(menuId);
            if (!menu || menu.style.display === 'none') return;
            if (e.target.closest('.applet-menu-cancel') || !menu.contains(e.target)) {
                menu.style.display = 'none';
                gear.classList.remove('active');
            }
        });
    })

};

document.addEventListener('DOMContentLoaded', initGearMenus);

const appletContainerIds = new Set([
    'id_applets_container',
    'id_game_applets_container',
    'id_gk_sections_container',
    'id_wallet_applets_container',
    'id_billboard_applets_wrapper',
]);

document.body.addEventListener('htmx:afterSwap', (e) => {
    if (!e.detail.target || !appletContainerIds.has(e.detail.target.id)) return;
    document.querySelectorAll('.gear-btn').forEach(gear => {
        const menu = document.getElementById(gear.dataset.menuTarget);
        if (menu) menu.style.display = 'none';
        gear.classList.remove('active');
    });
});