// retoor <retoor@molodetz.nl>

export class Accessibility {
    constructor() {
        this.hideDecorativeIcons();
        this.markCurrentLinks();
        this.labelIconControls();
    }

    hideDecorativeIcons() {
        document.querySelectorAll(".icon, .topnav-caret").forEach((icon) => {
            if (icon.hasAttribute("aria-hidden")) return;
            const host = icon.closest("a, button, label, summary, li, h1, h2, h3, h4, span, div");
            if (!host) return;
            const named =
                host.getAttribute("aria-label") ||
                host.getAttribute("title") ||
                (host.textContent || "").replace(icon.textContent || "", "").trim();
            if (named) icon.setAttribute("aria-hidden", "true");
        });
    }

    markCurrentLinks() {
        document.querySelectorAll("nav a.active").forEach((link) => {
            if (!link.hasAttribute("aria-current")) {
                link.setAttribute("aria-current", "page");
            }
        });
    }

    labelIconControls() {
        document.querySelectorAll("a[title], button[title]").forEach((el) => {
            if (el.getAttribute("aria-label")) return;
            if ((el.textContent || "").trim()) return;
            el.setAttribute("aria-label", el.getAttribute("title"));
        });
    }
}
