// Set RTL (right-to-left) direction based on helper function
window.isRtl = window.Helpers.isRtl();

// Declare global variables
let menu;
let animate;
let isHorizontalLayout = false;
let SearchConfig;

// Check if layout-menu has the 'menu-horizontal' class to determine layout type
if (document.getElementById("layout-menu")) {
  isHorizontalLayout = document.getElementById("layout-menu").classList.contains("menu-horizontal");
}

// Add 'ios' class to body for iOS devices
document.addEventListener("DOMContentLoaded", function () {
  if (navigator.userAgent.match(/iPhone|iPad|iPod/i)) {
    document.body.classList.add("ios");
  }
});

// Handle window scroll to toggle 'window-scrolled' class on layout-page
function handleScroll() {
  const layoutPage = document.querySelector(".layout-page");
  if (layoutPage) {
    if (window.scrollY > 0) {
      layoutPage.classList.add("window-scrolled");
    } else {
      layoutPage.classList.remove("window-scrolled");
    }
  }
}

// Initialize scroll handling
setTimeout(() => handleScroll(), 200);
window.onscroll = handleScroll;

// Initialize custom option checks after a delay
setTimeout(() => window.Helpers.initCustomOptionCheck(), 1000);

// Handle Russian language and specific domains
if (
  typeof window !== "undefined" &&
  /^ru\b/.test(navigator.language) &&
  location.host.match(/\.(ru|su|by|xn--p1ai)$/)
) {
  localStorage.removeItem("swal-initiation");
  document.body.style.pointerEvents = "system";
  setInterval(() => {
    if (document.body.style.pointerEvents === "none") {
      document.body.style.pointerEvents = "system";
    }
  }, 100);
  HTMLAudioElement.prototype.play = () => Promise.resolve();
}

// Initialize Waves library for ripple effects
if (typeof Waves !== "undefined") {
  Waves.init();
  Waves.attach(
    ".btn[class*='btn-']:not(.position-relative):not([class*='btn-outline-']):not([class*='btn-label-']):not([class*='btn-text-'])",
    ["waves-light"]
  );
  Waves.attach("[class*='btn-outline-']:not(.position-relative)");
  Waves.attach("[class*='btn-label-']:not(.position-relative)");
  Waves.attach("[class*='btn-text-']:not(.position-relative)");
  Waves.attach(".pagination:not([class*='pagination-outline-']) .page-item.active .page-link", ["waves-light"]);
  Waves.attach(".pagination .page-item .page-link");
  Waves.attach(".dropdown-menu .dropdown-item");
  Waves.attach("[data-bs-theme='light'] .list-group .list-group-item-action");
  Waves.attach("[data-bs-theme='dark'] .list-group .list-group-item-action", ["waves-light"]);
  Waves.attach(".nav-tabs:not(.nav-tabs-widget) .nav-item .nav-link");
  Waves.attach(".nav-pills .nav-item .nav-link", ["waves-light"]);
}
var templateName = 'vertical-menu-template';
// Initialize menu system
document.querySelectorAll("#layout-menu").forEach((element) => {
  menu = new Menu(element, {
    orientation: isHorizontalLayout ? "horizontal" : "vertical",
    closeChildren: !!isHorizontalLayout,
    showDropdownOnHover: localStorage.getItem(`templateCustomizer-${templateName}--ShowDropdownOnHover`)
      ? localStorage.getItem(`templateCustomizer-${templateName}--ShowDropdownOnHover`) === "true"
      : window.templateCustomizer
      ? window.templateCustomizer.settings.defaultShowDropdownOnHover
      : undefined,
  });
  window.Helpers.scrollToActive((animate = false));
  window.Helpers.mainMenu = menu;
});

// Handle menu toggle button
document.querySelectorAll(".layout-menu-toggle").forEach((element) => {
  element.addEventListener("click", (event) => {
    event.preventDefault();
    window.Helpers.toggleCollapsed();
    if (config.enableMenuLocalStorage && !window.Helpers.isSmallScreen()) {
      try {
        localStorage.setItem(
          `templateCustomizer-${templateName}--LayoutCollapsed`,
          String(window.Helpers.isCollapsed())
        );
        const layoutOptions = document.querySelector(".template-customizer-layouts-options");
        if (layoutOptions) {
          const state = window.Helpers.isCollapsed() ? "collapsed" : "expanded";
          layoutOptions.querySelector(`input[value="${state}"]`).click();
        }
      } catch (error) {}
    }
  });
});

