window.addEventListener('DOMContentLoaded', (event) => {
  let searchInitialized = false;
  let pagefindLoaded = false;

  // 获取正确的 Pagefind 资源路径
  function getPagefindResourcePath() {
    let pagefindPath = USER_DEFINED_OPTIONS.PAGEFIND_ROOT;

    const pathConfigs = [
      {
        uiPath: `${pagefindPath}/pagefind-ui.js`,
        cssPath: `${pagefindPath}/pagefind-ui.css`,
        indexPath: `${pagefindPath}`,
        description: '路径变量'
      },

      {
        uiPath: '../../pagefind/pagefind-ui.js',
        cssPath: '../../pagefind/pagefind-ui.css',
        indexPath: '../../pagefind',
        description: '相对路径（上级目录）'
      }
    ];

    return pathConfigs[0];
  }

  const pagefindConfig = getPagefindResourcePath();

  // 加载 Pagefind UI
  const loadPagefindUI = () => {
    return new Promise((resolve, reject) => {
      if (window.PagefindUI) {
        resolve();
        return;
      }

      const style = document.createElement('link');
      style.rel = 'stylesheet';
      style.href = pagefindConfig.cssPath;
      style.type = 'text/css';

      const script = document.createElement('script');
      script.src = pagefindConfig.uiPath;
      script.type = 'text/javascript';

      let cssLoaded = false;
      let jsLoaded = false;

      const checkAllLoaded = () => {
        if (cssLoaded && jsLoaded) {
          pagefindLoaded = true;
          resolve();
        }
      };

      style.onload = () => {
        cssLoaded = true;
        checkAllLoaded();
      };

      style.onerror = (error) => {
        reject(new Error(`CSS 加载失败: ${style.href}`));
      };

      script.onload = () => {
        jsLoaded = true;
        checkAllLoaded();
      };

      script.onerror = (error) => {
        const fallbackScript = document.createElement('script');
        fallbackScript.src = pagefindConfig.uiPath.startsWith('/')
          ? pagefindConfig.uiPath
          : '/' + pagefindConfig.uiPath;
        fallbackScript.type = 'text/javascript';

        fallbackScript.onload = () => {
          jsLoaded = true;
          checkAllLoaded();
        };

        fallbackScript.onerror = (fallbackError) => {
          reject(
            new Error(
              `JS 加载失败: ${script.src}, 备用路径: ${fallbackScript.src}`
            )
          );
        };

        document.head.appendChild(fallbackScript);
      };

      document.head.appendChild(style);
      document.head.appendChild(script);
    });
  };

  // 弹窗控制函数
  const openSearchModal = function () {
    const modal = document.getElementById('search-modal');
    if (modal) {
      document.body.style.overflow = 'hidden';
      initializePagefindSearch();
      modal.style.display = 'flex';
    }
  };

  const closeSearchModal = function () {
    const modal = document.getElementById('search-modal');
    if (modal) {
      modal.style.display = 'none';
      document.body.style.overflow = '';

      const searchContainer = document.querySelector(
        '#search-modal #pagefind-search'
      );
      if (searchContainer) {
        searchContainer.innerHTML = '';
        searchInitialized = false;
      }
    }
  };

  // 点击标题进行跳转
  function handleSearchResultClicks() {
    // 公共跳转处理函数
    function navigateFromAnchor(anchor, event) {
      if (!anchor) return false;

      const searchContainer = document.querySelector(
        '#search-modal #pagefind-search'
      );
      if (!searchContainer || !searchContainer.contains(anchor)) return false;

      event.preventDefault();
      const href = anchor.getAttribute('href');

      setTimeout(() => {
        closeSearchModal();
        if (href && !href.startsWith('javascript:') && !href.startsWith('#')) {
          window.location.href = href;
        } else if (href && href.startsWith('#')) {
          const element = document.querySelector(href);
          if (element) element.scrollIntoView({ behavior: 'smooth' });
        }
      }, 50);

      return true;
    }

    function findClickableTarget(element) {
      let current = element;
      while (current && current !== document) {
        // 1. 直接是 <a>
        if (current.tagName === 'A') return current;

        // 2. 是主标题 <p class="pagefind-ui__result-title">
        if (
          current.tagName === 'P' &&
          current.classList?.contains('pagefind-ui__result-title')
        ) {
          const anchor = current.querySelector('a');
          if (anchor) return anchor;
        }

        // 3. 是结果块 <div class="pagefind-ui__result-nested">
        if (
          current.tagName === 'DIV' &&
          current.classList?.contains('pagefind-ui__result-nested')
        ) {
          const anchor = current.querySelector('a');
          if (anchor) return anchor;
        }

        current = current.parentNode;
      }
      return null;
    }

    // 事件监听
    document.addEventListener(
      'click',
      function (event) {
        const modal = document.getElementById('search-modal');

        // 关闭模态框背景点击
        if (modal && event.target === modal) {
          closeSearchModal();
          return;
        }

        // 仅在弹窗打开时处理内部跳转
        if (!modal || modal.style.display !== 'flex') return;

        const clickable = findClickableTarget(event.target);
        if (clickable) {
          navigateFromAnchor(clickable, event);
        }
      },
      true
    );
  }

  // 搜索初始化
  async function initializePagefindSearch() {
    if (searchInitialized) {
      return;
    }

    try {
      await loadPagefindUI();

      const searchContainer = document.querySelector(
        '#search-modal #pagefind-search'
      );
      if (!searchContainer) {
        return;
      }

      // 清空容器
      searchContainer.innerHTML = '';

      // 初始化PagefindUI
      new PagefindUI({
        element: '#search-modal #pagefind-search',
        showSubResults: true,
        highlighting: true,
        showImages: false,
        autofocus: true,

        // 搜索词处理
        processTerm: (term) => {
          if (!term) return term;

          if (/[\u4e00-\u9fa5]/.test(term) && !term.includes(' ')) {
            try {
              const segmenter = new Intl.Segmenter('zh-CN', {
                granularity: 'word'
              });
              const segments = segmenter.segment(term);
              const words = Array.from(segments)
                .filter((s) => s.isWordLike)
                .map((s) => s.segment);
              return words.join(' ');
            } catch (error) {
              return term;
            }
          }

          return term;
        },
        // 重写标题
        processResult: function (result) {
          // 递归清理函数
          const cleanParagraphSymbols = (obj) => {
            if (!obj || typeof obj !== 'object') return;

            const fieldsToClean = ['title', 'excerpt'];
            fieldsToClean.forEach((field) => {
              if (obj[field] && typeof obj[field] === 'string') {
                obj[field] = obj[field].replace(/¶/g, '');
              }
            });
            const specialChars = {
              '&': '%26',
              '+': '%2B'
            };

            function encodeURI(params) {
              return params.replace(/[&+]/g, (match) => specialChars[match]);
            }
            if (obj.url) {
              obj.url = encodeURI(obj.url);
            }
            // 清理 meta.title
            if (
              obj.meta &&
              obj.meta.title &&
              typeof obj.meta.title === 'string'
            ) {
              obj.meta.title = obj.meta.title.replace(/¶/g, '');
            }
            if (
              obj.anchor &&
              obj.anchor.text &&
              typeof obj.anchor.text === 'string'
            ) {
              obj.anchor.text = obj.anchor.text.replace(/¶/g, '');
            }
            // 子搜索结果
            if (obj.sub_results && Array.isArray(obj.sub_results)) {
              obj.sub_results.forEach(cleanParagraphSymbols);
            }
          };

          cleanParagraphSymbols(result);
          return result;
        },

        // 结果排序
        sort: (a, b) => b.score - a.score,

        // 翻译配置
        translations: {
          placeholder: '搜索文档',
          zero_results: "没有找到关于'[SEARCH_TERM]'的相关内容",
          many_results: '找到 [COUNT] 个结果',
          one_result: '找到 [COUNT] 个结果',
          search_button: '搜索',
          clear_search: '',
          load_more: '加载更多',
          search_label: '搜索',
          filters_label: '分类',
          page_size_label: '每页结果数',
          skip_to_results: '跳转到结果'
        },

        // 自动完成
        autocomplete: {
          enabled: true,
          resultLimit: 15,
          highlighting: true
        }
      });

      searchInitialized = true;

      // 初始化点击事件处理
      handleSearchResultClicks();
    } catch (error) {
      const searchContainer = document.querySelector(
        '#search-modal #pagefind-search'
      );
      if (searchContainer) {
        searchContainer.innerHTML = `
                    <div style="padding: 20px; text-align: center; color: #666;">
                        <div style="font-size: 24px; margin-bottom: 10px;">⚠️</div>
                        <div style="margin-bottom: 10px;">搜索功能初始化失败</div>
                        <div style="font-size: 12px; color: #999; margin-bottom: 20px;">
                            错误: ${error.message}<br>
                            Pagefind 版本: 1.5.0-beta.1<br>
                            页面路径: ${window.location.pathname}
                        </div>
                        <button onclick="location.reload()" style="background: #2980b9; color: white; border: none; padding: 8px 16px; border-radius: 4px; cursor: pointer;">
                            刷新页面
                        </button>
                    </div>
                `;
      }
    }
  }

  // 添加搜索按钮事件监听器
  const searchBtn = document.querySelector('.search-trigger-btn');
  if (searchBtn) {
    if (searchBtn.hasAttribute('onclick')) {
      searchBtn.removeAttribute('onclick');
    }
    searchBtn.addEventListener('click', openSearchModal);
  }

  // 添加关闭按钮事件
  const closeBtn = document.querySelector('.close-search');
  if (closeBtn) {
    closeBtn.addEventListener('click', closeSearchModal);
  }

  // 添加键盘快捷键
  document.addEventListener('keydown', (event) => {
    if ((event.ctrlKey || event.metaKey) && event.key === 'k') {
      event.preventDefault();
      openSearchModal();
    }

    if (event.key === 'Escape') {
      closeSearchModal();
    }
  });

  // 预加载 Pagefind UI
  setTimeout(() => {
    loadPagefindUI()
      .then(() => {
        // 提前初始化点击事件处理
        handleSearchResultClicks();
      })
      .catch((error) => {
        console.error('Pagefind预加载失败:', error);
      });
  }, 1000);

  // 将函数暴露到全局
  window.openSearchModal = openSearchModal;
  window.closeSearchModal = closeSearchModal;
});
