document.addEventListener("DOMContentLoaded", function () {
  const searchInput = document.getElementById("serviceSearch");
  const navItems = document.querySelectorAll(".cloud-nav-link[href]");
  const submenuToggles = document.querySelectorAll(".cloud-nav-toggle[data-submenu-target]");
  const themeSwatches = document.querySelectorAll(".cloud-theme-swatch[data-theme]");
  const languageButtons = document.querySelectorAll(".cloud-language-btn[data-lang]");
  const searchRoot = document.querySelector("#main-body");
  const availableThemes = ["green", "blue", "purple"];
  const themeStorageKey = "cloudDashboardTheme";
  const availableLanguages = ["en", "ar"];
  const languageStorageKey = "cloudDashboardLang";
  let searchMarks = [];
  let activeSearchMatch = -1;
  let searchMeta = null;

  const translations = {
    en: {
      brandInfrastructure: "INFRASTRUCTURE",
      navOverview: "Overview",
      navServices: "Services",
      navDomains: "Domains",
      navBilling: "Billing",
      navSupport: "Support",
      navSettings: "Settings",
      myServices: "My Services",
      myDomains: "My Domains",
      orderNewService: "Order New Service",
      serviceUpgrades: "Service Upgrades",
      navPaymentMethods: "Payment Methods",
      navAddFunds: "Add Funds",
      openTicket: "Open Ticket",
      accountDetails: "Account Details",
      userManagement: "User Management",
      contacts: "Contacts",
      emailHistory: "Email History",
      securitySettings: "Security Settings",
      logout: "Logout",
      home: "Home",
      store: "Store",
      searchServices: "Search services...",
      notifications: "Notifications",
      viewAll: "View All",
      supportTickets: "Support Tickets",
      billingAlerts: "Billing Alerts",
      announcements: "Announcements",
      networkStatus: "Network Status",
      signinRequired: "Sign in required",
      newService: "New Service",
      breadcrumbSubtitle: "Cloud Hosting Infrastructure",
      activeProductsServices: "Active products/services",
      activeRegisteredDomains: "Active registered domains",
      unpaidInvoices: "Unpaid invoices",
      openSupportTickets: "Open support tickets",
      monthlySpend: "Monthly Spend",
      bandwidthUsed: "Bandwidth Used",
      uptime30d: "Uptime (30d)",
      plusOneMonth: "+1 this month",
      plus24vsLast: "+$24 vs last",
      of5tb: "of 5TB",
      twoMinDowntime: "2min downtime",
      activeServices: "Active Services",
      service: "Service",
      specs: "Specs",
      status: "Status",
      action: "Action",
      clientService: "Client Service",
      managedService: "Managed Service",
      active: "Active",
      manage: "Manage",
      recentInvoicesNews: "Recent Invoices & News",
      recentInvoices: "Recent Invoices",
      info: "Info",
      newTicket: "New Ticket",
      paid: "Paid",
      open: "Open",
      answered: "Answered",
    },
    ar: {
      brandInfrastructure: "البنية التحتية",
      navOverview: "نظرة عامة",
      navServices: "الخدمات",
      navDomains: "النطاقات",
      navBilling: "الفوترة",
      navSupport: "الدعم",
      navSettings: "الإعدادات",
      myServices: "خدماتي",
      myDomains: "نطاقاتي",
      orderNewService: "طلب خدمة جديدة",
      serviceUpgrades: "ترقيات الخدمات",
      navPaymentMethods: "طرق الدفع",
      navAddFunds: "إضافة رصيد",
      openTicket: "فتح تذكرة",
      accountDetails: "تفاصيل الحساب",
      userManagement: "إدارة المستخدمين",
      contacts: "جهات الاتصال",
      emailHistory: "سجل البريد",
      securitySettings: "إعدادات الأمان",
      logout: "تسجيل الخروج",
      home: "الرئيسية",
      store: "المتجر",
      searchServices: "ابحث في الخدمات...",
      notifications: "الإشعارات",
      viewAll: "عرض الكل",
      supportTickets: "تذاكر الدعم",
      billingAlerts: "تنبيهات الفوترة",
      announcements: "الإعلانات",
      networkStatus: "حالة الشبكة",
      signinRequired: "تسجيل الدخول مطلوب",
      newService: "خدمة جديدة",
      breadcrumbSubtitle: "البنية التحتية للاستضافة السحابية",
      activeProductsServices: "الخدمات/المنتجات النشطة",
      activeRegisteredDomains: "النطاقات النشطة",
      unpaidInvoices: "فواتير غير مدفوعة",
      openSupportTickets: "تذاكر دعم مفتوحة",
      monthlySpend: "الإنفاق الشهري",
      bandwidthUsed: "النطاق المستخدم",
      uptime30d: "وقت التشغيل (30 يوم)",
      plusOneMonth: "+1 هذا الشهر",
      plus24vsLast: "+24$ مقابل السابق",
      of5tb: "من 5 تيرا",
      twoMinDowntime: "دقيقتان توقف",
      activeServices: "الخدمات النشطة",
      service: "الخدمة",
      specs: "المواصفات",
      status: "الحالة",
      action: "الإجراء",
      clientService: "خدمة العميل",
      managedService: "خدمة مُدارة",
      active: "نشط",
      manage: "إدارة",
      recentInvoicesNews: "الفواتير الأخيرة والأخبار",
      recentInvoices: "الفواتير الأخيرة",
      info: "معلومات",
      newTicket: "تذكرة جديدة",
      paid: "مدفوعة",
      open: "مفتوحة",
      answered: "تم الرد",
    },
  };

  const escapeRegExp = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");

  const clearSearchMarks = () => {
    const marks = document.querySelectorAll("mark.cloud-search-mark");
    marks.forEach((mark) => {
      const parent = mark.parentNode;
      if (!parent) {
        return;
      }
      parent.replaceChild(document.createTextNode(mark.textContent || ""), mark);
      parent.normalize();
    });
    searchMarks = [];
    activeSearchMatch = -1;
  };

  const updateSearchMeta = () => {
    if (!searchMeta) {
      return;
    }

    if (!searchInput || !searchInput.value.trim()) {
      searchMeta.textContent = "";
      searchInput.classList.remove("search-no-results");
      return;
    }

    if (!searchMarks.length) {
      searchMeta.textContent = "";
      searchInput.classList.add("search-no-results");
      return;
    }

    searchInput.classList.remove("search-no-results");
    searchMeta.textContent = (activeSearchMatch + 1) + " / " + searchMarks.length;
  };

  const setActiveSearchMatch = (targetIndex, shouldScroll) => {
    if (!searchMarks.length) {
      activeSearchMatch = -1;
      updateSearchMeta();
      return;
    }

    const normalizedIndex = ((targetIndex % searchMarks.length) + searchMarks.length) % searchMarks.length;
    searchMarks.forEach((mark) => mark.classList.remove("active"));
    activeSearchMatch = normalizedIndex;
    const activeMark = searchMarks[normalizedIndex];
    activeMark.classList.add("active");

    if (shouldScroll) {
      activeMark.scrollIntoView({
        behavior: "smooth",
        block: "center",
        inline: "nearest",
      });
    }

    updateSearchMeta();
  };

  const highlightSearchTerm = (query) => {
    clearSearchMarks();
    if (!searchRoot || !query) {
      updateSearchMeta();
      return;
    }

    const regex = new RegExp("(" + escapeRegExp(query) + ")", "gi");
    const lowerQuery = query.toLowerCase();
    const walker = document.createTreeWalker(searchRoot, NodeFilter.SHOW_TEXT, {
      acceptNode: (node) => {
        const parent = node.parentElement;
        if (!parent) {
          return NodeFilter.FILTER_REJECT;
        }
        if (
          parent.closest(".sidebar, .cloud-topbar, .modal, script, style, noscript") ||
          ["SCRIPT", "STYLE", "NOSCRIPT", "TEXTAREA", "INPUT", "SELECT", "BUTTON"].includes(parent.tagName)
        ) {
          return NodeFilter.FILTER_REJECT;
        }
        if (!node.nodeValue || !node.nodeValue.trim()) {
          return NodeFilter.FILTER_REJECT;
        }
        return node.nodeValue.toLowerCase().includes(lowerQuery) ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT;
      },
    });

    const textNodes = [];
    let node;
    while ((node = walker.nextNode())) {
      textNodes.push(node);
    }

    textNodes.forEach((textNode) => {
      const text = textNode.nodeValue || "";
      const fragment = document.createDocumentFragment();
      let lastIndex = 0;

      text.replace(regex, (match, _group, offset) => {
        if (offset > lastIndex) {
          fragment.appendChild(document.createTextNode(text.slice(lastIndex, offset)));
        }
        const mark = document.createElement("mark");
        mark.className = "cloud-search-mark";
        mark.textContent = match;
        fragment.appendChild(mark);
        searchMarks.push(mark);
        lastIndex = offset + match.length;
        return match;
      });

      if (lastIndex < text.length) {
        fragment.appendChild(document.createTextNode(text.slice(lastIndex)));
      }

      if (textNode.parentNode) {
        textNode.parentNode.replaceChild(fragment, textNode);
      }
    });

    if (searchMarks.length) {
      setActiveSearchMatch(0, true);
    } else {
      updateSearchMeta();
    }
  };

  if (searchInput) {
    const searchWrap = searchInput.closest(".cloud-search-wrap");
    if (searchWrap) {
      searchMeta = document.createElement("span");
      searchMeta.className = "cloud-search-meta";
      searchWrap.appendChild(searchMeta);
    }

    searchInput.addEventListener("input", function () {
      const query = this.value.trim();
      highlightSearchTerm(query);
    });

    searchInput.addEventListener("keydown", function (event) {
      if (event.key !== "Enter" || !searchMarks.length) {
        return;
      }
      event.preventDefault();
      setActiveSearchMatch(activeSearchMatch + (event.shiftKey ? -1 : 1), true);
    });

    searchInput.addEventListener("blur", function () {
      if (!this.value.trim()) {
        clearSearchMarks();
        updateSearchMeta();
      }
    });
  }

  if (languageButtons.length) {
    const applyLanguage = (language) => {
      const normalizedLanguage = availableLanguages.includes(language) ? language : "en";
      const dictionary = translations[normalizedLanguage] || translations.en;

      document.documentElement.setAttribute("lang", normalizedLanguage);
      document.documentElement.setAttribute("dir", "ltr");
      document.body.setAttribute("data-language", normalizedLanguage);

      document.querySelectorAll("[data-i18n]").forEach((element) => {
        const key = element.getAttribute("data-i18n");
        if (key && dictionary[key]) {
          element.textContent = dictionary[key];
        }
      });

      document.querySelectorAll("[data-i18n-placeholder]").forEach((element) => {
        const key = element.getAttribute("data-i18n-placeholder");
        if (key && dictionary[key]) {
          element.setAttribute("placeholder", dictionary[key]);
        }
      });

      languageButtons.forEach((button) => {
        button.classList.toggle("active", button.getAttribute("data-lang") === normalizedLanguage);
      });

      try {
        window.localStorage.setItem(languageStorageKey, normalizedLanguage);
      } catch (_error) {
        // Ignore storage access errors.
      }
    };

    let savedLanguage = "";
    try {
      savedLanguage = window.localStorage.getItem(languageStorageKey) || "";
    } catch (_error) {
      savedLanguage = "";
    }

    const documentLang = (document.documentElement.getAttribute("lang") || "").toLowerCase();
    const languageFromDocument = documentLang.startsWith("ar") ? "ar" : "en";
    const initialLanguage = savedLanguage || languageFromDocument || document.body.getAttribute("data-language") || "en";
    applyLanguage(initialLanguage);

    languageButtons.forEach((button) => {
      button.addEventListener("click", function () {
        const selectedLanguage = this.getAttribute("data-lang") || "en";
        const targetLanguageParam = selectedLanguage === "ar" ? "arabic" : "english";

        try {
          window.localStorage.setItem(languageStorageKey, selectedLanguage);
        } catch (_error) {
          // Ignore storage access errors.
        }

        try {
          const currentUrl = new URL(window.location.href);
          currentUrl.searchParams.set("language", targetLanguageParam);
          window.location.replace(currentUrl.toString());
          return;
        } catch (_error) {
          // Fallback for any URL parsing edge case.
        }

        const separator = window.location.href.indexOf("?") === -1 ? "?" : "&";
        window.location.replace(window.location.href + separator + "language=" + targetLanguageParam);
      });
    });
  }

  if (themeSwatches.length) {
    const applyTheme = (theme) => {
      const normalizedTheme = availableThemes.includes(theme) ? theme : "green";
      if (window.HostiqueBranding && typeof window.HostiqueBranding.applyThemeBranding === "function") {
        window.HostiqueBranding.applyThemeBranding(normalizedTheme);
      }
      document.body.setAttribute("data-theme", normalizedTheme);
      themeSwatches.forEach((swatch) => {
        swatch.classList.toggle("active", swatch.getAttribute("data-theme") === normalizedTheme);
      });
      try {
        window.localStorage.setItem(themeStorageKey, normalizedTheme);
      } catch (_error) {
        // Ignore storage access errors (private mode/security restrictions).
      }
    };

    let savedTheme = "";
    try {
      savedTheme = window.localStorage.getItem(themeStorageKey) || "";
    } catch (_error) {
      savedTheme = "";
    }

    const initialTheme = savedTheme || document.body.getAttribute("data-theme") || "green";
    applyTheme(initialTheme);

    themeSwatches.forEach((swatch) => {
      swatch.addEventListener("click", function () {
        applyTheme(this.getAttribute("data-theme") || "green");
      });
    });
  }

  submenuToggles.forEach((toggle) => {
    const targetId = toggle.getAttribute("data-submenu-target");
    const submenu = document.getElementById(targetId);
    const navGroup = toggle.closest(".cloud-nav-group");
    if (!submenu || !navGroup) {
      return;
    }

    if (submenu.classList.contains("show")) {
      navGroup.classList.add("open");
    }

    toggle.addEventListener("click", function () {
      const isOpen = submenu.classList.contains("show");
      submenuToggles.forEach((otherToggle) => {
        const otherId = otherToggle.getAttribute("data-submenu-target");
        const otherSubmenu = document.getElementById(otherId);
        const otherGroup = otherToggle.closest(".cloud-nav-group");
        if (!otherSubmenu || !otherGroup || otherSubmenu === submenu) {
          return;
        }
        otherSubmenu.classList.remove("show");
        otherGroup.classList.remove("open");
      });

      submenu.classList.toggle("show", !isOpen);
      navGroup.classList.toggle("open", !isOpen);
    });
  });

  navItems.forEach((item) => {
    item.addEventListener("click", function () {
      navItems.forEach((nav) => nav.classList.remove("active"));
      this.classList.add("active");
    });
  });
});
