/* Skills — admin table。真实接 /api/skills。 */

function Skills({ onJump }) {
  const [view, setView]     = React.useState("table");
  const [skills, setSkills] = React.useState([]);
  const [activeId, setActiveId] = React.useState(null);

  const refresh = React.useCallback(async () => {
    const r = await API.get("/api/skills");
    if (!r.error) {
      const list = r.skills || [];
      setSkills(list);
      if (!activeId && list.length > 0) setActiveId(list[0].id);
    }
  }, [activeId]);

  React.useEffect(() => {
    refresh();
    const id = setInterval(refresh, 30000);
    return () => clearInterval(id);
  }, [refresh]);

  const active = skills.find(s => s.id === activeId);

  const hits24 = skills.reduce((a, s) => a + s.hits_24h, 0);
  const hits7d = skills.reduce((a, s) => a + s.hits_7d,  0);
  const totalChars = skills.reduce((a, s) => a + s.chars, 0);

  const reload = async () => {
    const r = await API.post("/api/skills/reload");
    if (r.error) alert("重载失败：" + r.error);
    else { alert("已重新扫描"); refresh(); }
  };

  return (
    <div data-screen-label="05 技能">
      <PageHeader
        title="技能"
        sub={`${skills.length} 个已注册 · 关键词匹配 · 协议: SKILL.md`}
        actions={
          <>
            <Segmented value={view} onChange={setView} options={[
              { id: "table", label: "表格" },
              { id: "grid",  label: "卡片" },
            ]} />
            <button className="btn btn-secondary" onClick={reload}><Icon name="refresh" size={13}/>重新扫描</button>
            <button className="btn btn-primary" onClick={() => {
              alert("新建 skill：请在 skills/ 下新建一个目录，放入带 frontmatter 的 SKILL.md，然后点'重新扫描'");
            }}><Icon name="plus" size={13} color="#fff"/>新建技能</button>
          </>
        }
      />

      <div className="page-body">
        <div className="grid-4">
          <StatCard label="已注册" value={skills.length} sub={`${API.fmtNumber(totalChars)} 字`} />
          <StatCard label="24h 命中" value={hits24} sub={hits24 > 0 ? "活跃" : "无"} />
          <StatCard label="7d 命中" value={hits7d} sub="" />
          <StatCard label="目录" value={skills.length > 0 ? "./skills" : "—"} sub="协议: SKILL.md" />
        </div>

        {view === "table" ? (
          <div style={{ display: "grid", gridTemplateColumns: "1fr 360px", gap: 16, marginTop: 16 }}>
            <div className="card">
              <CardHeader
                title="已注册 skill"
                sub="按 24h 命中排序"
                right={
                  <div className="search-wrap" style={{ width: 200 }}>
                    <span className="search-icon"><Icon name="search" size={13} color="var(--ink-48)"/></span>
                    <input className="search" placeholder="搜索"/>
                  </div>
                } />
              {skills.length === 0 ? (
                <div style={{ padding: 32, textAlign: "center", color: "var(--ink-60)" }} className="t-meta">暂无 skill</div>
              ) : (
              <table className="tbl">
                <thead>
                  <tr>
                    <th style={{ width: 36 }}></th>
                    <th>Skill</th>
                    <th style={{ width: 240 }}>关键词</th>
                    <th style={{ width: 80, textAlign: "right" }}>24h</th>
                    <th style={{ width: 80, textAlign: "right" }}>7d</th>
                    <th style={{ width: 36 }}></th>
                  </tr>
                </thead>
                <tbody>
                  {skills.map(s => (
                    <tr key={s.id} onClick={() => setActiveId(s.id)} style={{ cursor: "pointer", background: activeId === s.id ? "var(--primary-soft)" : "transparent" }}>
                      <td><span className={`dot ${s.hits_24h > 0 ? "dot-up" : "dot-off"}`} /></td>
                      <td>
                        <div className="t-mono-strong" style={{ color: activeId === s.id ? "var(--primary)" : "var(--ink)" }}>{s.name}</div>
                        <div className="t-meta" style={{ marginTop: 3 }}>{s.description.slice(0, 80)}</div>
                      </td>
                      <td>
                        <div style={{ display: "flex", gap: 4, flexWrap: "wrap" }}>
                          {(s.keywords || []).slice(0, 4).map(t => <span key={t} className="chip" style={{ fontSize: 10.5 }}>{t}</span>)}
                          {(s.keywords || []).length > 4 && <span className="t-meta">+{s.keywords.length - 4}</span>}
                        </div>
                      </td>
                      <td className="col-num" style={{ color: s.hits_24h ? "var(--primary)" : "var(--ink-60)" }}>{s.hits_24h}</td>
                      <td className="col-num">{s.hits_7d}</td>
                      <td><button className="btn-icon"><Icon name="chevron-r" size={14}/></button></td>
                    </tr>
                  ))}
                </tbody>
              </table>
              )}
            </div>

            {active && <SkillDetail s={active} />}
          </div>
        ) : (
          <div className="grid-3" style={{ marginTop: 16 }}>
            {skills.map(s => <SkillCard key={s.id} s={s} onClick={() => { setActiveId(s.id); setView("table"); }} />)}
          </div>
        )}
      </div>
    </div>
  );
}