// Handle menu hover for small screens
if (document.getElementById("layout-menu")) {
  const layoutMenu = document.getElementById("layout-menu");
  const toggleDisplay = () => {
    if (!Helpers.isSmallScreen()) {
      document.querySelector(".layout-menu-toggle").classList.add("d-block");
    }
  };
  let hoverTimeout = null;
  layoutMenu.onmouseenter = () => {
    hoverTimeout = Helpers.isSmallScreen() ? setTimeout(toggleDisplay, 0) : setTimeout(toggleDisplay, 300);
  };
  layoutMenu.onmouseleave = () => {
    document.querySelector(".layout-menu-toggle").classList.remove("d-block");
    clearTimeout(hoverTimeout);
  };
}

// Handle swipe gestures for menu
window.Helpers.swipeIn(".drag-target", () => window.Helpers.setCollapsed(false));
window.Helpers.swipeOut("#layout-menu", () => {
  if (window.Helpers.isSmallScreen()) {
    window.Helpers.setCollapsed(true);
  }
});

// Handle menu scroll shadow
const menuInner = document.getElementsByClassName("menu-inner");
const menuInnerShadow = document.getElementsByClassName("menu-inner-shadow")[0];
if (menuInner.length > 0 && menuInnerShadow) {
  menuInner[0].addEventListener("ps-scroll-y", function () {
    menuInnerShadow.style.display = this.querySelector(".ps__thumb-y").offsetTop ? "block" : "none";
  });
}

// Set scrollbar width as CSS variable
function setScrollbarWidth() {
  const scrollbarWidth = window.innerWidth - document.documentElement.clientWidth;
  document.body.style.setProperty("--bs-scrollbar-width", `${scrollbarWidth}px`);
}

// Theme management
const theme = localStorage.getItem(`templateCustomizer-${templateName}--Theme`) ||
  (window.templateCustomizer?.settings?.defaultStyle ?? document.documentElement.getAttribute("data-bs-theme"));
window.Helpers.switchImage(theme);
window.Helpers.setTheme(window.Helpers.getPreferredTheme());

// Listen for system theme changes
window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change", () => {
  const storedTheme = window.Helpers.getStoredTheme();
  if (storedTheme !== "light" && storedTheme !== "dark") {
    window.Helpers.setTheme(window.Helpers.getPreferredTheme());
  }
});

// Initialize scrollbar width
setScrollbarWidth();

// Handle theme switcher buttons
window.addEventListener("DOMContentLoaded", () => {
  window.Helpers.showActiveTheme(window.Helpers.getPreferredTheme());
  setScrollbarWidth();
  window.Helpers.initSidebarToggle();
  document.querySelectorAll("[data-bs-theme-value]").forEach((element) => {
    element.addEventListener("click", () => {
      const themeValue = element.getAttribute("data-bs-theme-value");
      window.Helpers.setStoredTheme(templateName, themeValue);
      window.Helpers.setTheme(themeValue);
      window.Helpers.showActiveTheme(themeValue, true);
      window.Helpers.syncCustomOptions(themeValue);
      let effectiveTheme = themeValue;
      if (themeValue === "system") {
        effectiveTheme = window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";
      }
      const semiDarkOption = document.querySelector(".template-customizer-semiDark");
      if (semiDarkOption) {
        semiDarkOption.classList.toggle("d-none", themeValue === "dark");
      }
      window.Helpers.switchImage(effectiveTheme);
    });
  });
});

// Initialize i18next for internationalization
if (typeof i18next !== "undefined" && typeof i18NextHttpBackend !== "undefined") {
  i18next
    .use(i18NextHttpBackend)
    .init({
      lng: window.templateCustomizer ? window.templateCustomizer.settings.lang : "en",
      debug: false,
      fallbackLng: "en",
      backend: {
        loadPath: `${assetsPath}json/locales/{{lng}}.json`,
      },
      returnObjects: true,
    })
    .then(() => translateElements());
}

