// ---------- 采集目标统计分析 ----------
// Two-level drill-down:
//   level 1 (default)  → site cards/table; click row to drill in
//   level 2 (drilled)  → all targets under one site, sortable
// Click target_code from level 2 → opens 文章列表 filtered to that target.

const STATS_STATE = { level: "sites", site: null, sortBy: "article_count", sortDir: "desc" };

PAGES.stats = async () => {
  const ws = document.getElementById("workspace");
  ws.innerHTML = `<div class="text-slate-400 text-sm">加载中…</div>`;
  if (STATS_STATE.level === "site" && STATS_STATE.site) {
    await _renderTargetStats(STATS_STATE.site);
  } else {
    STATS_STATE.level = "sites";
    await _renderSiteStats();
  }
};

async function _renderSiteStats() {
  const ws = document.getElementById("workspace");
  try {
    const r = await api("/api/stats/by-site");
    const sites = r.sites || [];
    // Aggregate footer
    const total = sites.reduce((acc, s) => {
      acc.targets += s.target_count;
      acc.target_enabled += s.target_enabled_count;
      acc.articles += s.article_count;
      acc.ready += s.ready_count;
      acc.articles_24h += s.articles_24h;
      return acc;
    }, { targets: 0, target_enabled: 0, articles: 0, ready: 0, articles_24h: 0 });

    const adapterPill = a => {
      const colors = { gkmlpt: "blue", yaml: "green", unset: "slate" };
      return pill(a, colors[a] || "slate");
    };

    ws.innerHTML = `
      ${pageBanner({
        title: "采集目标统计分析",
        subtitle: "按站点鸟瞰 → 点击行钻入查看该站点下全部 target 明细"
      })}
      <div class="grid grid-cols-4 gap-4">
        ${statCard("已配置站点", sites.length, sites.filter(s => s.enabled).length + " 启用", "blue", "")}
        ${statCard("采集目标总数", total.targets, total.target_enabled + " 启用", "green", "")}
        ${statCard("已抓文章", total.articles.toLocaleString(), total.ready + " ready", "amber", "")}
        ${statCard("24 小时新增", total.articles_24h, "ready 状态", "slate", "")}
      </div>
      ${card({
        body: `
          <div class="px-5 py-3 border-b border-[#E5EBF1] flex items-center justify-between">
            <div class="text-sm font-semibold text-slate-700">站点级别 · 按文章数倒序</div>
            <div class="text-[11px] text-slate-500">点击站点行 → 进入该站点 target 列表</div>
          </div>
          <div class="overflow-x-auto">
            <table class="w-full text-sm">
              <thead class="bg-slate-50 text-slate-500 text-xs">
                <tr>
                  <th class="text-left px-4 py-2.5">站点</th>
                  <th class="text-left px-4 py-2.5" style="width:90px">范式</th>
                  <th class="text-left px-4 py-2.5" style="width:80px">状态</th>
                  <th class="text-right px-4 py-2.5" style="width:100px">target</th>
                  <th class="text-right px-4 py-2.5" style="width:120px">文章总数</th>
                  <th class="text-right px-4 py-2.5" style="width:100px">ready</th>
                  <th class="text-right px-4 py-2.5" style="width:100px">24h 新增</th>
                  <th class="text-right px-4 py-2.5" style="width:100px">24h 成功率</th>
                  <th class="text-left px-4 py-2.5" style="width:160px">最后抓取</th>
                </tr>
              </thead>
              <tbody>
                ${sites.map(s => `
                  <tr class="border-t border-slate-100 hover:bg-blue-50 cursor-pointer" onclick="_drillIntoSite('${esc(s.site_code)}')">
                    <td class="px-4 py-2.5">
                      <div class="text-slate-900 font-medium">${esc(s.site_name || s.site_code)}</div>
                      <div class="text-[11px] text-slate-400 mono">${esc(s.site_code)}</div>
                    </td>
                    <td class="px-4 py-2.5">${adapterPill(s.adapter_type)}</td>
                    <td class="px-4 py-2.5">${s.enabled ? pill("启用","green") : pill("停用","slate")}</td>
                    <td class="px-4 py-2.5 text-right mono">
                      <div class="text-slate-900">${s.target_count}</div>
                      <div class="text-[11px] text-slate-400">${s.target_enabled_count} 启用</div>
                    </td>
                    <td class="px-4 py-2.5 text-right mono text-slate-900 font-medium">${s.article_count.toLocaleString()}</td>
                    <td class="px-4 py-2.5 text-right mono text-emerald-600">${s.ready_count.toLocaleString()}</td>
                    <td class="px-4 py-2.5 text-right mono ${s.articles_24h > 0 ? "text-emerald-600" : "text-slate-400"}">${s.articles_24h}</td>
                    <td class="px-4 py-2.5 text-right mono text-xs ${s.success_rate_24h == null ? "text-slate-400" : (s.success_rate_24h >= 0.9 ? "text-emerald-600" : s.success_rate_24h >= 0.6 ? "text-amber-600" : "text-red-600")}">
                      ${s.success_rate_24h == null ? "—" : (s.success_rate_24h * 100).toFixed(1) + "%"}
                      <div class="text-[10px] text-slate-400">${s.fetch_attempts_24h} 次</div>
                    </td>
                    <td class="px-4 py-2.5 text-xs mono text-slate-500">${s.last_crawled_at ? esc(s.last_crawled_at.replace("T"," ").slice(0,16)) : "—"}</td>
                  </tr>`).join("") || `<tr><td colspan="9" class="p-10 text-center text-slate-400 text-sm">无站点</td></tr>`}
              </tbody>
            </table>
          </div>`
      })}`;
  } catch (e) {
    ws.innerHTML = `<div class="card p-6 text-sm text-red-600">加载失败：${esc(e.message)}</div>`;
  }
}

