// Generic click-to-expand behavior for the sidebar: any element with
// [data-toggle-target="some-id"] toggles the .open class on #some-id,
// used for the collapsible Admin nav group and for the Settings/Logout
// menu under the account block. Closes on an outside click or Escape.
document.addEventListener('DOMContentLoaded', function () {
  var toggles = Array.prototype.slice.call(document.querySelectorAll('[data-toggle-target]'));
  if (!toggles.length) return;

  function targetOf(toggle) {
    return document.getElementById(toggle.getAttribute('data-toggle-target'));
  }

  function setOpen(toggle, open) {
    var menu = targetOf(toggle);
    if (!menu) return;
    menu.classList.toggle('open', open);
    toggle.setAttribute('aria-expanded', open ? 'true' : 'false');
  }

  toggles.forEach(function (toggle) {
    toggle.addEventListener('click', function (e) {
      e.stopPropagation();
      var willOpen = !targetOf(toggle).classList.contains('open');
      toggles.forEach(function (t) { setOpen(t, false); });
      setOpen(toggle, willOpen);
    });
  });

  document.addEventListener('click', function (e) {
    toggles.forEach(function (toggle) {
      var menu = targetOf(toggle);
      if (menu && !menu.contains(e.target) && !toggle.contains(e.target)) {
        setOpen(toggle, false);
      }
    });
  });

  document.addEventListener('keydown', function (e) {
    if (e.key === 'Escape') toggles.forEach(function (t) { setOpen(t, false); });
  });
});

// On the mobile layout the sidebar becomes a horizontally-scrollable icon
// row instead of a vertical list -- every navigation here is a full page
// load (no client-side routing), so the browser always renders that row
// scrolled back to the start, potentially leaving the page you're actually
// on scrolled out of view off to the right. Bring the active item back
// into view on load; a no-op on desktop, where the vertical sidebar
// doesn't overflow in the first place.
document.addEventListener('DOMContentLoaded', function () {
  var active = document.querySelector('.nav-item.active');
  if (active) active.scrollIntoView({ block: 'nearest', inline: 'nearest' });
});
