(function () {
    const themeMap = {
        green: {
            hue: "160",
            sat: "84%",
            primaryLightness: "32%",
            primary: "#0d9766",
            primaryRgb: "13, 151, 102",
            accent: "#1bb79b",
            accentRgb: "27, 183, 155",
            gradient: "linear-gradient(135deg, #0d9766 0%, #1bb79b 100%)",
            primaryHover: "#0c8e60",
            primaryActive: "#096f4b",
            hoverGradient: "linear-gradient(135deg, #0c8e60 0%, #19aa91 100%)",
            heroArtFilter: "none"
        },
        blue: {
            hue: "238",
            sat: "88%",
            primaryLightness: "66%",
            primary: "#5b5cf6",
            primaryRgb: "91, 92, 246",
            accent: "#7d6bff",
            accentRgb: "125, 107, 255",
            gradient: "linear-gradient(135deg, #4e46f8 0%, #7d6bff 100%)",
            primaryHover: "#4c4eed",
            primaryActive: "#3f42dd",
            hoverGradient: "linear-gradient(135deg, #433cf0 0%, #6f5dff 100%)",
            heroArtFilter: "none"
        },
        purple: {
            hue: "267",
            sat: "68%",
            primaryLightness: "51%",
            primary: "#6d2bd7",
            primaryRgb: "109, 43, 215",
            accent: "#b03ced",
            accentRgb: "176, 60, 237",
            gradient: "linear-gradient(135deg, #6d2bd7 0%, #b03ced 100%)",
            primaryHover: "#5f24c3",
            primaryActive: "#4f1ca7",
            hoverGradient: "linear-gradient(135deg, #5f24c3 0%, #9d35e3 100%)",
            heroArtFilter: "hue-rotate(184deg) saturate(1.12) brightness(1.01)"
        },
        red: {
            hue: "349",
            sat: "61%",
            primaryLightness: "51%",
            primary: "#cf334d",
            primaryRgb: "207, 51, 77",
            accent: "#f26b7a",
            accentRgb: "242, 107, 122",
            gradient: "linear-gradient(135deg, #cf334d 0%, #f26b7a 100%)",
            primaryHover: "#b82d44",
            primaryActive: "#962539",
            hoverGradient: "linear-gradient(135deg, #b82d44 0%, #e75f70 100%)",
            heroArtFilter: "hue-rotate(240deg) saturate(1.08) brightness(1.02)"
        },
        yellow: {
            hue: "38",
            sat: "82%",
            primaryLightness: "40%",
            primary: "#b87412",
            primaryRgb: "184, 116, 18",
            accent: "#e9a72f",
            accentRgb: "233, 167, 47",
            gradient: "linear-gradient(135deg, #b87412 0%, #e9a72f 100%)",
            primaryHover: "#a5660f",
            primaryActive: "#874f08",
            hoverGradient: "linear-gradient(135deg, #a5660f 0%, #d99a29 100%)",
            heroArtFilter: "hue-rotate(308deg) saturate(1.08) brightness(1.03)"
        },
        black: {
            hue: "220",
            sat: "22%",
            primaryLightness: "13%",
            primary: "#111827",
            primaryRgb: "17, 24, 39",
            accent: "#374151",
            accentRgb: "55, 65, 81",
            gradient: "linear-gradient(135deg, #111827 0%, #374151 100%)",
            primaryHover: "#0b1220",
            primaryActive: "#050a14",
            hoverGradient: "linear-gradient(135deg, #0b1220 0%, #2f3947 100%)",
            heroArtFilter: "grayscale(0.2) brightness(0.82) contrast(1.05)"
        }
    };
    const themeLabels = {
        green: "Green",
        blue: "Nebulix",
        purple: "Purple",
        red: "Red",
        yellow: "Yellow",
        black: "Black"
    };

    function setTheme(themeName) {
        const theme = themeMap[themeName] || themeMap.blue;
        const root = document.documentElement;

        if (window.HostiqueBranding && typeof window.HostiqueBranding.applyThemeBranding === "function") {
            window.HostiqueBranding.applyThemeBranding(themeName);
        } else {
            root.style.setProperty("--hue", theme.hue);
            root.style.setProperty("--sat", theme.sat);
            root.style.setProperty("--primary-lightness", theme.primaryLightness);
            root.style.setProperty("--brand-primary", theme.primary);
            root.style.setProperty("--brand-primary-rgb", theme.primaryRgb);
            root.style.setProperty("--brand-primary-hover", theme.primaryHover || theme.primary);
            root.style.setProperty("--brand-primary-active", theme.primaryActive || theme.primaryHover || theme.primary);
            root.style.setProperty("--brand-accent", theme.accent);
            root.style.setProperty("--brand-accent-rgb", theme.accentRgb);
            root.style.setProperty("--primary", theme.primary);
            root.style.setProperty("--primary-rgb", theme.primaryRgb);
            root.style.setProperty("--accent", theme.accent);
            root.style.setProperty("--accent-rgb", theme.accentRgb);
            root.style.setProperty("--gradient-primary", theme.gradient);
            root.style.setProperty("--gradient-primary-hover", theme.hoverGradient);
            root.style.setProperty("--primary-hover", theme.primaryHover || theme.primary);
            root.style.setProperty("--hero-art-filter", theme.heroArtFilter || "none");
        }

        document.body.setAttribute("data-theme", themeName);

        document.querySelectorAll(".current-theme-swatch").forEach(function (node) {
            node.className = "theme-swatch current-theme-swatch " + themeName;
        });

        document.querySelectorAll(".current-theme-name").forEach(function (node) {
            node.textContent = themeLabels[themeName] || "Theme";
        });

        document.querySelectorAll(".theme-option").forEach(function (button) {
            button.classList.toggle("active", button.getAttribute("data-theme") === themeName);
            button.setAttribute("aria-pressed", button.classList.contains("active") ? "true" : "false");
        });

        try {
            localStorage.setItem("hostique-theme", themeName);
        } catch (e) {}
    }

    function initThemeSelector() {
        setTheme("blue");

        document.querySelectorAll(".theme-option").forEach(function (button) {
            button.addEventListener("click", function () {
                setTheme(button.getAttribute("data-theme") || "green");
            });
        });
    }

    function toggleSidebar(forceOpen) {
        const body = document.body;
        const shouldOpen = typeof forceOpen === "boolean"
            ? forceOpen
            : !body.classList.contains("dashboard-sidebar-open");
        body.classList.toggle("dashboard-sidebar-open", shouldOpen);
        body.classList.toggle("dashboard-sidebar-mobile-active", shouldOpen && window.innerWidth < 992);
    }

    function initSidebar() {
        const openButton = document.querySelector("[data-dashboard-sidebar-toggle]");
        const closeButton = document.querySelector("[data-dashboard-sidebar-close]");
        const desktopToggleButton = document.querySelector("[data-dashboard-sidebar-desktop-toggle]");
        const reopenButton = document.querySelector("[data-dashboard-sidebar-reopen]");
        const overlay = document.querySelector("[data-dashboard-overlay]");
        const sidebar = document.getElementById("dashboardSidebar");
        const mobileNavLinks = Array.from(document.querySelectorAll(".dashboard-sidebar a, .dashboard-sidebar button.dashboard-nav__link"));
        const body = document.body;

        function syncMobileSidebarState() {
            const isOpen = body.classList.contains("dashboard-sidebar-open");
            const isMobile = window.innerWidth < 992;

            if (openButton) {
                openButton.setAttribute("aria-expanded", isOpen && isMobile ? "true" : "false");
            }

            if (closeButton) {
                closeButton.setAttribute("aria-expanded", isOpen && isMobile ? "true" : "false");
            }

            if (sidebar) {
                sidebar.setAttribute("aria-hidden", isOpen && isMobile ? "false" : (isMobile ? "true" : "false"));
            }

            if (overlay) {
                overlay.setAttribute("aria-hidden", isOpen && isMobile ? "false" : "true");
            }
        }

        function syncDesktopSidebarState(isHidden) {
            if (desktopToggleButton) {
                desktopToggleButton.setAttribute("aria-pressed", isHidden ? "true" : "false");
                desktopToggleButton.setAttribute("aria-label", isHidden ? "Show sidebar" : "Hide sidebar");
                desktopToggleButton.classList.toggle("is-collapsed", isHidden);
            }

            if (reopenButton) {
                reopenButton.setAttribute("aria-pressed", isHidden ? "true" : "false");
                reopenButton.classList.toggle("is-visible", isHidden);
            }
        }

        document.addEventListener("click", function (event) {
            const toggleTrigger = event.target.closest("[data-dashboard-sidebar-toggle]");
            const closeTrigger = event.target.closest("[data-dashboard-sidebar-close], [data-dashboard-overlay]");

            if (toggleTrigger) {
                event.preventDefault();
                toggleSidebar();
                syncMobileSidebarState();
                return;
            }

            if (closeTrigger) {
                event.preventDefault();
                toggleSidebar(false);
                syncMobileSidebarState();
            }
        });

        mobileNavLinks.forEach(function (link) {
            link.addEventListener("click", function () {
                if (window.innerWidth < 992 && !link.hasAttribute("data-dashboard-nav-toggle")) {
                    toggleSidebar(false);
                    syncMobileSidebarState();
                }
            });
        });

        if (desktopToggleButton || reopenButton) {
            let isHidden = false;

            try {
                isHidden = window.localStorage.getItem("hostique-sidebar-hidden") === "true";
            } catch (e) {}

            body.classList.toggle("dashboard-sidebar-hidden", isHidden);
            syncDesktopSidebarState(isHidden);

            if (desktopToggleButton) {
                desktopToggleButton.addEventListener("click", function () {
                    if (window.innerWidth < 992) {
                        toggleSidebar();
                        return;
                    }

                    const shouldHide = !body.classList.contains("dashboard-sidebar-hidden");
                    body.classList.toggle("dashboard-sidebar-hidden", shouldHide);
                    syncDesktopSidebarState(shouldHide);

                    try {
                        window.localStorage.setItem("hostique-sidebar-hidden", shouldHide ? "true" : "false");
                    } catch (e) {}
                });
            }

            if (reopenButton) {
                reopenButton.addEventListener("click", function () {
                    body.classList.remove("dashboard-sidebar-hidden");
                    syncDesktopSidebarState(false);

                    try {
                        window.localStorage.setItem("hostique-sidebar-hidden", "false");
                    } catch (e) {}
                });
            }
        }

        window.addEventListener("resize", function () {
            if (window.innerWidth >= 992) {
                toggleSidebar(false);
            }
            syncMobileSidebarState();
        });

        document.addEventListener("keydown", function (event) {
            if (event.key === "Escape" && body.classList.contains("dashboard-sidebar-open")) {
                toggleSidebar(false);
                syncMobileSidebarState();
            }
        });

        syncMobileSidebarState();
    }

    function initSidebarDropdowns() {
        const groups = Array.from(document.querySelectorAll(".dashboard-nav__group"));

        if (!groups.length) {
            return;
        }

        function syncGroupHeight(group) {
            const wrap = group.querySelector(".dashboard-nav__submenu-wrap");
            const submenu = group.querySelector(".dashboard-nav__submenu");

            if (!wrap || !submenu) {
                return;
            }

            wrap.style.maxHeight = group.classList.contains("is-open")
                ? submenu.scrollHeight + "px"
                : "0px";
        }

        function setGroupState(group, shouldOpen) {
            const button = group.querySelector("[data-dashboard-nav-toggle]");

            group.classList.toggle("is-open", shouldOpen);

            if (button) {
                button.setAttribute("aria-expanded", shouldOpen ? "true" : "false");
            }

            syncGroupHeight(group);
        }

        const initiallyOpenGroup = groups.find(function (group) {
            return group.classList.contains("is-open");
        });
        const defaultGroup = groups.find(function (group) {
            return group.hasAttribute("data-dashboard-nav-default-open");
        });

        if (!initiallyOpenGroup && defaultGroup) {
            defaultGroup.classList.add("is-open");
        }

        groups.forEach(function (group) {
            syncGroupHeight(group);
        });

        document.querySelectorAll("[data-dashboard-nav-toggle]").forEach(function (button) {
            button.addEventListener("click", function () {
                const group = button.closest(".dashboard-nav__group");

                if (!group) {
                    return;
                }

                const shouldOpen = !group.classList.contains("is-open");

                groups.forEach(function (currentGroup) {
                    setGroupState(currentGroup, currentGroup === group ? shouldOpen : false);
                });
            });
        });

        window.addEventListener("resize", function () {
            groups.forEach(syncGroupHeight);
        });
    }

    function initSidebarUserMenu() {
        const menu = document.querySelector("[data-dashboard-user-menu]");

        if (!menu) {
            return;
        }

        const toggle = menu.querySelector("[data-dashboard-user-toggle]");
        const dropdown = menu.querySelector(".dashboard-user-dropdown");

        if (!toggle || !dropdown) {
            return;
        }

        function syncMenuPlacement() {
            const toggleRect = toggle.getBoundingClientRect();
            const dropdownHeight = Math.min(dropdown.scrollHeight || 360, 420);
            const viewportPadding = 24;
            const spaceAbove = toggleRect.top - viewportPadding;
            const spaceBelow = window.innerHeight - toggleRect.bottom - viewportPadding;
            const shouldDropUp = spaceBelow < dropdownHeight && spaceAbove > spaceBelow;

            menu.classList.toggle("is-drop-up", shouldDropUp);
            menu.classList.toggle("is-drop-down", !shouldDropUp);
        }

        function setOpenState(shouldOpen) {
            if (shouldOpen) {
                syncMenuPlacement();
            }

            menu.classList.toggle("is-open", shouldOpen);
            toggle.setAttribute("aria-expanded", shouldOpen ? "true" : "false");
        }

        toggle.addEventListener("click", function (event) {
            event.stopPropagation();
            setOpenState(!menu.classList.contains("is-open"));
        });

        document.addEventListener("click", function (event) {
            if (!menu.contains(event.target)) {
                setOpenState(false);
            }
        });

        document.addEventListener("keydown", function (event) {
            if (event.key === "Escape") {
                setOpenState(false);
            }
        });

        window.addEventListener("resize", function () {
            if (menu.classList.contains("is-open")) {
                syncMenuPlacement();
            }
        });
    }

    function initSearch() {
        const input = document.getElementById("dashboardSearch");
        if (!input) {
            return;
        }

        input.addEventListener("input", function () {
            const value = input.value.toLowerCase().trim();
            const dataTablesFilter = document.querySelector(".dataTables_filter input");

            if (dataTablesFilter) {
                dataTablesFilter.value = value;
                if (window.jQuery) {
                    window.jQuery(dataTablesFilter).trigger("keyup");
                } else {
                    dataTablesFilter.dispatchEvent(new Event("keyup", { bubbles: true }));
                }
                return;
            }

            document.querySelectorAll(".dashboard-table tbody tr, .dashboard-stack .dashboard-list-card").forEach(function (row) {
                const text = row.textContent.toLowerCase();
                row.style.display = !value || text.indexOf(value) !== -1 ? "" : "none";
            });
        });
    }

    function parseRedirectUrl(value) {
        if (!value) {
            return "";
        }

        const match = value.match(/'([^']+)'/);
        return match ? match[1] : "";
    }

    function escapeHtml(value) {
        return String(value || "")
            .replace(/&/g, "&amp;")
            .replace(/</g, "&lt;")
            .replace(/>/g, "&gt;")
            .replace(/\"/g, "&quot;")
            .replace(/'/g, "&#39;");
    }

    function mapStatusClass(statusText) {
        const value = (statusText || "").toLowerCase();

        if (value.indexOf("active") !== -1 || value.indexOf("paid") !== -1) {
            return "success";
        }

        if (value.indexOf("unpaid") !== -1 || value.indexOf("pending") !== -1) {
            return "warning";
        }

        if (value.indexOf("answered") !== -1) {
            return "info";
        }

        if (value.indexOf("closed") !== -1 || value.indexOf("terminated") !== -1) {
            return "muted";
        }

        return "primary";
    }

    async function fetchDocument(url) {
        const response = await fetch(url, {
            credentials: "include"
        });

        if (!response.ok) {
            throw new Error("Request failed");
        }

        return new DOMParser().parseFromString(await response.text(), "text/html");
    }

    function loadDocumentFrame(url) {
        return new Promise(function (resolve, reject) {
            const frame = document.createElement("iframe");
            frame.setAttribute("src", url);
            frame.setAttribute("aria-hidden", "true");
            frame.tabIndex = -1;
            frame.style.position = "absolute";
            frame.style.width = "0";
            frame.style.height = "0";
            frame.style.border = "0";
            frame.style.opacity = "0";
            frame.style.pointerEvents = "none";

            const cleanup = function () {
                frame.remove();
            };

            frame.addEventListener("load", function () {
                try {
                    const doc = frame.contentDocument;
                    cleanup();

                    if (!doc) {
                        reject(new Error("Document unavailable"));
                        return;
                    }

                    resolve(doc);
                } catch (error) {
                    cleanup();
                    reject(error);
                }
            }, { once: true });

            frame.addEventListener("error", function () {
                cleanup();
                reject(new Error("Frame load failed"));
            }, { once: true });

            document.body.appendChild(frame);
        });
    }

    async function hydrateDashboardServices() {
        const body = document.querySelector("[data-dashboard-services-body]");
        const table = document.querySelector("[data-dashboard-services-table]");

        if (!body || !table) {
            return;
        }

        try {
            const doc = await fetchDocument(table.getAttribute("data-source-url") || "clientarea.php?action=services");
            const rows = Array.from(doc.querySelectorAll("#tableServicesList tbody tr"));
            const items = rows.map(function (row) {
                const cells = row.querySelectorAll("td");
                const productCell = cells[0];
                const amountCell = cells[1] ? cells[1].cloneNode(true) : null;
                const renewalCell = cells[2] ? cells[2].cloneNode(true) : null;
                const statusCell = cells[3];
                const product = productCell ? (productCell.querySelector("strong") || productCell).textContent.trim() : "";
                const domain = productCell && productCell.querySelector(".dashboard-item-subtitle")
                    ? productCell.querySelector(".dashboard-item-subtitle").textContent.trim()
                    : "-";
                const cycle = amountCell && amountCell.querySelector("small")
                    ? amountCell.querySelector("small").textContent.trim()
                    : "";
                const status = statusCell ? statusCell.textContent.trim() : "";
                const href = parseRedirectUrl(row.getAttribute("onclick"));
                let renewal = renewalCell;

                if (amountCell && amountCell.querySelector("small")) {
                    amountCell.querySelector("small").remove();
                }

                if (renewal && renewal.querySelector(".w-hidden")) {
                    renewal.querySelector(".w-hidden").remove();
                }

                const renewalDate = renewal && renewal.querySelector(".dashboard-table-date")
                    ? renewal.querySelector(".dashboard-table-date").textContent.trim()
                    : (renewal ? renewal.textContent.trim() : "");

                return {
                    product: product,
                    subtitle: cycle,
                    domain: domain || "-",
                    status: status,
                    href: href,
                    renewal: renewalDate
                };
            }).filter(function (item) {
                return item.status.toLowerCase() === "active" && item.product;
            }).slice(0, 4);

            if (!items.length) {
                return;
            }

            body.innerHTML = items.map(function (item) {
                const title = item.href
                    ? '<a href="' + escapeHtml(item.href) + '">' + escapeHtml(item.product) + "</a>"
                    : escapeHtml(item.product);
                const renewalValue = item.renewal || "Not scheduled";
                const renewalMeta = item.renewal ? "Next renewal" : (item.subtitle ? escapeHtml(item.subtitle) : "Service cycle");
                const actionHref = item.href || "clientarea.php?action=services";

                return '<tr>'
                    + '<td><div class="dashboard-home-service"><span class="dashboard-home-service__icon"><svg viewBox="0 0 24 24" aria-hidden="true"><rect x="5" y="5" width="14" height="5" rx="1.5"></rect><rect x="5" y="10.5" width="14" height="4.5" rx="1.5"></rect><rect x="5" y="16" width="14" height="3" rx="1.5"></rect></svg></span><div><div class="dashboard-item-title">' + title + '</div><div class="dashboard-item-subtitle">' + (item.subtitle ? escapeHtml(item.subtitle) : "&nbsp;") + "</div></div></div></td>"
                    + "<td>" + escapeHtml(item.domain || "-") + "</td>"
                    + '<td><span class="status-pill ' + mapStatusClass(item.status) + '"><span>' + escapeHtml(item.status) + "</span></span></td>"
                    + '<td><div class="dashboard-home-renewal"><div class="dashboard-home-renewal__date">' + escapeHtml(renewalValue) + '</div><div class="dashboard-item-subtitle">' + renewalMeta + "</div></div></td>"
                    + '<td class="text-right"><a href="' + escapeHtml(actionHref) + '" class="dashboard-home-action" aria-label="Manage Service"><svg viewBox="0 0 24 24" aria-hidden="true"><circle cx="12" cy="5" r="1.7"></circle><circle cx="12" cy="12" r="1.7"></circle><circle cx="12" cy="19" r="1.7"></circle></svg></a></td>'
                    + "</tr>";
            }).join("");
        } catch (e) {}
    }

    async function hydrateDashboardInvoices() {
        const list = document.querySelector("[data-dashboard-invoices-list]");

        if (!list) {
            return;
        }

        function renderEmptyState() {
            const emptyTitle = list.getAttribute("data-empty-title") || "No invoices";
            const emptyMessage = list.getAttribute("data-empty-message") || "";
            list.innerHTML =
                '<div class="dashboard-home-empty">'
                + '<span class="dashboard-home-empty__icon">'
                + '<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M7 3.5h8l4 4v12a1.5 1.5 0 0 1-1.5 1.5h-10A1.5 1.5 0 0 1 6 19.5V5A1.5 1.5 0 0 1 7.5 3.5z"></path><path d="M15 3.5V8h4"></path><path d="M9 12h6"></path><path d="M9 16h4"></path></svg>'
                + '</span>'
                + '<div class="dashboard-home-empty__title">' + escapeHtml(emptyTitle) + '</div>'
                + '<div class="dashboard-item-subtitle">' + escapeHtml(emptyMessage) + '</div>'
                + '</div>';
        }

        try {
            const sourceUrl = list.getAttribute("data-source-url") || "clientarea.php?action=invoices";
            let doc;

            try {
                doc = await fetchDocument(sourceUrl);
            } catch (fetchError) {
                doc = await loadDocumentFrame(sourceUrl);
            }

            const rows = Array.from(doc.querySelectorAll("#tableInvoicesList tbody tr"));
            const items = rows.map(function (row) {
                const cells = row.querySelectorAll("td");
                const dateCell = cells[1] ? cells[1].cloneNode(true) : null;

                if (dateCell && dateCell.querySelector(".w-hidden")) {
                    dateCell.querySelector(".w-hidden").remove();
                }

                return {
                    href: parseRedirectUrl(row.getAttribute("onclick")),
                    number: cells[0] ? cells[0].textContent.trim() : "",
                    date: dateCell ? dateCell.textContent.trim() : "",
                    total: cells[3] ? cells[3].textContent.trim() : "",
                    status: cells[4] ? cells[4].textContent.trim() : ""
                };
            }).filter(function (item) {
                return item.number;
            }).slice(0, 3);

            if (!items.length) {
                renderEmptyState();
                return;
            }

            list.innerHTML = items.map(function (item) {
                return '<a class="dashboard-list-card" href="' + escapeHtml(item.href || "clientarea.php?action=invoices") + '">'
                    + "<div><div class=\"dashboard-item-title\">" + escapeHtml(item.number) + "</div><div class=\"dashboard-item-subtitle\">" + escapeHtml(item.date) + "</div></div>"
                    + '<div class="text-right"><div class="fw-semibold">' + escapeHtml(item.total || "-") + '</div><div class="dashboard-list-status ' + mapStatusClass(item.status) + '">' + escapeHtml(item.status) + "</div></div>"
                    + "</a>";
            }).join("");
        } catch (e) {
            renderEmptyState();
        }
    }

    function slugifyModuleTitle(value) {
        return String(value || "")
            .toLowerCase()
            .replace(/[^a-z0-9]+/g, "-")
            .replace(/^-+|-+$/g, "");
    }

    function initModuleProductOverview() {
        document.querySelectorAll(".dashboard-usage-meter").forEach(function (meter) {
            const raw = parseFloat(meter.getAttribute("data-usage-value") || "0");
            const value = Math.max(0, Math.min(100, isNaN(raw) ? 0 : raw));
            meter.style.setProperty("--usage-value", value);
        });

        const overview = document.querySelector("[data-module-overview]");

        if (!overview) {
            return;
        }

        const cards = Array.from(overview.querySelectorAll(".panel.panel-default.card.mb-3"));

        cards.forEach(function (card) {
            const heading = card.querySelector("h3");
            const title = heading ? heading.textContent.trim() : "";
            const slug = slugifyModuleTitle(title);

            card.classList.add("dashboard-module-card");

            if (slug) {
                card.classList.add("dashboard-module-card--" + slug);
            }

            if (slug === "package-domain" || slug === "usage-statistics" || slug === "billing-overview") {
                card.classList.add("dashboard-module-card--hidden");
            }
        });
    }

    function syncWordPressInstanceSummary(select) {
        if (!select) {
            return;
        }

        const option = select.options[select.selectedIndex];

        if (!option) {
            return;
        }

        const titleNode = document.getElementById("wordPressSelectedLabel");
        const urlNode = document.getElementById("wordPressSelectedUrl");
        const pathNode = document.getElementById("wordPressSelectedPath");

        if (titleNode) {
            titleNode.textContent = option.getAttribute("data-title") || option.textContent.trim();
        }

        if (urlNode) {
            urlNode.textContent = option.getAttribute("data-url") || option.value || "";
        }

        if (pathNode) {
            pathNode.textContent = option.getAttribute("data-path") || "/";
        }
    }

    function enhanceWordPressOptionData(select) {
        if (!select) {
            return;
        }

        Array.from(select.options).forEach(function (option) {
            if (!option.getAttribute("data-title")) {
                option.setAttribute("data-title", option.textContent.trim());
            }

            if (!option.getAttribute("data-url")) {
                option.setAttribute("data-url", option.value || "");
            }

            if (!option.getAttribute("data-path")) {
                const match = option.textContent.match(/\(([^)]+)\)/);
                option.setAttribute("data-path", match ? match[1] : "/");
            }
        });
    }

    function createWordPressActionProxy(sourceButton, className) {
        if (!sourceButton) {
            return null;
        }

        const proxy = document.createElement("button");
        proxy.type = "button";
        proxy.className = sourceButton.className + " " + className;
        proxy.innerHTML = sourceButton.innerHTML;
        proxy.addEventListener("click", function () {
            sourceButton.click();
        });
        return proxy;
    }

    function initCpanelWordPress() {
        const panel = document.getElementById("cPanelWordPress");

        if (!panel) {
            return;
        }

        panel.classList.add("cpanel-wp-enhanced");

        const header = panel.querySelector(".card-header");
        const title = header ? header.querySelector("h3") : null;
        const body = panel.querySelector(".card-body");
        const instanceRow = document.getElementById("wordpressInstanceRow");
        const select = document.getElementById("wordPressInstances");
        const homeButton = document.getElementById("btnGoToWordPressHome");
        const adminButton = document.getElementById("btnGoToWordPressAdmin");
        const preview = document.getElementById("newWordPressFullUrlPreview");
        const installResultRow = document.getElementById("wordPressInstallResultRow");
        const titleInput = document.getElementById("wpNewBlogTitle");
        const pathInput = document.getElementById("wpNewPath");
        const passwordInput = document.getElementById("wpAdminPass");
        const installButton = document.getElementById("btnInstallWordpress");
        const wpDomain = panel.getAttribute("data-wp-domain") || "";
        const hasMultipleSites = select && select.options.length > 1;

        if (title) {
            title.textContent = "WordPress";
        }

        enhanceWordPressOptionData(select);

        if (header && !header.querySelector(".cpanel-wp-header")) {
            const headerWrap = document.createElement("div");
            headerWrap.className = "cpanel-wp-header";

            const titleWrap = document.createElement("div");
            titleWrap.className = "cpanel-wp-header__title";

            const icon = document.createElement("span");
            icon.className = "cpanel-wp-header__icon";
            icon.innerHTML = '<i class="fab fa-wordpress-simple"></i>';

            const badge = document.createElement("span");
            badge.className = "cpanel-wp-header__badge";
            badge.textContent = (select && select.options.length ? select.options.length : 0) + " " + ((select && select.options.length === 1) ? "Site" : "Sites");

            titleWrap.appendChild(icon);

            if (title) {
                titleWrap.appendChild(title);
            }

            if (select && select.options.length) {
                titleWrap.appendChild(badge);
            }

            headerWrap.appendChild(titleWrap);

            if (homeButton || adminButton) {
                const actions = document.createElement("div");
                actions.className = "cpanel-wp-header__actions";

                if (homeButton) {
                    const websiteProxy = createWordPressActionProxy(homeButton, "cpanel-wp-btn cpanel-wp-btn--ghost");
                    if (websiteProxy) {
                        actions.appendChild(websiteProxy);
                    }
                }

                if (adminButton) {
                    const adminProxy = createWordPressActionProxy(adminButton, "cpanel-wp-btn cpanel-wp-btn--primary");
                    if (adminProxy) {
                        actions.appendChild(adminProxy);
                    }
                }

                headerWrap.appendChild(actions);
            }

            header.innerHTML = "";
            header.appendChild(headerWrap);
        }

        if (body && instanceRow && select && !body.querySelector(".cpanel-wp-instance")) {
            instanceRow.className = "cpanel-wp-instance";
            instanceRow.removeAttribute("style");

            const card = document.createElement("div");
            card.className = "cpanel-wp-instance__card";

            const site = document.createElement("div");
            site.className = "cpanel-wp-instance__site";
            site.innerHTML =
                '<span class="cpanel-wp-instance__site-icon"><i class="fas fa-globe"></i></span>' +
                '<div class="cpanel-wp-instance__site-copy">' +
                '<strong id="wordPressSelectedLabel"></strong>' +
                '<span id="wordPressSelectedUrl"></span>' +
                '</div>';

            const meta = document.createElement("div");
            meta.className = "cpanel-wp-instance__meta";
            meta.innerHTML =
                '<div class="cpanel-wp-instance__meta-block">' +
                '<span class="cpanel-wp-instance__pill cpanel-wp-instance__pill--success"><i class="fas fa-circle"></i><span>Connected</span></span>' +
                '<span class="cpanel-wp-instance__meta-item"><span class="cpanel-wp-instance__meta-label">Installed Path</span><span class="cpanel-wp-instance__meta-value" id="wordPressSelectedPath">/</span></span>' +
                '</div>' +
                '<div class="cpanel-wp-instance__meta-block">' +
                '<span class="cpanel-wp-instance__meta-item"><span class="cpanel-wp-instance__meta-label">Primary Domain</span><span class="cpanel-wp-instance__meta-value">' + escapeHtml(wpDomain) + '</span></span>' +
                '<span class="cpanel-wp-instance__meta-item"><span class="cpanel-wp-instance__meta-label">Admin Access</span><span class="cpanel-wp-instance__meta-value">Available</span></span>' +
                '</div>';

            let selectorWrap = null;

            if (hasMultipleSites) {
                selectorWrap = document.createElement("div");
                selectorWrap.className = "cpanel-wp-instance__selector";

                const selectorLabel = document.createElement("label");
                selectorLabel.setAttribute("for", "wordPressInstances");
                selectorLabel.textContent = "Installed Sites";

                selectorWrap.appendChild(selectorLabel);
                selectorWrap.appendChild(select);
            } else {
                select.classList.add("cpanel-wp-select--hidden");
            }

            card.appendChild(site);
            card.appendChild(meta);

            if (selectorWrap) {
                card.appendChild(selectorWrap);
            }

            instanceRow.innerHTML = "";
            instanceRow.appendChild(card);

            syncWordPressInstanceSummary(select);
            select.addEventListener("change", function () {
                enhanceWordPressOptionData(select);
                syncWordPressInstanceSummary(select);
            });
        }

        if (body && titleInput && pathInput && passwordInput && installButton && !body.querySelector(".cpanel-wp-create")) {
            const createWrap = document.createElement("div");
            createWrap.className = "cpanel-wp-create";
            const createSourceRow = titleInput.closest(".row");

            const createHeader = document.createElement("div");
            createHeader.className = "cpanel-wp-create__header";
            createHeader.innerHTML = '<div><h5>Create New WordPress</h5></div>';

            if (preview) {
                const headerText = createHeader.querySelector("div");
                headerText.appendChild(preview);
            }

            const grid = document.createElement("div");
            grid.className = "cpanel-wp-create__grid";

            function wrapField(input, labelText, extraClass) {
                const field = document.createElement("div");
                field.className = "cpanel-wp-field" + (extraClass ? " " + extraClass : "");
                const label = document.createElement("label");
                label.setAttribute("for", input.id);
                label.textContent = labelText;
                field.appendChild(label);
                field.appendChild(input);
                return field;
            }

            titleInput.setAttribute("placeholder", "My New Website");
            pathInput.setAttribute("placeholder", "e.g. blog");
            passwordInput.setAttribute("placeholder", "Admin Password");
            installButton.classList.remove("btn-default");
            installButton.classList.add("cpanel-wp-install-btn");

            const addTile = document.createElement("div");
            addTile.className = "cpanel-wp-create__add";
            addTile.innerHTML = '<i class="fas fa-plus"></i><span>Add New Site</span>';
            grid.appendChild(addTile);

            grid.appendChild(wrapField(titleInput, "Website Title"));
            grid.appendChild(wrapField(pathInput, "Path (optional)"));

            const emailField = document.createElement("div");
            emailField.className = "cpanel-wp-field";
            emailField.innerHTML =
                '<label>Admin Email</label>' +
                '<input type="text" class="form-control" value="' + escapeHtml("admin@" + wpDomain) + '" readonly>';
            grid.appendChild(emailField);

            grid.appendChild(wrapField(passwordInput, "Admin Password", "cpanel-wp-field--password"));

            const submitWrap = document.createElement("div");
            submitWrap.className = "cpanel-wp-field cpanel-wp-field--submit";
            submitWrap.appendChild(installButton);
            grid.appendChild(submitWrap);

            createWrap.appendChild(createHeader);

            if (installResultRow) {
                createWrap.appendChild(installResultRow);
            }

            createWrap.appendChild(grid);
            body.appendChild(createWrap);

            if (createSourceRow) {
                createSourceRow.style.display = "none";
            }
        }
    }

    function decoratePanelHeader(panel, iconClass, subtitleText) {
        if (!panel) {
            return;
        }

        const header = panel.querySelector(".card-header");
        const title = header ? header.querySelector("h3") : null;

        if (!header || !title || header.querySelector(".cpanel-module-heading")) {
            return;
        }

        const wrap = document.createElement("div");
        wrap.className = "cpanel-module-heading";

        const icon = document.createElement("span");
        icon.className = "cpanel-module-heading__icon";
        icon.innerHTML = '<i class="' + iconClass + '"></i>';

        const copy = document.createElement("div");
        copy.className = "cpanel-module-heading__copy";

        const subtitle = document.createElement("p");
        subtitle.className = "cpanel-module-heading__subtitle";
        subtitle.textContent = subtitleText;

        copy.appendChild(title);
        copy.appendChild(subtitle);
        wrap.appendChild(icon);
        wrap.appendChild(copy);

        header.innerHTML = "";
        header.appendChild(wrap);
    }

    function initCpanelUtilityPanels() {
        const quickShortcuts = document.getElementById("cPanelQuickShortcutsPanel");
        const quickEmail = document.getElementById("cPanelQuickEmailPanel");

        if (quickShortcuts) {
            quickShortcuts.classList.add("cpanel-tools-panel");
            decoratePanelHeader(
                quickShortcuts,
                "fas fa-bolt",
                "Manage your hosting account with ease"
            );

            const body = quickShortcuts.querySelector(".card-body");
            const links = Array.from(quickShortcuts.querySelectorAll(".cpanel-feature-row a"));
            const serviceId = new URLSearchParams(window.location.search).get("id") || "";
            const toolMap = {
                "Email Accounts": { icon: "far fa-envelope", app: "Email_Accounts" },
                "Forwarders": { icon: "fas fa-arrow-right", app: "Email_Forwarders" },
                "Autoresponders": { icon: "far fa-comment", app: "Email_AutoResponders" },
                "File Manager": { icon: "far fa-folder", app: "FileManager_Home" },
                "Domains": { icon: "fas fa-globe", app: "Domains_domains" },
                "Backup": { icon: "fas fa-cloud-upload-alt", app: "Backups_Home" },
                "MySQL® Databases": { icon: "fas fa-database", app: "Database_MySQL" },
                "Cron Jobs": { icon: "far fa-clock", app: "Cron_Home" },
                "phpMyAdmin": { icon: "fas fa-terminal", app: "Database_phpMyAdmin" },
                "Awstats": { icon: "fas fa-chart-bar", app: "Stats_AWStats" },
                "Web Disk": { icon: "far fa-hdd", app: "WebDisk_Main" },
                "FTP Accounts": { icon: "fas fa-user-friends", app: "Ftp_Accounts" }
            };

            const toolOrder = [
                "Email Accounts",
                "Forwarders",
                "Autoresponders",
                "File Manager",
                "Domains",
                "Backup",
                "MySQL® Databases",
                "Cron Jobs",
                "phpMyAdmin",
                "Awstats",
                "Web Disk",
                "FTP Accounts"
            ];

            const existingLinks = {};
            links.forEach(function (link) {
                existingLinks[link.textContent.trim()] = link;
            });

            if (body && !body.querySelector(".cpanel-tools-grid")) {
                const grid = document.createElement("div");
                grid.className = "cpanel-tools-grid";

                toolOrder.forEach(function (label) {
                    const link = existingLinks[label];
                    const tool = toolMap[label] || { icon: "fas fa-link" };
                    const href = link
                        ? link.href
                        : "clientarea.php?action=productdetails&id=" + encodeURIComponent(serviceId) + "&dosinglesignon=1&app=" + encodeURIComponent(tool.app || "");

                    if (!href) {
                        return;
                    }

                    const tile = document.createElement("a");
                    tile.href = href;
                    tile.target = "_blank";
                    tile.className = "cpanel-tools-tile";
                    tile.innerHTML =
                        '<span class="cpanel-tools-tile__icon"><i class="' + tool.icon + '"></i></span>' +
                        '<span class="cpanel-tools-tile__label">' + escapeHtml(label) + '</span>' +
                        '<span class="cpanel-tools-tile__arrow"><i class="fas fa-chevron-right"></i></span>';
                    grid.appendChild(tile);
                });

                const help = document.createElement("div");
                help.className = "cpanel-tools-help";
                help.innerHTML =
                    '<div class="cpanel-tools-help__copy">' +
                    '<span><strong>Need help?</strong></span>' +
                    '<span>Check our <span class="cpanel-tools-help__accent">documentation</span> or contact <span class="cpanel-tools-help__accent">support</span></span>' +
                    '</div>' +
                    '<span class="cpanel-tools-help__link">View Docs <i class="fas fa-external-link-alt"></i></span>';

                body.innerHTML = "";
                body.appendChild(grid);
                body.appendChild(help);
            }
        }

        if (quickEmail) {
            quickEmail.classList.add("cpanel-email-panel");
            const emailTitle = quickEmail.querySelector(".card-header h3");
            if (emailTitle) {
                emailTitle.textContent = "Create Email Account";
            }
            decoratePanelHeader(
                quickEmail,
                "far fa-envelope",
                "Set up a new email inbox for your domain"
            );

            const body = quickEmail.querySelector(".card-body");
            const form = quickEmail.querySelector("#frmCreateEmailAccount");
            const prefixInput = quickEmail.querySelector("#cpanel-email-prefix");
            const passwordInput = quickEmail.querySelector("#cpanel-email-password");
            const submitBtn = quickEmail.querySelector('button[type="submit"]');
            const addonText = quickEmail.querySelector(".input-group-text");
            const row = quickEmail.querySelector(".row");

            if (body) {
                body.classList.add("cpanel-email-panel__body");
            }

            if (form && !form.classList.contains("cpanel-email-form")) {
                form.classList.add("cpanel-email-form");
            }

            if (row) {
                row.classList.add("cpanel-email-form__grid");
                const cols = row.children;
                if (cols[0]) {
                    cols[0].classList.remove("col-md-6");
                    cols[0].classList.add("col-md-12");
                    cols[0].classList.add("cpanel-email-form__user");
                }
                if (cols[1]) {
                    cols[1].classList.add("cpanel-email-form__password");
                }
                if (cols[2]) {
                    cols[2].classList.add("cpanel-email-form__action");
                }
            }

            if (prefixInput) {
                prefixInput.setAttribute("placeholder", "Username");
            }

            if (passwordInput) {
                passwordInput.setAttribute("placeholder", "Password");

                if (!passwordInput.parentElement.classList.contains("cpanel-email-form__password-wrap")) {
                    const wrap = document.createElement("div");
                    wrap.className = "cpanel-email-form__password-wrap";
                    passwordInput.parentNode.insertBefore(wrap, passwordInput);
                    wrap.appendChild(passwordInput);

                    const eye = document.createElement("button");
                    eye.type = "button";
                    eye.className = "cpanel-email-form__eye";
                    eye.setAttribute("aria-label", "Toggle password visibility");
                    eye.innerHTML = '<i class="far fa-eye"></i>';
                    eye.addEventListener("click", function () {
                        const nextType = passwordInput.getAttribute("type") === "password" ? "text" : "password";
                        passwordInput.setAttribute("type", nextType);
                        eye.classList.toggle("is-active", nextType === "text");
                    });
                    wrap.appendChild(eye);
                }
            }

            if (submitBtn) {
                submitBtn.classList.remove("btn-primary", "btn-block");
                submitBtn.classList.add("cpanel-email-form__submit");
                submitBtn.innerHTML = '<i class="fas fa-plus"></i><span>Create Account</span>';
            }

            if (addonText) {
                addonText.parentElement.classList.add("cpanel-email-form__suffix");
            }
        }
    }

    function initPagePreloader() {
        const body = document.body;
        const preloader = document.getElementById("dashboardPreloader");
        const progressBar = preloader ? preloader.querySelector("[data-preloader-progress]") : null;
        const progressLabel = preloader ? preloader.querySelector("[data-preloader-percent]") : null;

        if (!body || !preloader) {
            return;
        }

        const isOrderFocusPage = body.classList.contains("is-order-focus-page");
        let hidden = false;
        let progressValue = 0;
        let progressTimer = null;

        function setProgress(value) {
            const normalized = Math.max(0, Math.min(100, value));

            if (progressBar) {
                progressBar.style.width = normalized + "%";
            }

            if (progressLabel) {
                progressLabel.textContent = normalized + "%";
            }
        }

        function stopProgress() {
            if (progressTimer) {
                window.clearInterval(progressTimer);
                progressTimer = null;
            }
        }

        const hidePreloader = function () {
            if (hidden) {
                return;
            }

            hidden = true;
            stopProgress();
            progressValue = 100;
            setProgress(progressValue);
            preloader.classList.add("is-hidden");
            body.classList.remove("dashboard-preload-pending");

            window.setTimeout(function () {
                if (preloader.parentNode) {
                    preloader.parentNode.removeChild(preloader);
                }
            }, 700);
        };

        setProgress(progressValue);

        progressTimer = window.setInterval(function () {
            if (hidden) {
                stopProgress();
                return;
            }

            progressValue = Math.min(94, progressValue + (progressValue < 52 ? 7 : progressValue < 78 ? 4 : 2));
            setProgress(progressValue);
        }, 90);

        window.setTimeout(hidePreloader, isOrderFocusPage ? 260 : 1350);
        window.addEventListener("load", hidePreloader, { once: true });
    }

    function initDomainDetailsInteractions() {
        const tabsRoot = document.querySelector("[data-domain-details-tabs]");

        if (!tabsRoot) {
            return;
        }

        const panes = Array.from(tabsRoot.querySelectorAll(".tab-pane[id]"));
        const tabLinks = Array.from(document.querySelectorAll(".tabControlLink[href^='#tab']"));
        const actionMenu = document.querySelector("[data-domain-actions-menu]");
        const actionToggle = actionMenu ? actionMenu.querySelector("[data-domain-actions-toggle]") : null;

        function closeActionMenu() {
            if (!actionMenu || !actionToggle) {
                return;
            }

            actionMenu.classList.remove("is-open");
            actionToggle.setAttribute("aria-expanded", "false");
        }

        function setActivePane(hash, syncHash) {
            const targetId = (hash || "").replace(/^#/, "");
            const targetPane = panes.find(function (pane) {
                return pane.id === targetId;
            }) || panes[0];

            if (!targetPane) {
                return;
            }

            panes.forEach(function (pane) {
                const isActive = pane === targetPane;
                pane.classList.toggle("show", isActive);
                pane.classList.toggle("active", isActive);
            });

            tabLinks.forEach(function (link) {
                const linkTarget = link.getAttribute("href");
                link.classList.toggle("is-active", !!linkTarget && linkTarget.replace(/^#/, "") === targetPane.id);
                link.setAttribute("aria-current", link.classList.contains("is-active") ? "page" : "false");
            });

            if (syncHash) {
                if (window.history && window.history.replaceState) {
                    window.history.replaceState(null, "", "#" + targetPane.id);
                } else {
                    window.location.hash = targetPane.id;
                }
            }
        }

        tabLinks.forEach(function (link) {
            link.addEventListener("click", function (event) {
                const target = link.getAttribute("href");

                if (!target || target.charAt(0) !== "#") {
                    return;
                }

                event.preventDefault();
                setActivePane(target, true);
                closeActionMenu();
            });
        });

        if (actionMenu && actionToggle) {
            actionToggle.addEventListener("click", function (event) {
                event.preventDefault();
                event.stopPropagation();
                const shouldOpen = !actionMenu.classList.contains("is-open");
                actionMenu.classList.toggle("is-open", shouldOpen);
                actionToggle.setAttribute("aria-expanded", shouldOpen ? "true" : "false");
            });

            document.addEventListener("click", function (event) {
                if (!actionMenu.contains(event.target)) {
                    closeActionMenu();
                }
            });

            document.addEventListener("keydown", function (event) {
                if (event.key === "Escape") {
                    closeActionMenu();
                }
            });
        }

        setActivePane(window.location.hash || "#tabOverview", false);
    }

    function initAccountDetailsStickyAside() {
        const body = document.body;
        const aside = document.querySelector(".dashboard-account-settings__aside");

        if (!body || !aside || body.getAttribute("data-page-template") !== "clientareadetails") {
            return;
        }

        let lastScrollY = window.scrollY || window.pageYOffset || 0;

        function syncAsideOffset() {
            if (window.innerWidth <= 767) {
                aside.classList.remove("is-scroll-offset");
                lastScrollY = window.scrollY || window.pageYOffset || 0;
                return;
            }

            const currentScrollY = window.scrollY || window.pageYOffset || 0;
            const scrollingDown = currentScrollY > lastScrollY;
            const pastThreshold = currentScrollY > 24;

            aside.classList.toggle("is-scroll-offset", scrollingDown && pastThreshold);
            lastScrollY = currentScrollY;
        }

        syncAsideOffset();
        window.addEventListener("scroll", syncAsideOffset, { passive: true });
        window.addEventListener("resize", syncAsideOffset);
    }

    function initDashboardUi() {
        initThemeSelector();
        initPagePreloader();
        initSidebar();
        initSidebarDropdowns();
        initSidebarUserMenu();
        initSearch();
        hydrateDashboardServices();
        hydrateDashboardInvoices();
        initModuleProductOverview();
        initCpanelWordPress();
        initCpanelUtilityPanels();
        initDomainDetailsInteractions();
        initAccountDetailsStickyAside();
    }

    if (document.readyState === "loading") {
        document.addEventListener("DOMContentLoaded", initDashboardUi);
    } else {
        initDashboardUi();
    }
})();
