import { j as s, c as z, b as P, g as K, aE as V, aF as $ } from "./DocsApp-CEu0IOyd.js";
import { useState as y, useRef as j, useEffect as p, useCallback as E, createContext as q, useContext as H, forwardRef as M } from "react";
import { useNavigate as Q } from "react-router-dom";
import R from "flexsearch";
import { Search as U, X, FileText as G, Loader2 as J } from "lucide-react";
const W = 20;
class O {
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  index;
  sections = /* @__PURE__ */ new Map();
  initialized = !1;
  constructor() {
    this.index = new R.Index({
      tokenize: "full",
      resolution: 9,
      cache: 100
    });
  }
  init(t) {
    this.clear();
    for (const r of t.sections)
      this.sections.set(r.id, r), this.index.add(r.id, r.tokens.join(" "));
    this.initialized = !0;
  }
  clear() {
    this.sections.clear(), this.index = new R.Index({
      tokenize: "full",
      resolution: 9,
      cache: 100
    }), this.initialized = !1;
  }
  search(t) {
    if (!this.initialized)
      return [];
    const { query: r, limit: n = W } = t, i = r.toLowerCase().trim();
    return i ? this.index.search(i, { limit: n }).map((c) => {
      const a = this.sections.get(c);
      return a ? {
        id: a.id,
        pageTitle: a.pageTitle,
        sectionTitle: a.sectionTitle,
        snippet: this.generateSnippet(a.content, i),
        url: a.url,
        score: 1
      } : null;
    }).filter((c) => c !== null) : [];
  }
  generateSnippet(t, r) {
    if (!t) return "";
    const n = 150, i = t.toLowerCase(), d = r.split(/\s+/).filter(Boolean);
    let c = 0;
    for (const u of d) {
      const f = i.indexOf(u);
      if (f !== -1) {
        c = f;
        break;
      }
    }
    const a = Math.max(0, c - 30), o = Math.min(t.length, a + n);
    let l = t.slice(a, o);
    return a > 0 && (l = "..." + l), o < t.length && (l = l + "..."), l;
  }
  isInitialized() {
    return this.initialized;
  }
  getSectionCount() {
    return this.sections.size;
  }
}
const le = new O();
function Y(e, t, r = "mark") {
  if (!e || t.length === 0)
    return e;
  const n = e.toLowerCase(), i = [];
  for (const o of t) {
    const l = o.toLowerCase();
    let u = 0;
    for (; ; ) {
      const f = n.indexOf(l, u);
      if (f === -1) break;
      i.push({ start: f, end: f + o.length }), u = f + 1;
    }
  }
  if (i.length === 0)
    return e;
  const d = Z(i);
  let c = "", a = 0;
  for (const o of d)
    c += e.slice(a, o.start), c += `<${r}>`, c += e.slice(o.start, o.end), c += `</${r}>`, a = o.end;
  return c += e.slice(a), c;
}
function Z(e) {
  if (e.length === 0) return [];
  const t = [...e].sort((n, i) => n.start - i.start), r = [t[0]];
  for (let n = 1; n < t.length; n++) {
    const i = t[n], d = r[r.length - 1];
    i.start <= d.end ? d.end = Math.max(d.end, i.end) : r.push(i);
  }
  return r;
}
function ee(e, t, r = {}) {
  const {
    maxLength: n = 120,
    contextBefore: i = 30,
    contextAfter: d = 80
  } = r;
  if (!e) return "";
  if (t.length === 0)
    return e.slice(0, n) + (e.length > n ? "..." : "");
  const c = e.toLowerCase();
  let a = -1, o = "";
  for (const g of t) {
    const h = c.indexOf(g.toLowerCase());
    h !== -1 && (a === -1 || h < a) && (a = h, o = g);
  }
  if (a === -1)
    return e.slice(0, n) + (e.length > n ? "..." : "");
  const l = Math.max(0, a - i), u = Math.min(e.length, a + o.length + d);
  let f = e.slice(l, u);
  return l > 0 && (f = "..." + f), u < e.length && (f = f + "..."), f;
}
function D(e, t, r = {}) {
  const n = ee(e, t, r);
  return Y(n, t, r.tag || "mark");
}
function te(e) {
  return e.toLowerCase().split(/[\s\-_]+/).filter((t) => t.length > 0);
}
const B = q(null);
function ne() {
  const e = H(B);
  if (!e)
    throw new Error("useSearch must be used within a SearchProvider");
  return e;
}
function de({
  children: e,
  lang: t = "zh-cn",
  enabled: r = !0,
  maxResults: n = 20,
  enableHotkeys: i = !0
}) {
  const [d, c] = y(!1), [a, o] = y(!1), [l, u] = y(null), [f, g] = y([]), [h, I] = y(""), [v, S] = y(!1), x = j(null), b = j(null), N = j(null), L = j(!1);
  p(() => (x.current = new O(), () => {
    x.current && (x.current.clear(), x.current = null);
  }), []), p(() => {
    N.current && N.current !== t && (c(!1), N.current = null, g([]), I(""), x.current && x.current.clear());
  }, [t]);
  const k = E(async () => {
    if (!(d && N.current === t || L.current || !r)) {
      L.current = !0, o(!0), u(null);
      try {
        const m = await fetch(`/search-index-${t}.json`);
        if (!m.ok)
          throw new Error(`Failed to load search index: ${m.status}`);
        const w = await m.json();
        x.current && x.current.init(w), N.current = t, c(!0);
      } catch (m) {
        u(m instanceof Error ? m.message : "Failed to load search index");
      } finally {
        o(!1), L.current = !1;
      }
    }
  }, [t, d, r]), T = E(async (m) => {
    if (!m.trim())
      return g([]), [];
    x.current?.isInitialized() || await k();
    const w = {
      query: m,
      lang: t,
      limit: n
    };
    if (x.current) {
      const C = x.current.search(w);
      return g(C), C;
    }
    return [];
  }, [t, k, n]);
  p(() => {
    if (!h.trim()) {
      g([]);
      return;
    }
    return b.current && clearTimeout(b.current), b.current = setTimeout(() => {
      T(h);
    }, 150), () => {
      b.current && clearTimeout(b.current);
    };
  }, [h, T]), p(() => {
    v && !d && !L.current && k();
  }, [v, d, k]), p(() => {
    if (!i) return;
    const m = (w) => {
      (w.metaKey || w.ctrlKey) && w.key.toLowerCase() === "k" && (w.preventDefault(), S((C) => !C)), w.key === "Escape" && v && S(!1);
    };
    return document.addEventListener("keydown", m), () => document.removeEventListener("keydown", m);
  }, [i, v]);
  const A = {
    isLoaded: d,
    isLoading: a,
    error: l,
    search: T,
    results: f,
    query: h,
    setQuery: I,
    open: v,
    setOpen: S,
    loadIndex: k
  };
  return /* @__PURE__ */ s.jsx(B.Provider, { value: A, children: e });
}
const F = M(
  ({ value: e, onChange: t, onClear: r, className: n, placeholder: i, ...d }, c) => /* @__PURE__ */ s.jsxs("div", { className: "flex items-center gap-3 px-4 py-3 border-b", children: [
    /* @__PURE__ */ s.jsx(U, { className: "h-5 w-5 shrink-0 text-muted-foreground" }),
    /* @__PURE__ */ s.jsx(
      "input",
      {
        ref: c,
        type: "text",
        value: e,
        onChange: (a) => t(a.target.value),
        placeholder: i || "搜索文档...",
        className: z(
          "flex-1 bg-transparent text-base outline-none placeholder:text-muted-foreground",
          n
        ),
        ...d
      }
    ),
    e && r && /* @__PURE__ */ s.jsx(
      "button",
      {
        type: "button",
        onClick: r,
        className: "p-1 rounded hover:bg-muted transition-colors",
        children: /* @__PURE__ */ s.jsx(X, { className: "h-4 w-4 text-muted-foreground" })
      }
    )
  ] })
);
F.displayName = "SearchInput";
const _ = M(
  ({ result: e, query: t, isSelected: r, onClick: n, onMouseEnter: i }, d) => {
    const c = te(t), a = D(
      e.sectionTitle,
      c,
      { maxLength: 100, contextBefore: 0, contextAfter: 0 }
    ), o = D(
      e.snippet,
      c,
      { maxLength: 150 }
    );
    return /* @__PURE__ */ s.jsxs(
      "div",
      {
        ref: d,
        onClick: n,
        onMouseEnter: i,
        className: z(
          "flex items-start gap-3 px-4 py-3 cursor-pointer transition-all duration-200 border-l-2 rounded-r-md mx-2",
          "hover:shadow-sm hover:translate-x-0.5",
          r ? "bg-accent/80 border-l-primary shadow-md scale-[1.02] translate-x-1" : "hover:bg-muted/50 border-l-transparent"
        ),
        children: [
          /* @__PURE__ */ s.jsx(G, { className: "h-4 w-4 mt-0.5 shrink-0 text-muted-foreground" }),
          /* @__PURE__ */ s.jsxs("div", { className: "flex-1 min-w-0", children: [
            /* @__PURE__ */ s.jsx("div", { className: "flex items-center gap-2", children: /* @__PURE__ */ s.jsx(
              "span",
              {
                className: "font-medium text-sm truncate",
                dangerouslySetInnerHTML: { __html: a }
              }
            ) }),
            e.pageTitle !== e.sectionTitle && /* @__PURE__ */ s.jsx("div", { className: "text-xs text-muted-foreground truncate mt-0.5", children: e.pageTitle }),
            o && /* @__PURE__ */ s.jsx(
              "div",
              {
                className: "text-xs text-muted-foreground mt-1 line-clamp-2",
                dangerouslySetInnerHTML: { __html: o }
              }
            )
          ] })
        ]
      }
    );
  }
);
_.displayName = "SearchItem";
function re({ results: e, query: t, onSelect: r }) {
  const [n, i] = y(0), d = j(null), c = j(null);
  p(() => {
    i(0);
  }, [e]), p(() => {
    if (c.current && d.current) {
      const o = d.current, l = c.current, u = o.getBoundingClientRect(), f = l.getBoundingClientRect();
      f.bottom > u.bottom ? l.scrollIntoView({ block: "nearest" }) : f.top < u.top && l.scrollIntoView({ block: "nearest" });
    }
  }, [n]), p(() => {
    const o = (l) => {
      if (l.key === "ArrowDown")
        l.preventDefault(), i((u) => Math.min(u + 1, e.length - 1));
      else if (l.key === "ArrowUp")
        l.preventDefault(), i((u) => Math.max(u - 1, 0));
      else if (l.key === "Enter") {
        l.preventDefault();
        const u = e[n];
        u && r(u.url);
      }
    };
    return document.addEventListener("keydown", o), () => document.removeEventListener("keydown", o);
  }, [e, n, r]);
  const a = (o) => {
    r(o.url);
  };
  return /* @__PURE__ */ s.jsx("div", { ref: d, className: "py-2", children: e.map((o, l) => /* @__PURE__ */ s.jsx(
    _,
    {
      result: o,
      query: t,
      isSelected: l === n,
      ref: l === n ? c : null,
      onClick: () => a(o),
      onMouseEnter: () => i(l)
    },
    o.id
  )) });
}
function ue({ placeholder: e }) {
  const {
    open: t,
    setOpen: r,
    query: n,
    setQuery: i,
    results: d,
    isLoading: c,
    error: a,
    isLoaded: o
  } = ne(), l = Q(), u = j(null);
  p(() => {
    t && u.current && setTimeout(() => u.current?.focus(), 0);
  }, [t]), p(() => {
    t || i("");
  }, [t, i]);
  const f = (h) => {
    l(h), r(!1);
  }, g = (h) => {
    r(h);
  };
  return /* @__PURE__ */ s.jsx(P, { open: t, onOpenChange: g, children: /* @__PURE__ */ s.jsxs(K, { className: "overflow-hidden p-0 shadow-lg max-w-xl top-[15%] translate-y-0", showCloseButton: !1, children: [
    /* @__PURE__ */ s.jsx(V, { children: "搜索文档" }),
    /* @__PURE__ */ s.jsx($, { children: "搜索文档内容" }),
    /* @__PURE__ */ s.jsxs("div", { className: "flex flex-col", children: [
      /* @__PURE__ */ s.jsx(
        F,
        {
          ref: u,
          value: n,
          onChange: i,
          placeholder: e,
          onClear: () => i("")
        }
      ),
      /* @__PURE__ */ s.jsxs("div", { className: "max-h-[60vh] overflow-y-auto border-t", children: [
        c && !o && /* @__PURE__ */ s.jsx("div", { className: "flex items-center justify-center py-12", children: /* @__PURE__ */ s.jsx(J, { className: "h-6 w-6 animate-spin text-muted-foreground" }) }),
        a && /* @__PURE__ */ s.jsx("div", { className: "px-4 py-8 text-center text-sm text-muted-foreground", children: a }),
        o && !c && !n && /* @__PURE__ */ s.jsx("div", { className: "px-4 py-8 text-center text-sm text-muted-foreground", children: "输入关键词搜索文档" }),
        o && n && d.length === 0 && !c && /* @__PURE__ */ s.jsxs("div", { className: "px-4 py-8 text-center text-sm text-muted-foreground", children: [
          '未找到 "',
          n,
          '" 相关结果'
        ] }),
        d.length > 0 && /* @__PURE__ */ s.jsx(re, { results: d, query: n, onSelect: f })
      ] }),
      /* @__PURE__ */ s.jsxs("div", { className: "flex items-center justify-between border-t px-4 py-2 text-xs text-muted-foreground bg-muted/30", children: [
        /* @__PURE__ */ s.jsxs("div", { className: "flex items-center gap-4", children: [
          /* @__PURE__ */ s.jsxs("span", { className: "flex items-center gap-1", children: [
            /* @__PURE__ */ s.jsx("kbd", { className: "px-1.5 py-0.5 rounded bg-muted border text-[10px]", children: "↵" }),
            "选择"
          ] }),
          /* @__PURE__ */ s.jsxs("span", { className: "flex items-center gap-1", children: [
            /* @__PURE__ */ s.jsx("kbd", { className: "px-1.5 py-0.5 rounded bg-muted border text-[10px]", children: "↑↓" }),
            "导航"
          ] })
        ] }),
        /* @__PURE__ */ s.jsxs("span", { className: "flex items-center gap-1", children: [
          /* @__PURE__ */ s.jsx("kbd", { className: "px-1.5 py-0.5 rounded bg-muted border text-[10px]", children: "esc" }),
          "关闭"
        ] })
      ] })
    ] })
  ] }) });
}
export {
  de as S,
  ue as a,
  O as b,
  F as c,
  _ as d,
  re as e,
  Y as f,
  ee as g,
  D as h,
  le as s,
  te as t,
  ne as u
};