function SkillDetail({ s }) {
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
      <div className="card">
        <CardHeader
          title={s.name}
          sub={s.description.slice(0, 60)}
          right={<span className="chip chip-success">已加载</span>}
        />
        <div className="card-body">
          <p className="t-body" style={{ margin: 0, marginBottom: 16 }}>{s.description}</p>
          <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
            <KV k="目录"     v={s.source.split(/[\\/]/).slice(-2).join("/")} />
            <KV k="字数"     v={`${API.fmtNumber(s.chars)} 字`} />
            <KV k="关键词"   v={(s.keywords || []).join(", ") || "—"} />
            <KV k="优先级"   v={s.priority === 0 ? "project" : s.priority === 1 ? "global" : "repo"} />
            <KV k="24h 命中" v={s.hits_24h} accent={s.hits_24h ? "var(--primary)" : undefined} />
          </div>
        </div>
      </div>

      <div className="card">
        <CardHeader title="SKILL.md frontmatter" />
        <pre style={{
          margin: 0, padding: "16px 20px",
          fontFamily: "var(--font-mono)", fontSize: 11.5, lineHeight: 1.7,
          color: "var(--ink-80)", whiteSpace: "pre-wrap",
          background: "var(--pearl)", borderTop: "1px solid var(--hairline)",
        }}>{`---
name: ${s.name}
description: ${s.description}
keywords: [${(s.keywords || []).map(k => `"${k}"`).join(", ")}]
---`}</pre>
      </div>
    </div>
  );
}

function SkillCard({ s, onClick }) {
  return (
    <div className="card" onClick={onClick} style={{ cursor: "pointer" }}>
      <div className="card-padded" style={{ paddingBottom: 14 }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start" }}>
          <div>
            <div className="t-mono-strong">{s.name}</div>
            <div className="t-card-title" style={{ marginTop: 4 }}>{s.description.slice(0, 30)}</div>
          </div>
          <span className="chip chip-success chip-dot">已加载</span>
        </div>
        <p className="t-body" style={{ margin: "12px 0 0", minHeight: 60 }}>{s.description}</p>
      </div>
      <div style={{ padding: "12px 20px", borderTop: "1px solid var(--hairline)", background: "var(--pearl)" }}>
        <div style={{ display: "flex", gap: 4, flexWrap: "wrap", marginBottom: 12 }}>
          {(s.keywords || []).slice(0, 6).map(t => <span key={t} className="chip" style={{ fontSize: 10.5 }}>{t}</span>)}
        </div>
        <div style={{ display: "flex", justifyContent: "space-between" }}>
          <span className="t-meta">{API.fmtNumber(s.chars)} 字</span>
          <span className="t-mono-sm" style={{ color: s.hits_24h ? "var(--primary)" : "var(--ink-60)" }}>{s.hits_24h} 命中 / 24h</span>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Skills });
