(function () {
  const url = new URL(window.location.href);
  const tag = url.searchParams.get("tag");
  if (!tag) return;

  // Check if we're on a proper tag page or a fallback
  const hasTagPreview = document.querySelector(".tag-preview");
  if (hasTagPreview) return; // Server rendered tag page correctly

  // We're on a fallback page (likely offline) — build tag view from cache
  if (!window.MDHubCache) return;

  window.MDHubCache.getCachedDocuments().then(function (docs) {
    if (!docs || !docs.length) return;

    const tagged = docs.filter(function (doc) {
      return doc.tags && doc.tags.indexOf(tag) !== -1;
    });

    // Build a minimal tag browser
    const shell = document.querySelector(".workspace-shell");
    if (!shell) return;

    const browser = shell.querySelector(".miller-browser");
    const preview = shell.querySelector(".empty-preview") || shell.querySelector(".document-shell");

    if (browser) {
      // Replace browser with a single column of tagged docs
      const itemsHtml = tagged
        .sort(function (a, b) {
          const aName = (a.title || a.path).toLowerCase();
          const bName = (b.title || b.path).toLowerCase();
          return aName < bName ? -1 : aName > bName ? 1 : 0;
        })
        .map(function (doc) {
          const name = doc.title || doc.path;
          const path = doc.path.replace(/\.md$/, "");
          return (
            '<li><a href="/docs/' +
            escapeHtml(path) +
            '" title="' +
            escapeHtml(name) +
            '"><span class="browser-item-label"><svg class="browser-icon browser-icon--page" aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round"><path d="M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z"></path><path d="M14 2v4a2 2 0 0 0 2 2h4"></path></svg><span class="browser-item-name">' +
            escapeHtml(name) +
            "</span></span></a></li>"
          );
        })
        .join("");

      browser.innerHTML =
        '<section class="miller-column miller-column--root" aria-label="#' +
        escapeHtml(tag) +
        '"><h2><span class="miller-column-title-wrap"><span class="miller-column-title-text">#' +
        escapeHtml(tag) +
        "</span></span></h2><ul>" +
        itemsHtml +
        "</ul></section>";
    }

    if (preview) {
      preview.outerHTML =
        '<section class="tag-preview"><p class="eyebrow">Tag</p><h1>#' +
        escapeHtml(tag) +
        '</h1><p class="lede">' +
        tagged.length +
        " document" +
        (tagged.length === 1 ? "" : "s") +
        " found</p></section>";
    }
  });

  function escapeHtml(str) {
    if (!str) return "";
    return str
      .replace(/&/g, "&amp;")
      .replace(/</g, "&lt;")
      .replace(/>/g, "&gt;")
      .replace(/"/g, "&quot;")
      .replace(/'/g, "&#039;");
  }
})();
