/* Celena Handbook — docs.js
   Мобильное боковое меню + scrollspy правого оглавления. Без зависимостей. */
(function () {
  'use strict';
  var root = document.querySelector('.hb');
  if (!root) return;

  // ── мобильное боковое меню ──
  var burger = document.getElementById('hbBurger');
  var side = document.getElementById('hbSide');
  if (burger && side) {
    var overlay = document.createElement('div');
    overlay.className = 'hb-side__overlay';
    side.parentNode.insertBefore(overlay, side.nextSibling);

    var close = function () { root.classList.remove('is-side-open'); };
    burger.addEventListener('click', function () { root.classList.toggle('is-side-open'); });
    overlay.addEventListener('click', close);
    side.addEventListener('click', function (e) { if (e.target.closest('a')) close(); });
    window.addEventListener('keydown', function (e) { if (e.key === 'Escape') close(); });
  }

  // ── scrollspy оглавления ──
  var links = Array.prototype.slice.call(document.querySelectorAll('.hb-toc__list a'));
  if (!links.length) return;

  var map = links.map(function (a) {
    var href = a.getAttribute('href') || '';
    var id = href.charAt(0) === '#' ? decodeURIComponent(href.slice(1)) : '';
    return { link: a, el: id ? document.getElementById(id) : null };
  }).filter(function (x) { return x.el; });

  var ticking = false;
  function spy() {
    ticking = false;
    var pos = window.scrollY + 120;
    var current = null;
    for (var i = 0; i < map.length; i++) {
      if (map[i].el.offsetTop <= pos) current = map[i];
    }
    links.forEach(function (a) { a.classList.remove('is-active'); });
    if (current) current.link.classList.add('is-active');
  }
  function onScroll() {
    if (!ticking) { ticking = true; window.requestAnimationFrame(spy); }
  }
  window.addEventListener('scroll', onScroll, { passive: true });
  window.addEventListener('resize', onScroll);
  spy();
})();