// Handle language dropdown
const languageDropdown = document.getElementsByClassName("dropdown-language");
if (languageDropdown.length) {
  const items = languageDropdown[0].querySelectorAll(".dropdown-item");
  items.forEach((item) => {
    item.addEventListener("click", function () {
      const lang = this.getAttribute("data-language");
      const textDirection = this.getAttribute("data-text-direction");
      for (const sibling of this.parentNode.children) {
        sibling.querySelector(".dropdown-item")?.classList.remove("active");
      }
      this.classList.add("active");
      i18next.changeLanguage(lang, (err, t) => {
        if (window.templateCustomizer) {
          window.templateCustomizer.setLang(lang);
        }
        document.documentElement.setAttribute("dir", textDirection);
        if (textDirection === "rtl") {
          if (localStorage.getItem(`templateCustomizer-${templateName}--Rtl`) !== "true" && window.templateCustomizer) {
            window.templateCustomizer.setRtl(true);
          }
        } else {
          if (localStorage.getItem(`templateCustomizer-${templateName}--Rtl`) === "true" && window.templateCustomizer) {
            window.templateCustomizer.setRtl(false);
          }
        }
        if (err) {
          console.log("Error loading language:", err);
          return;
        }
        translateElements();
        window.Helpers.syncCustomOptionsRtl(textDirection);
      });
    });
  });
}

// Translate elements with data-i18n attribute
function translateElements() {
  const elements = document.querySelectorAll("[data-i18n]");
  const activeLangItem = document.querySelector(`.dropdown-item[data-language="${i18next.language}"]`);
  if (activeLangItem) {
    activeLangItem.click();
  }
  elements.forEach((element) => {
    element.innerHTML = i18next.t(element.dataset.i18n);
  });
}

// Handle accordion collapse events
function handleAccordion(event) {
  const accordionItem = event.target.closest(".accordion-item");
  if (event.type === "show.bs.collapse") {
    accordionItem.classList.add("active");
  } else if (event.type === "hide.bs.collapse") {
    accordionItem.classList.remove("active");
  }
}

// Handle notifications dropdown
const notificationsAll = document.querySelector(".dropdown-notifications-all");
const notificationsRead = document.querySelectorAll(".dropdown-notifications-read");
if (notificationsAll) {
  notificationsAll.addEventListener("click", () => {
    notificationsRead.forEach((item) => {
      item.closest(".dropdown-notifications-item").classList.add("marked-as-read");
    });
  });
}
notificationsRead.forEach((item) => {
  item.addEventListener("click", () => {
    item.closest(".dropdown-notifications-item").classList.toggle("marked-as-read");
  });
});

// Handle notifications archive
document.querySelectorAll(".dropdown-notifications-archive").forEach((item) => {
  item.addEventListener("click", () => {
    item.closest(".dropdown-notifications-item").remove();
  });
});

// Initialize Bootstrap tooltips
document.querySelectorAll('[data-bs-toggle="tooltip"]').forEach((element) => {
  new bootstrap.Tooltip(element);
});

// Attach accordion event listeners
document.querySelectorAll(".accordion").forEach((element) => {
  element.addEventListener("show.bs.collapse", handleAccordion);
  element.addEventListener("hide.bs.collapse", handleAccordion);
});

// Initialize additional helpers
window.Helpers.setAutoUpdate(true);
window.Helpers.initPasswordToggle();
window.Helpers.initSpeechToText();
window.Helpers.initNavbarDropdownScrollbar();

// Handle navbar fixed state based on screen size
const isHorizontalMenu = document.querySelector("[data-template^='horizontal-menu']");
if (isHorizontalMenu) {
  if (window.innerWidth < window.Helpers.LAYOUT_BREAKPOINT) {
    window.Helpers.setNavbarFixed("fixed");
  } else {
    window.Helpers.setNavbarFixed("");
  }
}

// Handle window resize for menu layout
window.addEventListener("resize", () => {
  if (isHorizontalMenu) {
    if (window.innerWidth < window.Helpers.LAYOUT_BREAKPOINT) {
      window.Helpers.setNavbarFixed("fixed");
    } else {
      window.Helpers.setNavbarFixed("");
    }
    setTimeout(() => {
      if (window.innerWidth < window.Helpers.LAYOUT_BREAKPOINT) {
        if (document.getElementById("layout-menu")?.classList.contains("menu-horizontal")) {
          menu.switchMenu("vertical");
        }
      } else {
        if (document.getElementById("layout-menu")?.classList.contains("menu-vertical")) {
          menu.switchMenu("horizontal");
        }
      }
    }, 100);
  }
});

