// ---------- 1. Dashboard (采集工作台) ----------
const DASH_STATE = { page: 1, pageSize: 8 };

PAGES.dashboard = async () => {
  const ws = document.getElementById("workspace");
  ws.innerHTML = `<div class="text-slate-400 text-sm">加载中…</div>`;
  try {
    const [s, alertsResp, articlesResp] = await Promise.all([
      api("/api/stats"),
      api("/api/alerts").catch(() => ({ count: 0, items: [] })),
      api("/api/articles/search?limit=50").catch(() => ({ count: 0, items: [] })),
    ]);

    window.__dashArticles = articlesResp.items || [];
    window.__dashAlerts = alertsResp.items || [];

    const statCard = (label, value, tag, tagKind, sub) => `
      <div class="card p-[18px] flex-1 flex flex-col gap-2.5">
        <div class="text-[13px] text-slate-500">${esc(label)}</div>
        <div class="flex items-center justify-between">
          <div class="text-[32px] font-semibold text-slate-900 leading-none">${esc(value)}</div>
          ${tag ? `<span class="pill pill-${tagKind}">${esc(tag)}</span>` : ""}
        </div>
        <div class="text-xs text-slate-400">${esc(sub)}</div>
      </div>`;

    ws.innerHTML = `
      ${pageBanner({
        title: "采集工作台",
        subtitle: "面向清远知识库的数据采集、归集与运行监控总览",
        actions: `
          <button class="btn-outline" onclick="toast('导出报表待接入','err')">导出报表</button>
          <button class="btn-primary" onclick="toast('立即采集指令已记录','ok')">立即采集</button>`
      })}
      <div class="flex gap-4">
        ${statCard("24h 新增文章", s.articles_24h, pct(s.success_rate_24h) + " 成功率", "green", `${s.fetch_attempts_24h} 次抓取 · ${s.ready_articles} ready`)}
        ${statCard("运行中目标", `${s.targets.enabled} / ${s.targets.total}`, "正常", "green", `站点 ${s.sites.enabled}/${s.sites.total} 启用 · 目标 ${s.targets.total} 条`)}
        ${statCard("待导出到 RAG", s.unexported_to_rag, "队列中", "blue", `文章总计 ${s.total_articles} · ready ${s.ready_articles}`)}
        ${statCard("异常与告警", alertsResp.count || 0, (alertsResp.count || 0) > 0 ? "需处理" : "无", (alertsResp.count || 0) > 0 ? "red" : "slate", `服务器时间 ${fmt(s.now)}`)}
      </div>
      <div class="flex gap-5 items-start mt-5">
        <section class="card flex-1 overflow-hidden">
          <header class="flex items-center justify-between px-5 py-4 border-b border-[#E5EBF1]">
            <div>
              <div class="text-[15px] font-semibold text-slate-900">最近采集文档</div>
              <div class="text-xs text-slate-500 mt-0.5">按抓取时间倒序，支持按关键字筛选</div>
            </div>
            <div class="flex gap-2">
              <input id="dash-q" class="h-8 border border-slate-300 rounded px-2 text-xs w-48" placeholder="标题 / target_code…" />
              <button class="btn-outline" onclick="go('articles')">打开文章列表</button>
            </div>
          </header>
          <div id="dash-table"></div>
          <div id="dash-pager"></div>
        </section>
        <aside class="flex flex-col gap-5" style="width:380px; flex:none">
          <section class="card p-5">
            <div class="text-[15px] font-semibold text-slate-900 mb-3">待处理事项</div>
            <div class="space-y-2.5 text-sm">
              ${s.unexported_to_rag > 0 ? `<div class="flex items-start gap-2"><span class="pill pill-amber shrink-0">导出</span><span class="text-slate-700">待导出到 RAG：${s.unexported_to_rag} 篇</span></div>` : ""}
              ${(alertsResp.count || 0) > 0 ? `<div class="flex items-start gap-2"><span class="pill pill-red shrink-0">告警</span><span class="text-slate-700">${alertsResp.count} 条运行告警待处理</span></div>` : ""}
              ${s.targets.total - s.targets.enabled > 0 ? `<div class="flex items-start gap-2"><span class="pill pill-slate shrink-0">停用</span><span class="text-slate-700">${s.targets.total - s.targets.enabled} 个采集目标被停用</span></div>` : ""}
              ${(s.unexported_to_rag || (alertsResp.count || 0) || (s.targets.total - s.targets.enabled)) ? "" : `<div class="text-slate-400 text-xs">✓ 暂无待处理事项</div>`}
            </div>
          </section>
          <section class="card p-5">
            <div class="text-[15px] font-semibold text-slate-900 mb-3">运行告警</div>
            <div class="space-y-2.5 text-sm">
              ${(alertsResp.items || []).slice(0, 5).map(a => {
                const kind = a.code === "R1_SUCCESS_RATE" ? "red" : a.code === "R2_BLOCK_RATE" ? "amber" : "slate";
                return `<div class="flex items-start gap-2">${pill(a.code.replace("_", " "), kind)}<div class="flex-1 min-w-0"><div class="text-slate-700 text-xs">${esc(a.message)}</div><div class="text-[11px] text-slate-400 mono truncate">${esc(a.site_code || "")} ${a.target_code ? "· " + esc(a.target_code) : ""}</div></div></div>`;
              }).join("") || `<div class="text-slate-400 text-xs">✓ 当前无告警</div>`}
            </div>
          </section>
        </aside>
      </div>`;
    document.getElementById("dash-q").oninput = () => { DASH_STATE.page = 1; renderDashTable(); };
    renderDashTable();
  } catch (e) {
    ws.innerHTML = `<div class="card p-6 text-sm text-red-600">加载失败：${esc(e.message)}</div>`;
  }
};

