document.addEventListener("DOMContentLoaded", async () => {
  await loadCurrentUser();
  renderNav();
  loadRegistrySelection();
  await loadDeptRegionMap();  // fetch authoritative dept_id → region map
  OPEN_TABS = [CURRENT_USER.standard_downloader ? "standardDownloads" : "dashboard"];
  renderTabs();
  document.getElementById("topSearch").addEventListener("keydown", e => {
    if (e.key === "Enter") {
      const q = e.target.value.trim();
      // Stash via the same pending-state hand-off articles.js uses for
      // cross-page navigation. PAGES.articles consumes ARTICLES_STATE.pendingQ
      // INSIDE the same render cycle so the initial searchArticles() call
      // already has the right query — no setTimeout race with the async
      // sites/depts fetch.
      ARTICLES_STATE.pendingQ = q;
      go("articles");
    }
  });
  // Boot: initial route from hash or default dashboard
  const defaultKey = CURRENT_USER.standard_downloader ? "standardDownloads" : "dashboard";
  const initial = (location.hash || "#" + defaultKey).slice(1);
  const page = NAV.find(n => n.key === initial && n.impl && _navVisible(n));
  go(page ? initial : defaultKey);
});
