(function(){
  function root(id){ return document.getElementById(id); }

  function lockScroll(){
    document.documentElement.classList.add('appModalNoScroll');
    document.body.classList.add('appModalNoScroll');
  }
  function unlockScroll(){
    if (document.querySelector('.featureModalRoot.is-open')) return;
    document.documentElement.classList.remove('appModalNoScroll');
    document.body.classList.remove('appModalNoScroll');
  }

  function open(id){
    var el = root(id);
    if(!el) return false;
    el.hidden = false;
    el.removeAttribute('hidden');
    el.setAttribute('aria-hidden','false');
    el.classList.add('is-open');
    lockScroll();
    return true;
  }

  function close(id){
    var el = root(id);
    if(!el) return false;
    el.classList.remove('is-open');
    el.setAttribute('aria-hidden','true');
    el.hidden = true;
    unlockScroll();
    return true;
  }

  document.addEventListener('click', function(ev){
    var closeBtn = ev.target.closest('[data-feature-close]');
    if(closeBtn){
      close(closeBtn.getAttribute('data-feature-close'));
      return;
    }
    var modal = ev.target.closest('.featureModalRoot');
    if(modal && ev.target === modal){
      close(modal.id);
    }
  }, true);

  document.addEventListener('keydown', function(ev){
    if(ev.key !== 'Escape') return;
    document.querySelectorAll('.featureModalRoot.is-open').forEach(function(el){ close(el.id); });
  }, true);

  window.FeatureModal = { open: open, close: close, root: root };
})();
