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

  var displayYear = parseInt(cal.dataset.displayYear, 10);
  var current = parseInt(cal.dataset.displayMonth, 10);
  var monthLabel = cal.querySelector("[data-cal-month-link]");
  var months = {};
  cal.querySelectorAll("[data-cal-month]").forEach(function (t) {
    months[parseInt(t.dataset.calMonth, 10)] = t;
  });
  var jumpLinks = {};
  cal.querySelectorAll("[data-cal-month-jump]").forEach(function (a) {
    jumpLinks[parseInt(a.dataset.calMonthJump, 10)] = a;
  });

  function show(m) {
    if (m === current) return;
    if (!months[m]) return;
    months[current].hidden = true;
    months[m].hidden = false;
    current = m;
    if (monthLabel) {
      var label = jumpLinks[m];
      if (label) monthLabel.textContent = " " + label.textContent + " ";
    }
  }

  // Dropdown month picks scroll via the href anchor; we also swap the grid
  // so the calendar reflects what the user just navigated to.
  Object.keys(jumpLinks).forEach(function (key) {
    var a = jumpLinks[key];
    a.addEventListener("click", function () { show(parseInt(key, 10)); });
  });

  // Any in-page anchor click (#YYYY-MM or #YYYY-MM-DD) updates the calendar
  // so it tracks the user's focus through the year page.
  function syncFromHash() {
    var h = window.location.hash;
    if (!h) return;
    var m = h.match(/^#(\d{4})-(\d{2})(?:-\d{2})?$/);
    if (!m) return;
    if (parseInt(m[1], 10) !== displayYear) return;
    show(parseInt(m[2], 10));
  }
  window.addEventListener("hashchange", syncFromHash);
  syncFromHash();
})();