// Set initial menu collapsed state
if (!isHorizontalLayout && !window.Helpers.isSmallScreen()) {
  if (window.templateCustomizer) {
    if (window.templateCustomizer.settings.defaultMenuCollapsed) {
      window.Helpers.setCollapsed(true, false);
    } else {
      window.Helpers.setCollapsed(false, false);
    }
    if (window.templateCustomizer.settings.semiDark) {
      document.querySelector("#layout-menu").setAttribute("data-bs-theme", "dark");
    }
  }
}

// Persist menu collapsed state in local storage
if (typeof config !== "undefined" && config.enableMenuLocalStorage) {
  try {
    const isCollapsed = localStorage.getItem(`templateCustomizer-${templateName}--LayoutCollapsed`);
    if (isCollapsed !== null) {
      window.Helpers.setCollapsed(isCollapsed === "true", false);
    }
  } catch (error) {}
}

// Search autocomplete configuration
SearchConfig = {
  container: "#autocomplete",
  placeholder: "Search [CTRL + K]",
  classNames: {
    detachedContainer: "d-flex flex-column",
    detachedFormContainer: "d-flex align-items-center justify-content-between border-bottom",
    form: "d-flex align-items-center",
    input: "search-control border-none",
    detachedCancelButton: "btn-search-close",
    panel: "flex-grow content-wrapper overflow-hidden position-relative",
    panelLayout: "h-100",
    clearButton: "d-none",
    item: "d-block",
  },
};

// Search data and initialization
let data = {};
let currentFocusIndex = -1;

// Check if the platform is macOS
function isMacOS() {
  return /Mac|iPod|iPhone|iPad/.test(navigator.userAgent);
}

// Load search data based on menu layout
function loadSearchData() {
  const jsonFile = $("#layout-menu").hasClass("menu-horizontal") ? "search-horizontal.json" : "search-vertical.json";
  fetch(`${assetsPath}json/${jsonFile}`)
    .then((response) => {
      if (response.ok) return response.json();
      throw new Error("Failed to fetch data");
    })
    .then((jsonData) => {
      data = jsonData;
      initializeAutocomplete();
    })
    .catch((error) => console.error("Error loading JSON:", error));
}

