// ---------- 8. Alerts ----------
PAGES.alerts = async () => {
  const ws = document.getElementById("workspace");
  ws.innerHTML = `<div class="text-slate-400 text-sm">规则计算中…</div>`;
  try {
    const { count, by_code, items } = await api("/api/alerts");
    const badge = document.getElementById("alert-badge");
    if (badge) {
      if (count > 0) { badge.classList.remove("hidden"); badge.textContent = `! 告警 ${count}`; }
      else { badge.classList.add("hidden"); }
    }
    const legend = `
      <div class="flex gap-3 text-xs flex-wrap">
        <div>${pill("R1 成功率", "red")} 24h 目标成功率 &lt; 80%（样本≥5）</div>
        <div>${pill("R2 风控", "amber")} 1h 同站 403/412/429 &gt; 30%（样本≥10）</div>
        <div>${pill("R3 选择器", "slate")} 目标 24h 内无新文章但前 24h 有</div>
      </div>`;
    const rows = items.map(a => {
      const k = a.code === "R1_SUCCESS_RATE" ? "red"
             : a.code === "R2_BLOCK_RATE"   ? "amber" : "slate";
      return `
        <tr class="border-t border-slate-100">
          <td class="px-4 py-2 text-center">${pill(a.code, k)}</td>
          <td class="px-4 py-2 mono text-xs text-slate-600">${esc(a.site_code || "—")}</td>
          <td class="px-4 py-2 mono text-xs text-slate-600">${esc(a.target_code || "—")}</td>
          <td class="px-4 py-2 text-xs text-slate-700">${esc(a.message)}</td>
        </tr>`;
    }).join("") || `<tr><td colspan="4" class="p-8 text-center text-emerald-700 text-sm">✓ 当前无告警</td></tr>`;
    ws.innerHTML = `
      <div class="card p-4 space-y-3">
        <div class="flex items-center gap-4 text-sm">
          <div class="text-slate-600">共 <span class="font-semibold">${count}</span> 条</div>
          ${Object.entries(by_code || {}).map(([k,n]) => `<div class="mono text-xs text-slate-500">${esc(k)}: ${n}</div>`).join("")}
        </div>
        ${legend}
      </div>` + card({
        title: "告警列表",
        body: `
          <table class="w-full text-sm">
            <thead class="bg-slate-50 text-slate-500 text-xs uppercase">
              <tr>
                <th class="px-4 py-2">规则</th>
                <th class="text-left px-4 py-2">site</th>
                <th class="text-left px-4 py-2">target</th>
                <th class="text-left px-4 py-2">消息</th>
              </tr>
            </thead>
            <tbody>${rows}</tbody>
          </table>`
      });
  } catch (e) {
    ws.innerHTML = `<div class="card p-6 text-sm text-red-600">加载失败：${esc(e.message)}</div>`;
  }
};
