(function(){
    var CFG = window.paintopsDirCfg || { ajax: '', nonce: '' };
    window.paintopsDirToggle = function(id){
        var m = document.getElementById(id);
        if (!m) { return; }
        var willShow = !m.classList.contains('show');
        document.querySelectorAll('.pv-dir-menu.show').forEach(function(o){ o.classList.remove('show'); });
        if (willShow) { m.classList.add('show'); }
    };
    window.paintopsDirPick = function(a){
        var provider = a.getAttribute('data-provider');
        var wrap = a.closest('.pv-dir-wrap');
        if (wrap && provider){
            var main = wrap.querySelector('.pv-dir-main');
            if (main){ main.setAttribute('href', a.getAttribute('href')); }
            wrap.querySelectorAll('.pv-dir-menu a').forEach(function(x){
                var cur = (x.getAttribute('data-provider') === provider);
                x.classList.toggle('is-current', cur);
                var chk = x.querySelector('.pv-dir-check');
                if (chk){ chk.style.visibility = cur ? 'visible' : 'hidden'; }
            });
            var menu = a.closest('.pv-dir-menu');
            if (menu){ menu.classList.remove('show'); }
            var fd = new FormData();
            fd.append('action','paintops_set_directions_provider');
            fd.append('nonce', CFG.nonce);
            fd.append('provider', provider);
            fetch(CFG.ajax, {method:'POST', body:fd, credentials:'same-origin'}).catch(function(){});
        }
        return true; // let the link open the chosen maps app
    };
    document.addEventListener('click', function(e){
        if (e.target.closest('.pv-dir-wrap')) { return; }
        document.querySelectorAll('.pv-dir-menu.show').forEach(function(o){ o.classList.remove('show'); });
    });
})();