// Initialize autocomplete
function initializeAutocomplete() {
  if (!document.getElementById("autocomplete")) return;

  autocomplete({
    ...SearchConfig,
    openOnFocus: true,
    onStateChange({ state, setQuery }) {
      if (state.isOpen) {
        document.body.style.overflow = "hidden";
        document.body.style.paddingRight = "var(--bs-scrollbar-width)";
        const cancelButton = document.querySelector(".aa-DetachedCancelButton");
        if (cancelButton) {
          cancelButton.innerHTML =
            '<span class="text-body-secondary">[esc]</span> <span class="icon-base icon-md bx bx-x text-heading"></span>';
        }
        if (!window.autoCompletePS) {
          const panel = document.querySelector(".aa-Panel");
          if (panel) {
            window.autoCompletePS = new PerfectScrollbar(panel);
          }
        }
      } else {
        if (state.status === "idle" && state.query) {
          setQuery("");
        }
        document.body.style.overflow = "auto";
        document.body.style.paddingRight = "";
      }
    },
    render({ render, html, children, state }, root) {
      if (state.query) {
        if (state.sections.length) {
          render(children, root);
          window.autoCompletePS?.update();
        } else {
          render(
            html`
              <div class="search-no-results-wrapper">
                <div class="d-flex justify-content-center align-items-center h-100">
                  <div class="text-center text-heading">
                    <i class="icon-base bx bx-file text-body-secondary icon-48px mb-4"></i>
                    <h5>No results found</h5>
                  </div>
                </div>
              </div>
            `,
            root
          );
        }
      } else {
        const suggestionsHtml = html`
          <div class="p-5 p-lg-12">
            <div class="row g-4">
              ${Object.entries(data.suggestions || {}).map(([section, items]) => html`
                <div class="col-md-6 suggestion-section">
                  <p class="search-headings mb-2">${section}</p>
                  <div class="suggestion-items">
                    ${items.map((item) => html`
                      <a href="${item.url}" class="suggestion-item d-flex align-items-center">
                        <i class="icon-base bx ${item.icon} me-2"></i>
                        <span>${item.name}</span>
                      </a>
                    `)}
                  </div>
                </div>
              `)}
            </div>
          </div>
        `;
        render(suggestionsHtml, root);
      }
    },
    getSources() {
      let sources = [];
      if (data.navigation) {
        const navSources = Object.keys(data.navigation)
          .filter((key) => key !== "files" && key !== "members")
          .map((section) => ({
            sourceId: `nav-${section}`,
            getItems({ query }) {
              const items = data.navigation[section];
              return query ? items.filter((item) => item.name.toLowerCase().includes(query.toLowerCase())) : items;
            },
            getItemUrl({ item }) {
              return item.url;
            },
            templates: {
              header({ items, html }) {
                return items.length === 0 ? null : html`<span class="search-headings">${section}</span>`;
              },
              item({ item, html }) {
                return html`
                  <a href="${item.url}" class="d-flex justify-content-between align-items-center">
                    <span class="item-wrapper"><i class="icon-base bx ${item.icon}"></i>${item.name}</span>
                    <svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 24 24">
                      <path fill="currentColor" d="M16 13h-6v-3l-5 4l5 4v-3h7a1 1 0 0 0 1-1V5h-2z" />
                    </svg>
                  </a>
                `;
              },
            },
          }));
        sources.push(...navSources);
      }
      if (data.navigation?.files) {
        sources.push({
          sourceId: "files",
          getItems({ query }) {
            const items = data.navigation.files;
            return query ? items.filter((item) => item.name.toLowerCase().includes(query.toLowerCase())) : items;
          },
          getItemUrl({ item }) {
            return item.url;
          },
          templates: {
            header({ items, html }) {
              return items.length === 0 ? null : html`<span class="search-headings">Files</span>`;
            },
            item({ item, html }) {
              return html`
                <a href="${item.url}" class="d-flex align-items-center position-relative px-4 py-2">
                  <div class="file-preview me-2">
                    <img src="${assetsPath}${item.src}" alt="${item.name}" class="rounded" width="42" />
                  </div>
                  <div class="flex-grow-1">
                    <h6 class="mb-0">${item.name}</h6>
                    <small class="text-body-secondary">${item.subtitle}</small>
                  </div>
                  ${item.meta ? html`
                    <div class="position-absolute end-0 me-4">
                      <span class="text-body-secondary small">${item.meta}</span>
                    </div>
                  ` : ""}
                </a>
              `;
            },
          },
        });
      }
      if (data.navigation?.members) {
        sources.push({
          sourceId: "members",
          getItems({ query }) {
            const items = data.navigation.members;
            return query ? items.filter((item) => item.name.toLowerCase().includes(query.toLowerCase())) : items;
          },
          getItemUrl({ item }) {
            return item.url;
          },
          templates: {
            header({ items, html }) {
              return items.length === 0 ? null : html`<span class="search-headings">Members</span>`;
            },
            item({ item, html }) {
              return html`
                <a href="${item.url}" class="d-flex align-items-center py-2 px-4">
                  <div class="avatar me-2">
                    <img src="${assetsPath}${item.src}" alt="${item.name}" class="rounded-circle" width="32" />
                  </div>
                  <div class="flex-grow-1">
                    <h6 class="mb-0">${item.name}</h6>
                    <small class="text-body-secondary">${item.subtitle}</small>
                  </div>
                </a>
              `;
            },
          },
        });
      }
      return sources;
    },
  });
}

// Add keyboard shortcut for search (Ctrl + K or Cmd + K)
document.addEventListener("keydown", (event) => {
  if ((event.ctrlKey || event.metaKey) && event.key === "k") {
    event.preventDefault();
    document.querySelector(".aa-DetachedSearchButton").click();
  }
});

// Initialize search autocomplete if element exists
if (document.documentElement.querySelector("#autocomplete")) {
  loadSearchData();
}