function _drillIntoSite(siteCode) {
  STATS_STATE.level = "site";
  STATS_STATE.site = siteCode;
  PAGES.stats();
}

async function _renderTargetStats(siteCode) {
  const ws = document.getElementById("workspace");
  try {
    const r = await api("/api/stats/by-target?site=" + encodeURIComponent(siteCode));
    const items = r.targets || [];
    const total = items.reduce((acc, t) => {
      acc.articles += t.article_count;
      acc.ready += t.ready_count;
      acc.articles_24h += t.articles_24h;
      return acc;
    }, { articles: 0, ready: 0, articles_24h: 0 });
    const siteName = items.length ? items[0].site_name : siteCode;

    // Sort by current sort key
    const cmp = (a, b) => {
      const dir = STATS_STATE.sortDir === "asc" ? 1 : -1;
      const va = a[STATS_STATE.sortBy], vb = b[STATS_STATE.sortBy];
      if (va == null) return 1;
      if (vb == null) return -1;
      if (typeof va === "number") return dir * (va - vb);
      return dir * String(va).localeCompare(String(vb));
    };
    items.sort(cmp);

    const sortIcon = key => STATS_STATE.sortBy === key
      ? (STATS_STATE.sortDir === "asc" ? " ▲" : " ▼")
      : "";
    const sortHeader = (key, label, extra = "") =>
      `<th class="text-left px-4 py-2.5 cursor-pointer hover:text-slate-900 ${extra}" onclick="_statsSort('${key}')">${label}${sortIcon(key)}</th>`;

    ws.innerHTML = `
      ${pageBanner({
        title: `${siteName} · target 明细`,
        subtitle: `共 ${items.length} 个 target · 文章 ${total.articles.toLocaleString()} 条 · 24h 新增 ${total.articles_24h}`
      })}
      <div class="card p-3 mb-3 flex items-center gap-2">
        <button class="btn-outline" onclick="_statsBackToSites()">← 返回站点列表</button>
        <div style="flex:1"></div>
        <button class="btn-outline" onclick="_jumpToTargetsPage('${esc(siteCode)}')">在「采集目标管理」中查看</button>
        <button class="btn-outline" onclick="_jumpToArticlesPage('${esc(siteCode)}', null)">查看该站点全部文章</button>
      </div>
      ${card({
        body: `
          <div class="overflow-x-auto">
            <table class="w-full text-sm">
              <thead class="bg-slate-50 text-slate-500 text-xs">
                <tr>
                  ${sortHeader("target_code", "target")}
                  ${sortHeader("content_category", "分类", 'style="width:100px"')}
                  ${sortHeader("article_count", "文章", 'style="width:90px;text-align:right"')}
                  ${sortHeader("ready_count", "ready", 'style="width:80px;text-align:right"')}
                  ${sortHeader("articles_24h", "24h", 'style="width:80px;text-align:right"')}
                  ${sortHeader("success_rate_24h", "24h成功率", 'style="width:110px;text-align:right"')}
                  ${sortHeader("expected_cadence_days", "节奏", 'style="width:80px"')}
                  ${sortHeader("last_crawled_at", "最后抓取", 'style="width:140px"')}
                  ${sortHeader("created_at", "创建", 'style="width:140px"')}
                  <th class="text-right px-4 py-2.5" style="width:140px">操作</th>
                </tr>
              </thead>
              <tbody>
                ${items.map(t => `
                  <tr class="border-t border-slate-100 hover:bg-slate-50/60">
                    <td class="px-4 py-2.5">
                      <div class="text-slate-900">${esc(t.target_name || t.target_code)}</div>
                      <div class="text-[11px] text-slate-400 mono">${esc(t.target_code)}</div>
                      <div class="text-[11px] text-slate-500 truncate max-w-[280px]" title="${esc(t.channel_path || "")}">${esc(t.channel_path || "—")}</div>
                    </td>
                    <td class="px-4 py-2.5 text-xs">${t.content_category ? pill(t.content_category, "blue") : `<span class="text-slate-400">—</span>`}</td>
                    <td class="px-4 py-2.5 text-right mono ${t.article_count > 0 ? "text-slate-900 font-medium" : "text-slate-400"}">${t.article_count}</td>
                    <td class="px-4 py-2.5 text-right mono text-emerald-600">${t.ready_count}</td>
                    <td class="px-4 py-2.5 text-right mono ${t.articles_24h > 0 ? "text-emerald-600" : "text-slate-400"}">${t.articles_24h}</td>
                    <td class="px-4 py-2.5 text-right mono text-xs ${t.success_rate_24h == null ? "text-slate-400" : (t.success_rate_24h >= 0.9 ? "text-emerald-600" : t.success_rate_24h >= 0.6 ? "text-amber-600" : "text-red-600")}">
                      ${t.success_rate_24h == null ? "—" : (t.success_rate_24h * 100).toFixed(1) + "%"}
                    </td>
                    <td class="px-4 py-2.5 text-xs">
                      <div class="text-slate-700">每 ${t.expected_cadence_days || "—"} 天</div>
                      <div class="text-slate-400">${t.interval_sec != null ? t.interval_sec + "s 间隔" : ""}${t.interval_jitter_sec ? ` +0-${esc(t.interval_jitter_sec)}s` : ""}</div>
                    </td>
                    <td class="px-4 py-2.5 text-xs mono text-slate-500">${t.last_crawled_at ? esc(t.last_crawled_at.replace("T"," ").slice(0,16)) : "—"}</td>
                    <td class="px-4 py-2.5 text-xs mono text-slate-500">${t.created_at ? esc(t.created_at.replace("T"," ").slice(0,16)) : "—"}</td>
                    <td class="px-4 py-2.5 text-right whitespace-nowrap">
                      <button onclick="_jumpToArticlesPage('${esc(t.site_code)}', '${esc(t.target_code)}')" class="text-xs px-2 py-1 rounded border border-slate-200 text-slate-700 hover:bg-slate-50">看文章</button>
                    </td>
                  </tr>`).join("") || `<tr><td colspan="10" class="p-10 text-center text-slate-400 text-sm">该站点无 target</td></tr>`}
              </tbody>
            </table>
          </div>`
      })}`;
  } catch (e) {
    ws.innerHTML = `<div class="card p-6 text-sm text-red-600">加载失败：${esc(e.message)}</div>`;
  }
}