function renderDashTable() {
  const items = window.__dashArticles || [];
  const q = (document.getElementById("dash-q")?.value || "").trim().toLowerCase();
  const filtered = q
    ? items.filter(a => ((a.title || "") + " " + (a.target_code || "") + " " + (a.site_code || "")).toLowerCase().includes(q))
    : items;
  const { page, pageSize } = DASH_STATE;
  const total = filtered.length;
  const start = (page - 1) * pageSize;
  const rows = filtered.slice(start, start + pageSize);
  const body = `
    <table class="w-full text-sm">
      <thead class="bg-slate-50 text-slate-500 text-xs">
        <tr>
          <th class="text-left px-5 py-2.5" style="width:40%">标题</th>
          <th class="text-left px-5 py-2.5" style="width:22%">部门与来源</th>
          <th class="text-left px-5 py-2.5">栏目路径</th>
          <th class="text-left px-5 py-2.5" style="width:130px">公开时间</th>
          <th class="text-left px-5 py-2.5" style="width:130px">抓取时间</th>
        </tr>
      </thead>
      <tbody>
        ${rows.map(a => `
          <tr class="border-t border-slate-100">
            <td class="px-5 py-3"><a href="${esc(a.url)}" target="_blank" class="text-slate-900 hover:underline">${esc(a.title || "(无标题)")}</a></td>
            <td class="px-5 py-3 text-xs"><div class="text-slate-700">${esc(a.site_code || "—")}</div><div class="text-slate-400 mono">${esc(a.target_code || "")}</div></td>
            <td class="px-5 py-3 text-xs text-slate-600 max-w-[260px] truncate" title="${esc(a.channel_path || "")}">${esc(a.channel_path || "—")}</td>
            <td class="px-5 py-3 text-xs mono text-slate-500">${fmt(a.publish_time)}</td>
            <td class="px-5 py-3 text-xs mono text-slate-500">${fmt(a.fetched_at)}</td>
          </tr>`).join("") || `<tr><td colspan="5" class="p-10 text-center text-slate-400 text-sm">暂无采集记录</td></tr>`}
      </tbody>
    </table>`;
  document.getElementById("dash-table").innerHTML = body;
  renderPager({
    container: document.getElementById("dash-pager"),
    total, page, pageSize,
    summary: `共 ${total} 篇最近采集`,
    onPage: p => { DASH_STATE.page = p; renderDashTable(); },
  });
}

