(function () {
  var cal = document.querySelector(".diary-cal");
  if (!cal) return;
  cal.querySelectorAll(".dropdown > button").forEach(wireDropdown);

  var displayMonth = parseInt(cal.dataset.displayMonth, 10);
  var months = {};
  cal.querySelectorAll("[data-cal-month]").forEach(function (t) {
    months[parseInt(t.dataset.calMonth, 10)] = t;
  });

  // Centering only applies inside the persistent desktop rail (.sidebar). On
  // mobile the widget is re-parented into .overlay-body, where we leave the
  // grids stacked from January and do not scroll (design decision).
  function railContainer() {
    var el = cal.parentElement;
    while (el) {
      if (el.classList) {
        if (el.classList.contains("overlay-body")) return null;
        if (el.classList.contains("sidebar")) return el;
      }
      el = el.parentElement;
    }
    return null;
  }

  // Scroll only the rail so the given month grid sits in its vertical center;
  // the main document/window position is untouched (priority: don't disturb
  // the reading position).
  function centerMonth(m) {
    var grid = months[m];
    if (!grid) return;
    var container = railContainer();
    if (!container) return;
    var offset = grid.getBoundingClientRect().top -
      container.getBoundingClientRect().top + container.scrollTop;
    container.scrollTop = offset - (container.clientHeight - grid.clientHeight) / 2;
  }

  // Center the current month once, on initial render. Anchor navigation
  // (#YYYY-MM / #YYYY-MM-DD) deliberately does NOT re-center the rail —
  // re-scrolling on every hop is disorienting; the today/current cell
  // highlighting is enough to keep bearings.
  centerMonth(displayMonth);
})();