function _statsSort(key) {
  if (STATS_STATE.sortBy === key) {
    STATS_STATE.sortDir = STATS_STATE.sortDir === "asc" ? "desc" : "asc";
  } else {
    STATS_STATE.sortBy = key;
    STATS_STATE.sortDir = key.endsWith("_at") || key === "target_code" ? "desc" : "desc";
  }
  PAGES.stats();
}

function _statsBackToSites() {
  STATS_STATE.level = "sites";
  STATS_STATE.site = null;
  PAGES.stats();
}

function _jumpToArticlesPage(siteCode, targetCode) {
  // Stash desired filters in ARTICLES_STATE before navigation. PAGES.articles
  // consumes them within the same render cycle (sets <select> values BEFORE
  // its initial searchArticles() runs), so only one fetch fires and we can't
  // race the empty-filter default.
  if (typeof ARTICLES_STATE !== "undefined") {
    ARTICLES_STATE.pendingSite = siteCode || "";
    ARTICLES_STATE.pendingTarget = targetCode || "";
  }
  go("articles");
}

function _jumpToTargetsPage(siteCode) {
  go("targets");
  setTimeout(() => {
    if (typeof TARGETS_STATE !== "undefined") {
      TARGETS_STATE.site = siteCode;
      TARGETS_STATE.page = 1;
    }
    const f = document.getElementById("t-site-f");
    if (f) f.value = siteCode;
    if (typeof renderTargetsTable === "function") renderTargetsTable();
  }, 200);
}
