/* VKINGING 客户端子串搜索
   接管 Doxygen 的 MSearchField，对 search-index.json 做中文关键字包含匹配。
   补足 Doxygen 内置搜索仅"前缀匹配"的不足（搜"存储"可命中"连续离线存储"）。
   纯前端、无后端依赖，适配静态部署。 */
(function () {
  "use strict";
  function init() {
    var field = document.getElementById("MSearchField");
    var box = document.getElementById("MSearchBox");
    if (!field || !box) return;
    var host = box;
    host.style.position = host.style.position || "relative";

    /* 禁用 Doxygen 原生前缀搜索，避免弹两套结果 */
    if (window.searchBox) {
      window.searchBox.OnSearchFieldChange = function () {};
      window.searchBox.OnSearchFieldFocus = function () {};
    }

    /* 加载索引（与页面同目录的 search-index.json） */
    var index = [];
    var xhr = new XMLHttpRequest();
    xhr.open("GET", "search-index.json", true);
    xhr.onload = function () {
      if (xhr.status === 200) { try { index = JSON.parse(xhr.responseText); } catch (e) {} }
    };
    xhr.send();

    /* 下拉结果容器 */
    var dd = document.createElement("div");
    dd.className = "vk-search-dropdown";
    dd.style.display = "none";
    host.appendChild(dd);

    function escapeHtml(s) {
      return String(s).replace(/[&<>"]/g, function (c) {
        return { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" }[c];
      });
    }

    function render(q) {
      if (!q) { dd.style.display = "none"; dd.innerHTML = ""; return; }
      /* 左对齐搜索框，宽度自适应：既够宽又不超出右视口 */
      var rect = box.getBoundingClientRect();
      dd.style.width = Math.max(220, Math.min(340, window.innerWidth - rect.left - 16)) + "px";
      var ql = q.toLowerCase(), res = [];
      for (var i = 0; i < index.length && res.length < 12; i++) {
        var it = index[i];
        var hay = (it.title || "") + " " + (it.text || "");
        if (hay.toLowerCase().indexOf(ql) >= 0) res.push(it);
      }
      if (res.length === 0) {
        dd.innerHTML = '<div class="vk-search-empty">未找到 "' + escapeHtml(q) + '"</div>';
      } else {
        dd.innerHTML = res.map(function (r) {
          return '<a class="vk-search-item" href="' + r.url + '">' +
                 '<span class="vk-search-title">' + escapeHtml(r.title || r.url) + '</span></a>';
        }).join("");
      }
      dd.style.display = "block";
    }

    field.addEventListener("input", function () { render(field.value.trim()); });
    field.addEventListener("focus", function () { if (field.value.trim()) render(field.value.trim()); });
    document.addEventListener("click", function (e) {
      if (!host.contains(e.target)) dd.style.display = "none";
    });
    field.addEventListener("keydown", function (e) {
      if (e.key === "Escape") { dd.style.display = "none"; }
      if (e.key === "Enter") {
        var first = dd.querySelector(".vk-search-item");
        if (first && dd.style.display !== "none") { e.preventDefault(); window.location = first.getAttribute("href"); }
      }
    });
  }
  if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", init);
  else init();
})();
