(function () {
    "use strict";

    const content = document.querySelector("#wpbody-content");
    if (!content) {
        return;
    }

    document.body.classList.add("h4bs-admin-ui");
    const labels = Object.assign({
        adminNavigation: "Help4 admin navigation",
        quickNavigation: "Quick navigation",
        workspace: "Workspace",
        openWorkspace: "Open Help4 workspace",
        jumpTo: "Jump to",
        jumpToSection: "Jump to page section",
        chooseSection: "Choose a section",
        details: "Details",
        scrollableTable: "Scrollable data table",
        filterRows: "Filter table rows",
        filterPlaceholder: "Filter these rows",
        rowCount: "%1$d of %2$d rows",
    }, window.h4bsAdminWorkspaceData || {});

    function cleanText(value) {
        return String(value || "").replace(/\s+/g, " ").trim();
    }

    function uniqueId(prefix, index) {
        let candidate = prefix + "-" + String(index + 1);
        let suffix = 1;
        while (document.getElementById(candidate)) {
            suffix += 1;
            candidate = prefix + "-" + String(index + 1) + "-" + String(suffix);
        }
        return candidate;
    }

    function prepareResponsiveTables() {
        content.querySelectorAll("table.widefat").forEach(function (table, tableIndex) {
            if (table.classList.contains("h4bs-forms-table")) return;
            const headings = Array.from(table.querySelectorAll(":scope > thead > tr:first-child > th"))
                .map(function (heading) {
                    return cleanText(heading.textContent);
                });
            if (!headings.length) {
                return;
            }

            table.classList.add("h4bs-admin-responsive-table");
            if (! table.parentElement.classList.contains("h4bs-admin-table-scroll")) {
                const scroller = document.createElement("div");
                scroller.className = "h4bs-admin-table-scroll h4bs-admin-table-scroll--generated";
                scroller.tabIndex = 0;
                scroller.setAttribute("role", "region");
                scroller.setAttribute("aria-label", labels.scrollableTable);
                table.parentNode.insertBefore(scroller, table);
                scroller.appendChild(table);
            }

            table.querySelectorAll(":scope > tbody > tr").forEach(function (row) {
                Array.from(row.children).forEach(function (cell, cellIndex) {
                    if (cell.tagName !== "TD") {
                        return;
                    }
                    const label = headings[cellIndex] || labels.details;
                    cell.dataset.h4bsLabel = label;
                    if (cell.colSpan > 1) {
                        cell.classList.add("h4bs-admin-responsive-table__wide-cell");
                    }
                });
            });

            table.dataset.h4bsTableIndex = String(tableIndex);
            const rows = Array.from(table.querySelectorAll(":scope > tbody > tr"));
            if (rows.length < 8) {
                return;
            }

            const scroller = table.closest(".h4bs-admin-table-scroll");
            if (!scroller || scroller.previousElementSibling?.classList.contains("h4bs-admin-table-tools")) {
                return;
            }
            const tools = document.createElement("div");
            tools.className = "h4bs-admin-table-tools";
            const searchLabel = document.createElement("label");
            const searchText = document.createElement("span");
            searchText.className = "screen-reader-text";
            searchText.textContent = labels.filterRows;
            const search = document.createElement("input");
            search.type = "search";
            search.placeholder = labels.filterPlaceholder;
            search.setAttribute("aria-label", labels.filterRows);
            const status = document.createElement("span");
            status.className = "h4bs-admin-table-tools__status";
            status.setAttribute("aria-live", "polite");
            const updateStatus = function (visibleCount) {
                status.textContent = labels.rowCount
                    .replace("%1$d", String(visibleCount))
                    .replace("%2$d", String(rows.length));
            };
            updateStatus(rows.length);
            search.addEventListener("input", function () {
                const query = cleanText(search.value).toLocaleLowerCase();
                let visibleCount = 0;
                rows.forEach(function (row) {
                    const match = !query || cleanText(row.textContent).toLocaleLowerCase().includes(query);
                    row.hidden = !match;
                    if (match) {
                        visibleCount += 1;
                    }
                });
                updateStatus(visibleCount);
            });
            searchLabel.append(searchText, search);
            tools.append(searchLabel, status);
            scroller.insertAdjacentElement("beforebegin", tools);
        });
    }

    function menuWorkspaces() {
        const seen = new Set();
        const selectors = [
            '#adminmenu a[href*="page=h4"]',
            '#toplevel_page_h4bs-settings .wp-submenu a[href*="post_type=h4_"]',
            '#toplevel_page_h4bs-commerce .wp-submenu a[href*="post_type=h4_"]',
        ];
        const simpleAllowed = new Set(['h4bs-settings','h4bs-builder-pages','h4bs-calendar','h4bs-staff-directory','h4bs-forms','h4bs-form-entries']);
        return Array.from(document.querySelectorAll(selectors.join(',')))
            .map(function (anchor) {
                let url;
                try {
                    url = new URL(anchor.href, window.location.href);
                } catch (error) {
                    return null;
                }
                const pageSlug = url.searchParams.get("page");
                const postType = url.searchParams.get("post_type");
                const slug = pageSlug || (postType?.startsWith("h4_") ? "post_type:" + postType : "");
                if (labels.simpleMode && !simpleAllowed.has(slug)) return null;
                const label = cleanText(anchor.textContent);
                if (!slug || !label || seen.has(slug)) {
                    return null;
                }
                seen.add(slug);
                return { slug: slug, label: label, href: url.href };
            })
            .filter(Boolean);
    }

    function pageSections() {
        return Array.from(content.querySelectorAll("h2, h3"))
            .filter(function (heading) {
                const label = cleanText(heading.textContent);
                const rect = heading.getBoundingClientRect();
                return label && rect.width > 0 && rect.height > 0;
            })
            .slice(0, 80)
            .map(function (heading, index) {
                if (!heading.id) {
                    heading.id = uniqueId("h4bs-admin-section", index);
                }
                heading.tabIndex = -1;
                return { id: heading.id, label: cleanText(heading.textContent) };
            });
    }

    function appendOption(select, value, label, selected) {
        const option = document.createElement("option");
        option.value = value;
        option.textContent = label;
        option.selected = !!selected;
        select.appendChild(option);
    }

    function buildAdminNavigator() {
        const workspaces = menuWorkspaces();
        const sections = pageSections();
        if (!workspaces.length && sections.length < 2) {
            return;
        }

        const navigator = document.createElement("nav");
        navigator.className = "h4bs-admin-navigator";
        navigator.setAttribute("aria-label", labels.adminNavigation);

        const disclosure = document.createElement("details");
        disclosure.className = "h4bs-admin-navigator__disclosure";
        const summary = document.createElement("summary");
        summary.className = "h4bs-admin-navigator__summary";
        summary.textContent = labels.quickNavigation;
        const panel = document.createElement("div");
        panel.className = "h4bs-admin-navigator__panel";

        if (workspaces.length) {
            const workspaceLabel = document.createElement("label");
            workspaceLabel.className = "h4bs-admin-navigator__field";
            const workspaceText = document.createElement("span");
            workspaceText.textContent = labels.workspace;
            const workspaceSelect = document.createElement("select");
            workspaceSelect.setAttribute("aria-label", labels.openWorkspace);
            const currentUrl = new URL(window.location.href);
            const currentPage = currentUrl.searchParams.get("page");
            const currentPostType = currentUrl.searchParams.get("post_type");
            const currentSlug = currentPage || (currentPostType?.startsWith("h4_") ? "post_type:" + currentPostType : "");
            workspaces.forEach(function (workspace) {
                appendOption(workspaceSelect, workspace.href, workspace.label, workspace.slug === currentSlug);
            });
            workspaceSelect.addEventListener("change", function () {
                if (workspaceSelect.value) {
                    window.location.assign(workspaceSelect.value);
                }
            });
            workspaceLabel.append(workspaceText, workspaceSelect);
            panel.appendChild(workspaceLabel);
        }

        if (sections.length >= 2) {
            const sectionLabel = document.createElement("label");
            sectionLabel.className = "h4bs-admin-navigator__field";
            const sectionText = document.createElement("span");
            sectionText.textContent = labels.jumpTo;
            const sectionSelect = document.createElement("select");
            sectionSelect.setAttribute("aria-label", labels.jumpToSection);
            appendOption(sectionSelect, "", labels.chooseSection, true);
            sections.forEach(function (section) {
                appendOption(sectionSelect, section.id, section.label, false);
            });
            sectionSelect.addEventListener("change", function () {
                const target = document.getElementById(sectionSelect.value);
                if (!target) {
                    return;
                }
                target.scrollIntoView({ behavior: "smooth", block: "start" });
                target.focus({ preventScroll: true });
                window.history.replaceState(null, "", "#" + encodeURIComponent(target.id));
                disclosure.open = false;
            });
            sectionLabel.append(sectionText, sectionSelect);
            panel.appendChild(sectionLabel);
        }

        disclosure.append(summary, panel);
        navigator.appendChild(disclosure);

        document.addEventListener("pointerdown", function (event) {
            if (disclosure.open && !navigator.contains(event.target)) {
                disclosure.open = false;
            }
        });
        disclosure.addEventListener("keydown", function (event) {
            if (event.key === "Escape" && disclosure.open) {
                disclosure.open = false;
                summary.focus();
            }
        });

        const firstWrap = content.querySelector(":scope > .wrap, :scope > .h4bs-workspace");
        const title = firstWrap ? firstWrap.querySelector(":scope > h1") : content.querySelector("h1");
        if (title && title.parentNode) {
            title.insertAdjacentElement("afterend", navigator);
        } else if (firstWrap) {
            firstWrap.prepend(navigator);
        } else {
            content.prepend(navigator);
        }
    }

    prepareResponsiveTables();
    buildAdminNavigator();
}());
