(function(){
  function toggle(btn, opts){
    var wrapper = btn.closest('.falcify-wrapper') || btn.closest('.falcify-floating');
    if (!wrapper) return;
    var falc = wrapper.querySelector('.falcify-falc-content');
    var orig = wrapper.querySelector('.falcify-original-content');
    var label = btn.querySelector('.falcify-label');
    var external = null;
    var sel = wrapper.getAttribute('data-target-selector');
    if (sel){ try{ external = document.querySelector(sel); }catch(e){} }
    var expanded = btn.getAttribute('aria-expanded') === 'true';
    if (expanded){
      if (falc) falc.hidden = true;
      if (orig) orig.style.display = '';
      if (external) external.style.display = '';
      btn.setAttribute('aria-expanded','false');
      if (label) label.textContent = btn.getAttribute('data-text-falc');
    } else {
      if (falc) falc.hidden = false;
      if (orig) orig.style.display = 'none';
      if (external) external.style.display = 'none';
      btn.setAttribute('aria-expanded','true');
      if (label) label.textContent = btn.getAttribute('data-text-normal');
      if (falc && falc.id) btn.setAttribute('aria-controls', falc.id);
    }
  }
  document.addEventListener('click', function(e){
    var btn = e.target.closest('.falcify-toggle-button');
    if (btn) toggle(btn);
  });
  document.addEventListener('keydown', function(e){
    if (e.key !== 'Enter' && e.key !== ' ') return;
    var btn = e.target.closest && e.target.closest('.falcify-toggle-button');
    if (btn && document.activeElement === btn){ e.preventDefault(); toggle(btn); }
  });
})();
