<script>
(function () {
    var data = window.blogData;
    if (!data || !data.articles || !data.articles.length) return;
    var menu = document.getElementById("menu");
    if (!menu) return;

    var byAlias = {};
    data.articles.forEach(function (a) {
        var alias = String(a.url || "").split("/").pop();
        if (alias) byAlias[alias] = a;
    });

    function shorten(t) {
        t = String(t || "").replace(/\s+/g, " ").trim();
        if (t.length <= 32) return t;
        var cut = t.slice(0, 32).replace(/\s+\S*$/, "");
        return (cut.length ? cut : t.slice(0, 32)) + "…";
    }

    menu.querySelectorAll("li").forEach(function (li) {
        var a = li.querySelector(":scope > a");
        if (!a) return;
        var m = String(a.getAttribute("href") || "").match(/\.\/([^/?#]+)$/);
        if (!m) return;
        var art = byAlias[m[1]];
        if (!art) return;
        var pub = String(art.date || "").slice(0, 10);
        var date = String(art.dateText || pub || "");
        li.setAttribute("data-pubdate", pub);
        var span = a.querySelector("span");
        if (span) {
            var label = (date ? date + " " : "") + shorten(a.textContent.replace(/\s+/g, " ").trim());
            var icon = span.querySelector("i");
            span.textContent = "";
            if (icon) span.appendChild(icon);
            span.appendChild(document.createTextNode(" " + label));
        }
    });

    menu.querySelectorAll("ul").forEach(function (ul) {
        var items = Array.from(ul.children);
        var dated = items.filter(function (li) { return li.hasAttribute("data-pubdate"); });
        if (dated.length < 2) return;
        dated.sort(function (x, y) {
            var dx = x.getAttribute("data-pubdate");
            var dy = y.getAttribute("data-pubdate");
            if (dx === dy) return 0;
            return dx > dy ? -1 : 1;
        });
        items.forEach(function (li) { if (!li.hasAttribute("data-pubdate")) ul.appendChild(li); });
        dated.forEach(function (li) { ul.appendChild(li); });
    });
})();
</script>