/**
 * Settings > Voting: Create election modal and assignment visibility
 */
(function() {
    function init() {
        var assignmentWrap = document.getElementById('election-assignment-wrap');
        var typeSelect = document.getElementById('election_type');
        var genGrp = document.getElementById('election-gen-grp-wrap');
        var serviceGrp = document.getElementById('election-service-grp-wrap');
        var radios = document.querySelectorAll('input[name="election_group_type"]');

        function updateAssignmentVisibility() {
            if (assignmentWrap && typeSelect) {
                assignmentWrap.style.display = typeSelect.value === 'fellowship' ? 'block' : 'none';
            }
        }
        if (typeSelect) {
            typeSelect.addEventListener('change', updateAssignmentVisibility);
            updateAssignmentVisibility();
        }

        if (genGrp && serviceGrp && radios.length) {
            function update() {
                var v = document.querySelector('input[name="election_group_type"]:checked');
                if (!v) return;
                genGrp.style.display = v.value === 'gen_grp' ? 'block' : 'none';
                serviceGrp.style.display = v.value === 'service_grp' ? 'block' : 'none';
            }
            radios.forEach(function(r) { r.addEventListener('change', update); });
            update();
        }

        var createModal = document.getElementById('election-create-modal');
        var openTop = document.getElementById('election-open-create-top');
        var openBottom = document.getElementById('election-open-create-bottom');
        var openEmpty = document.getElementById('election-open-create-empty');
        var cancelBtn = document.getElementById('election-create-cancel');
        var backdrop = createModal ? createModal.querySelector('.modal-backdrop') : null;
        function openModal() { if (createModal) createModal.hidden = false; }
        function closeModal() { if (createModal) createModal.hidden = true; }
        if (openTop) openTop.addEventListener('click', openModal);
        if (openBottom) openBottom.addEventListener('click', openModal);
        if (openEmpty) openEmpty.addEventListener('click', openModal);
        if (cancelBtn) cancelBtn.addEventListener('click', closeModal);
        if (backdrop) backdrop.addEventListener('click', closeModal);
    }
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }
})();
