(() => {
  // 保存初始的hash值
  let initialHash = window.location.hash;
  let resourcesLoaded = false;
  let isProgrammaticScroll = false;
  
  function selectLeftTree() {
    let t = document.querySelector(".globaltoc");
    if (!t) return;

    // 根据当前URL找到对应的导航项
    function findCurrentNavItem() {
      // 获取当前页面的完整URL（包括哈希）
      let currentFullURL = window.location.href;
      // 获取当前页面的路径（不带哈希）
      let currentPath = window.location.pathname;
      // 获取哈希部分
      let currentHash = window.location.hash;

      // 查找所有导航链接
      let allLinks = t.querySelectorAll("a");
      let currentLink = null;

      // 先尝试完整匹配（包括哈希）
      allLinks.forEach((link) => {
        let href = link.getAttribute("href");
        if (href && (currentFullURL.endsWith(href) || href === currentHash)) {
          currentLink = link;
        }
      });

      // 如果完整匹配失败，尝试匹配路径部分
      if (!currentLink) {
        allLinks.forEach((link) => {
          let href = link.getAttribute("href");
          if (href && href.split("#")[0] === currentPath.split("#")[0]) {
            currentLink = link;
          }
        });
      }

      // 如果路径匹配也失败，尝试部分匹配
      if (!currentLink) {
        let pathSegments = currentPath.split("/").filter((seg) => seg);
        allLinks.forEach((link) => {
          let href = link.getAttribute("href");
          if (href) {
            let hrefPath = href.split("#")[0];
            let hrefSegments = hrefPath.split("/").filter((seg) => seg);
            // 检查是否有足够的匹配段
            let matchCount = 0;
            for (
              let i = 0;
              i < Math.min(pathSegments.length, hrefSegments.length);
              i++
            ) {
              if (pathSegments[i] === hrefSegments[i]) {
                matchCount++;
              } else {
                break;
              }
            }
            // 如果匹配度超过50%，认为是当前页面
            if (
              matchCount > 0 &&
              matchCount >=
                Math.min(pathSegments.length, hrefSegments.length) / 2
            ) {
              currentLink = link;
            }
          }
        });
      }

      return currentLink;
    }

    function findParentInRightToc(hashId) {
      // 点击右侧树的子级，高亮左侧树
      const localtoc = document.querySelector(".localtoc");
      if (!localtoc) return null;

      const targetLink = localtoc.querySelector(`a[href="#${hashId}"]`);
      if (!targetLink) return null;

      const targetLi = targetLink.closest("li");
      if (!targetLi) return null;

      const parentUl = targetLi.parentElement;
      if (!parentUl || parentUl === localtoc) return null;

      const grandParentLi = parentUl.parentElement;
      if (!grandParentLi || grandParentLi.tagName !== "LI") return null;

      const parentLink = grandParentLi.querySelector("a.reference.internal");
      if (!parentLink) return null;

      const parentHref = parentLink.getAttribute("href");
      if (!parentHref) return null;

      return parentHref;
    }

    // 设置当前导航项
    function setCurrentNav() {
      let currentLink = findCurrentNavItem();
      if (currentLink === null) {
        let currentHash = window.location.hash.split("#")[1];
        let ids = findParentInRightToc(currentHash);
        if (ids === null) {
          ids = "#";
        }
        let allLinks = t.querySelectorAll("a");

        allLinks.forEach((link) => {
          let href = link.getAttribute("href");
          if (href && href === ids) {
            currentLink = link;
          }
        });
      }

      if (currentLink) {
        // 移除所有current类和active类
        document
          .querySelectorAll(".globaltoc .current, .globaltoc .active")
          .forEach((el) => {
            el.classList.remove("current", "active");
          });

        // 设置当前链接为选中状态
        let currentLi = currentLink.closest("li");
        if (currentLi) {
          currentLi.classList.add("current", "active");
          currentLink.classList.add("current", "active");

          // 确保父级菜单也是展开状态
          let parentUl = currentLi.closest("ul");
          while (parentUl && parentUl !== t) {
            let parentLi = parentUl.closest("li");
            if (parentLi) {
              parentLi.classList.add("_expand");
              parentLi.classList.remove("_collapse");
              parentUl = parentLi.closest("ul");
            } else {
              break;
            }
          }
        }
      }
    }

    // 处理链接点击
    function handleMenuClick(clickedA) {
      // 移除所有current类和active类
      document
        .querySelectorAll(".globaltoc .current, .globaltoc .active")
        .forEach((el) => {
          el.classList.remove("current", "active");
        });

      // 为当前点击的元素添加current和active类
      let currentLi = clickedA.closest("li");
      if (currentLi) {
        currentLi.classList.add("active");
        clickedA.classList.add("active");
      }
    }

    // 使用事件委托处理点击
    t.addEventListener("click", function (e) {
      // 只处理链接点击
      if (e.target.tagName === "A" && e.target.getAttribute("href") !== "#") {
        let href = e.target.getAttribute("href");

        // 如果是页面内锚点链接
        if (href.startsWith("#")) {
          e.preventDefault();
          handleMenuClick(e.target);

          // 标记程序滚动
          isProgrammaticScroll = true;
          // 保存新的hash
          initialHash = href;
          
          // 滚动到锚点
          let target = document.querySelector(href);
          if (target) {
            let offset = 80;
            let targetPosition =
              target.getBoundingClientRect().top + window.pageYOffset - offset;

            window.scrollTo({
              top: targetPosition,
              behavior: "smooth",
            });

            // 更新URL哈希（不刷新页面）
            history.pushState(null, null, href);
          }
          
          // 重置程序滚动标记
          setTimeout(() => {
            isProgrammaticScroll = false;
          }, 1000);
        } else {
          // 普通页面链接
          handleMenuClick(e.target);
        }
      }
    });

    // 监听哈希变化
    window.addEventListener("hashchange", function () {
      // 如果是用户点击触发的hash变化，不立即设置导航
      if (!isProgrammaticScroll && resourcesLoaded) {
        setTimeout(() => {
          setCurrentNav();
        }, 100);
      }
    });

    // 页面加载时设置选中状态
    setTimeout(() => {
      setCurrentNav();
    }, 300);
  }

  function selectRightTree() {
    const sections = document.querySelectorAll(
      ".yue > section[id], .yue > section section[id]"
    );
    const localtoc = document.querySelector(".localtoc");
    if (!localtoc || sections.length === 0) return;

    let scrollMarginTop = 0;
    let clickedSectionId = null;
    let lastClickTime = 0;
    let scrollTimeout;

    // 获取排序的章节
    const getSortedSections = () =>
      Array.from(sections).sort(
        (a, b) =>
          a.getBoundingClientRect().top +
          window.scrollY -
          (b.getBoundingClientRect().top + window.scrollY)
      );

    // 检测当前章节ID
    const detectCurrentSection = () => {
      const sorted = getSortedSections();
      const scrollY = window.scrollY;

      // 底部检测
      if (scrollY + window.innerHeight >= document.body.offsetHeight - 50) {
        return sorted[sorted.length - 1]?.id || null;
      }

      // 从下往上找第一个在页面顶部以上的章节
      for (let i = sorted.length - 1; i >= 0; i--) {
        const section = sorted[i];
        const elementTop = section.getBoundingClientRect().top + scrollY;
        if (elementTop <= scrollY + 110) {
          return section.id;
        }
      }

      // 顶部检测
      if (scrollY < 100) {
        return sorted[0]?.id || null;
      }

      // 最接近顶部的章节
      return sorted.reduce(
        (closest, section) => {
          const distance = Math.abs(
            section.getBoundingClientRect().top + scrollY - scrollY
          );
          return distance < closest.distance
            ? { id: section.id, distance }
            : closest;
        },
        { id: sorted[0]?.id, distance: Infinity }
      ).id;
    };

    // 设置活动章节
    const setActiveSection = (ids) => {
      let sectionId = ids;
      // 选中前言
      if (!sectionId || sectionId === "id1") sectionId = "";
      document
        .querySelectorAll(".localtoc .active, .localtoc .activeCurrent")
        .forEach((el) => {
          el.classList.remove("active", "activeCurrent");
        });

      const tocLink =
        document.querySelector(`.localtoc a[href="#${sectionId}"]`) ||
        [...document.querySelectorAll('.localtoc a[href^="#"]')].find(
          (link) => link.getAttribute("href") === `#${sectionId}`
        );

      if (tocLink) {
        const parentLi = tocLink.closest("li");
        if (parentLi) {
          parentLi.classList.add("active", "activeCurrent");
        }
      }

      history.pushState(null, null, `#${ids}`);
      selectLeftTree();
    };

    // 滚动处理
    const handleScroll = () => {
      clearTimeout(scrollTimeout);
      scrollTimeout = setTimeout(() => {
        const now = Date.now();
        const sectionId =
          clickedSectionId && now - lastClickTime < 1000
            ? clickedSectionId
            : detectCurrentSection();

        if (sectionId) setActiveSection(sectionId);
        clickedSectionId = null;
      }, 300);
    };

    // 获取滚动边距
    const getScrollMargin = () => {
      const firstSection = document.querySelector(
        ".yue > section, .yue > section[id]"
      );
      if (firstSection) {
        scrollMarginTop =
          parseInt(window.getComputedStyle(firstSection).scrollMarginTop) || 0;
      }
    };

    // 目录点击事件
    const handleTocClick = (e) => {
      if (
        e.target.tagName === "A" &&
        e.target.getAttribute("href")?.startsWith("#")
      ) {
        e.preventDefault();
        const targetId = e.target.getAttribute("href").substring(1);
        clickedSectionId = targetId;
        lastClickTime = Date.now();

        const targetElement = document.getElementById(targetId);
        if (targetElement) {
          setActiveSection(targetId);
          const offsetTop =
            targetElement.getBoundingClientRect().top +
            window.scrollY -
            scrollMarginTop -
            20;
          window.scrollTo({ top: offsetTop, behavior: "smooth" });
        } else {
          setActiveSection(targetId);
          window.scrollTo({ top: 0, behavior: "smooth" });
        }
      }
    };

    // 初始化
    const init = () => {
      getScrollMargin();
      const initialSectionId = detectCurrentSection();
      if (initialSectionId) setActiveSection(initialSectionId);
    };

    // 事件绑定
    window.addEventListener("scroll", handleScroll);
    window.addEventListener("resize", getScrollMargin);
    localtoc.addEventListener("click", handleTocClick);

    if (document.readyState === "loading") {
      document.addEventListener("DOMContentLoaded", init);
    } else {
      setTimeout(init, 100);
    }
  }
  // 等待图片加载完成
  function waitForImages() {
    return new Promise((resolve) => {
      const images = document.querySelectorAll('img');
      let loadedCount = 0;
      const totalImages = images.length;
      
      if (totalImages === 0) {
        resolve();
        return;
      }
      
      images.forEach(img => {
        if (img.complete) {
          checkImageLoaded();
        } else {
          img.addEventListener('load', checkImageLoaded);
          img.addEventListener('error', checkImageLoaded);
        }
      });
      
      function checkImageLoaded() {
        loadedCount++;
        if (loadedCount === totalImages) {
          resolve();
        }
      }
    });
  }

  // 修正锚点滚动位置
  function fixAnchorPosition() {
    if (initialHash && initialHash !== '#') {
      const targetElement = document.querySelector(initialHash);
      if (targetElement) {
        isProgrammaticScroll = true;
        
        const offset = 80;
        const targetPosition = 
          targetElement.getBoundingClientRect().top + 
          window.pageYOffset - offset;
        
        // 使用instant快速跳转到正确位置
        window.scrollTo({
          top: targetPosition,
          behavior: 'instant'
        });
        
        // 更新hash（如果需要）
        if (window.location.hash !== initialHash) {
          history.replaceState(null, null, initialHash);
        }
        
        // 触发目录更新
        selectLeftTree();
        
        setTimeout(() => {
          isProgrammaticScroll = false;
        }, 100);
        
      }
    }
  }

    // 执行
  document.addEventListener("DOMContentLoaded", () => {
    window.localtocManager = selectRightTree();
  });


  // 主初始化函数-----保证搜索定位准确，在资源加载后再定位一次
  async function initialize() {
    selectLeftTree();
    
    // 如果有初始hash，先尝试滚动一次（可能不准确）
    if (initialHash && initialHash !== '#') {
      const targetElement = document.querySelector(initialHash);
      if (targetElement) {
        isProgrammaticScroll = true;
        const offset = 80;
        const targetPosition = 
          targetElement.getBoundingClientRect().top + 
          window.pageYOffset - offset;
        
        window.scrollTo({
          top: targetPosition,
          behavior: 'smooth'
        });
        
        setTimeout(() => {
          isProgrammaticScroll = false;
        }, 1000);
      }
    }
    
    // 等待图片加载完成
    await waitForImages();
    
    // 标记资源已加载完成
    resourcesLoaded = true;
    
    // 修正锚点位置
    setTimeout(fixAnchorPosition, 100);
    
    // 监听后续的图片加载
    const observer = new MutationObserver((mutations) => {
      mutations.forEach((mutation) => {
        if (mutation.addedNodes.length) {
          mutation.addedNodes.forEach((node) => {
            if (node.nodeName === 'IMG') {
              // 新的图片加载完成后修正位置
              waitForImages().then(() => {
                if (initialHash && initialHash !== '#') {
                  setTimeout(fixAnchorPosition, 50);
                }
              });
            }
          });
        }
      });
    });
    
    observer.observe(document.body, {
      childList: true,
      subtree: true
    });
  }

  // 使用window.onload确保页面完全加载
  if (document.readyState === 'loading') {
    window.addEventListener('load', function() {
      setTimeout(initialize, 100);
    });
  } else {
    // 页面已经加载完成
    setTimeout(initialize, 100);
  }
  
  window.addEventListener('hashchange', function() {
    if (!isProgrammaticScroll) {
      initialHash = window.location.hash;
      
      if (resourcesLoaded) {
        const targetElement = document.querySelector(initialHash);
        if (targetElement) {
          isProgrammaticScroll = true;
          const offset = 80;
          const targetPosition = 
            targetElement.getBoundingClientRect().top + 
            window.pageYOffset - offset;
          
          window.scrollTo({
            top: targetPosition,
            behavior: 'smooth'
          });
          
          setTimeout(() => {
            isProgrammaticScroll = false;
          }, 1000);
        }
      }
    }
  });
})();