// ———— Search Page ————
function MarkdownLite({ text }) {
  const lines = text.split("\n");
  const out = [];
  let listBuf = [];
  const flush = () => { if (listBuf.length) { out.push(<ul key={out.length}>{listBuf}</ul>); listBuf = []; } };
  const inline = (s, k) => {
    const parts = [];
    let rest = s;
    let idx = 0;
    const patterns = [
      [/\*\*(.+?)\*\*/, (m) => <strong key={k+"_"+idx++}>{m[1]}</strong>],
      [/`([^`]+)`/, (m) => <code key={k+"_"+idx++}>{m[1]}</code>],
    ];
    while (rest) {
      let earliest = -1, which = -1, match;
      patterns.forEach(([re], i) => {
        const m = rest.match(re);
        if (m && (earliest === -1 || m.index < earliest)) { earliest = m.index; which = i; match = m; }
      });
      if (which === -1) { parts.push(rest); break; }
      if (earliest > 0) parts.push(rest.slice(0, earliest));
      parts.push(patterns[which][1](match));
      rest = rest.slice(earliest + match[0].length);
    }
    return parts;
  };
  lines.forEach((ln, i) => {
    if (ln.startsWith("- ")) {
      listBuf.push(<li key={i}>{inline(ln.slice(2), i)}</li>);
    } else if (ln.trim() === "") {
      flush();
    } else {
      flush();
      out.push(<p key={i} style={{ margin: "0 0 10px" }}>{inline(ln, i)}</p>);
    }
  });
  flush();
  return <div>{out}</div>;
}

function MechBadge({ name }) {
  const cls = MECH_COLORS[name] || "neutral";
  return <span className={`badge ${cls}`}>{name}</span>;
}

function SearchPage({ openDetail }) {
  const [q, setQ] = useState("");
  const [loading, setLoading] = useState(false);
  const [results, setResults] = useState([]);
  const [insight, setInsight] = useState("");
  const [error, setError] = useState("");
  const [searched, setSearched] = useState(false);

  const doSearch = async (e) => {
    if (e) e.preventDefault();
    if (!q.trim()) return;
    setLoading(true);
    setError("");
    try {
      const data = await window.API.search(q.trim(), 20);
      setInsight(data.insight || "");
      setResults(data.videos || []);
      setSearched(true);
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  const vectorCount = results.filter(r => r.score_source === "vector").length;
  const aiCount = results.filter(r => r.score_source === "hermes_ref").length;
  const bothCount = results.filter(r => r.score_source === "both").length;

  const _openDetail = (r) => {
    const platMap = { youtube: PLATFORMS[0], tiktok: PLATFORMS[1], bilibili: PLATFORMS[2] };
    const meta = r.metadata || {};
    const hue = (r.id || "").split("").reduce((a, c) => a + c.charCodeAt(0), 200) % 360;
    const mechs = (() => { try { return JSON.parse(meta.viral_mechanisms || "[]"); } catch { return []; } })();
    const labels = (() => { try { return JSON.parse(meta.structure_labels || "[]"); } catch { return []; } })();
    openDetail({
      id: r.id,
      title: meta.title || r.id,
      platform: platMap[meta.platform] || { id: "?", label: "?", cls: "neutral" },
      type: meta.video_type || "",
      structure: meta.story_structure || "",
      hook_type: meta.hook_type || "",
      score: meta.score_total || 0,
      reproducibility: meta.reproducibility || "",
      publishedAt: meta.published_at || "",
      duration: meta.duration_sec || 0,
      url: meta.url || "",
      thumbHue: hue,
      mechanisms: mechs,
      emotionPath: (meta.emotion_curve || "").split(/[→\-]/).map(s => s.trim()).filter(Boolean),
      transferable: mechs,
      structure_labels_arr: labels,
      radar: { "综合评分": meta.score_total || 0 },
      metricsHistory: [],
    });
  };

  return (
    <>
      <div className="page-header">
        <div>
          <h1 className="page-title">语义搜索</h1>
          <div className="page-subtitle">结合 ChromaDB 向量检索与 Hermes AI 洞察，返回最贴近意图的爆款样本。</div>
        </div>
      </div>

      <div className="search-hero">
        <h2 className="search-hero-title">在知识库中，描述你想找的视频</h2>
        <div className="search-hero-sub">自然语言 / 机制关键词 / 结构标签都可以 · 支持中英文混写</div>
        <form className="search-big-input-wrap" onSubmit={doSearch}>
          <Icon.Search size={16} className="search-big-input-icon" style={{position:"absolute", left:16, top:"50%", transform:"translateY(-50%)", color:"var(--ink-3)"}} />
          <input className="search-big-input" value={q} onChange={e=>setQ(e.target.value)}
            placeholder="描述你想找的视频类型，如「传承赋能 三段式 情感共鸣」" />
          <button className="btn primary search-big-submit" type="submit" disabled={loading || !q.trim()}>
            {loading ? <Icon.Spinner /> : "搜索"}
          </button>
        </form>
      </div>

      {error && (
        <div style={{ margin: "0 0 16px", padding: "10px 14px", background: "#fff0f0", border: "1px solid var(--danger)", borderRadius: 6, fontSize: 12, color: "var(--danger)" }}>
          {error}
        </div>
      )}

      {(searched || loading) && (
        <>
          {/* AI Insight */}
          <div className="insight-card">
            <div className="insight-header">
              <div className="insight-icon">H</div>
              <div className="insight-title">AI 知识库洞察</div>
              <div className="insight-sub">Hermes LLM Wiki</div>
            </div>
            <div className="insight-body">
              {loading ? (
                <div>
                  <div style={{ fontSize: 12, color: "var(--ink-3)", marginBottom: 10, fontFamily: "var(--font-mono)" }}>
                    <Icon.Spinner size={12}/> 正在查询知识库...
                  </div>
                  <div className="skeleton-line" style={{ width: "92%" }} />
                  <div className="skeleton-line" style={{ width: "100%" }} />
                  <div className="skeleton-line" style={{ width: "86%" }} />
                </div>
              ) : insight ? (
                <MarkdownLite text={insight} />
              ) : (
                <div style={{ color: "var(--ink-3)", fontSize: 13 }}>
                  Hermes 未配置或无洞察内容。向量搜索结果如下。
                </div>
              )}
            </div>
          </div>

          {/* Results */}
          {!loading && (
            <>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 12 }}>
                <div style={{ fontSize: 13, color: "var(--ink-2)" }}>
                  <strong style={{color:"var(--ink-1)"}}>{results.length}</strong> 条视频结果 · 按综合评分排序
                </div>
                <div className="btn-row">
                  {vectorCount > 0 && <span className="badge info">向量匹配 {vectorCount}</span>}
                  {aiCount > 0 && <span className="badge warning">AI 引用 {aiCount}</span>}
                  {bothCount > 0 && <span className="badge purple">双重命中 {bothCount}</span>}
                </div>
              </div>

              {results.length === 0 ? (
                <div style={{ padding: "40px 0", textAlign: "center", color: "var(--ink-3)" }}>
                  知识库中暂无相关视频，请先采集一些视频
                </div>
              ) : (
                <div className="result-list">
                  {results.map((r, idx) => {
                    const meta = r.metadata || {};
                    const mechs = (() => { try { return JSON.parse(meta.viral_mechanisms || "[]"); } catch { return []; } })();
                    const platMap = { youtube: PLATFORMS[0], tiktok: PLATFORMS[1], bilibili: PLATFORMS[2] };
                    const plat = platMap[meta.platform] || { id: "?", label: "?", cls: "neutral" };
                    const hue = (r.id || "").split("").reduce((a, c) => a + c.charCodeAt(0), 200) % 360;
                    const scoreDisplay = Math.round((r.score || 0) * 100);
                    return (
                      <div key={r.id || idx} className="result-row" onClick={() => _openDetail(r)}>
                        <div className="result-thumb" style={{ background: `linear-gradient(135deg, oklch(0.78 0.05 ${hue}), oklch(0.5 0.09 ${(hue + 40) % 360}))` }}>
                          <div className="video-thumb-overlay"/>
                          <div style={{ position: "absolute", top: 4, right: 4 }}><PlatformBadge platform={plat}/></div>
                          <div className="video-duration" style={{bottom:4, right:4, fontSize:9.5}}>{formatDuration(meta.duration_sec || 0)}</div>
                        </div>
                        <div>
                          <div className="result-title">{meta.title || r.id}</div>
                          <div className="result-meta">{meta.story_structure || ""} · {formatDate(meta.published_at || "")}</div>
                          <div className="video-mechs">
                            {mechs.slice(0, 4).map(m => <MechBadge key={m} name={m} />)}
                          </div>
                        </div>
                        <div className="result-score">
                          <div>
                            <span className="num">{meta.score_total || "—"}</span>
                            {meta.score_total && <span className="unit"> /100</span>}
                          </div>
                          <div className="source">
                            {r.score_source === "vector" && <span className="badge info">向量匹配</span>}
                            {r.score_source === "hermes_ref" && <span className="badge warning">AI 引用</span>}
                            {r.score_source === "both" && <span className="badge purple">双重命中</span>}
                          </div>
                          <div className="breakdown" title="综合得分">
                            <span>得分 {(r.score || 0).toFixed(3)}</span>
                          </div>
                        </div>
                      </div>
                    );
                  })}
                </div>
              )}
            </>
          )}
        </>
      )}

      {!searched && !loading && (
        <div style={{ padding: "60px 0", textAlign: "center", color: "var(--ink-3)", fontSize: 14 }}>
          输入查询词后按搜索
        </div>
      )}
    </>
  );
}
window.SearchPage = SearchPage;
