// ---------- 5. Logs ----------
PAGES.logs = async () => {
  const ws = document.getElementById("workspace");
  ws.innerHTML = `
    <div class="card p-4">
      <div class="flex gap-2 flex-wrap items-center">
        <input id="l-site" placeholder="site_code" class="border border-slate-200 rounded px-3 py-1.5 text-sm w-32 mono"/>
        <input id="l-target" placeholder="target_code" class="border border-slate-200 rounded px-3 py-1.5 text-sm w-48 mono"/>
        <label class="text-sm flex items-center gap-1.5"><input type="checkbox" id="l-failed" />仅失败</label>
        <button onclick="loadLogs()" class="bg-[#1D4ED8] hover:bg-blue-700 text-white text-sm rounded px-4 py-1.5">刷新</button>
      </div>
    </div>
    <div id="l-results"></div>`;
  loadLogs();
};
const LOGS_STATE = { page: 1, pageSize: 20, rows: [], total: 0 };

async function loadLogs({ resetPage = true } = {}) {
  if (resetPage) LOGS_STATE.page = 1;
  const { page, pageSize } = LOGS_STATE;
  const site = document.getElementById("l-site").value.trim();
  const target = document.getElementById("l-target").value.trim();
  const failed = document.getElementById("l-failed").checked;
  const qs = new URLSearchParams();
  qs.set("limit", String(pageSize));
  qs.set("offset", String((page - 1) * pageSize));
  if (site) qs.set("site", site);
  if (target) qs.set("target", target);
  if (failed) qs.set("only_failed", "true");
  const box = document.getElementById("l-results");
  box.innerHTML = `<div class="text-slate-400 text-sm">加载中…</div>`;
  try {
    const r = await api("/api/logs?" + qs);
    LOGS_STATE.rows = r.items || [];
    LOGS_STATE.total = r.total || 0;
    _renderLogsTable();
  } catch (e) {
    box.innerHTML = `<div class="card p-6 text-sm text-red-600">加载失败：${esc(e.message)}</div>`;
  }
}

function _renderLogsTable() {
  const { rows, page, pageSize, total } = LOGS_STATE;
  // Server already paginated.
  const slice = rows;
  document.getElementById("l-results").innerHTML = card({
    title: "抓取日志",
    body: `
      <table class="w-full text-xs">
        <thead class="bg-slate-50 text-slate-500 uppercase">
          <tr>
            <th class="text-left px-3 py-2">时间</th>
            <th class="text-left px-3 py-2">site</th>
            <th class="text-left px-3 py-2">target</th>
            <th class="text-left px-3 py-2">URL</th>
            <th class="px-3 py-2">策略</th>
            <th class="px-3 py-2">HTTP</th>
            <th class="px-3 py-2">耗时</th>
            <th class="px-3 py-2">结果</th>
            <th class="px-3 py-2">操作</th>
          </tr>
        </thead>
        <tbody>
          ${slice.map(r => `
            <tr class="border-t border-slate-100 hover:bg-slate-50/60">
              <td class="px-3 py-2 mono text-slate-500 whitespace-nowrap">${fmt(r.occurred_at)}</td>
              <td class="px-3 py-2 mono text-slate-500">${esc(r.site_code || "")}</td>
              <td class="px-3 py-2 mono text-slate-500">${esc(r.target_code || "")}</td>
              <td class="px-3 py-2 text-slate-600 max-w-[320px] truncate" title="${esc(r.article_url || "")}">${esc(r.article_url || "")}</td>
              <td class="px-3 py-2 text-center">${esc(r.strategy || "")}</td>
              <td class="px-3 py-2 text-center">${esc(r.http_status || "")}</td>
              <td class="px-3 py-2 text-right">${esc(r.duration_ms || "")}</td>
              <td class="px-3 py-2 text-center">${r.success ? pill("成功","green") : pill("失败","red")}</td>
              <td class="px-3 py-2 text-center">${r.success ? "" : `<button onclick="retryLog(${r.id})" class="text-xs bg-[#1D4ED8] text-white rounded px-2 py-1">重试</button>`}</td>
            </tr>
            ${r.error_msg ? `<tr class="bg-red-50/40"><td colspan="9" class="px-3 py-1.5 text-[11px] text-red-700 mono">↳ ${esc(r.error_msg)}</td></tr>` : ""}
          `).join("") || `<tr><td colspan="9" class="p-6 text-center text-slate-400">暂无记录</td></tr>`}
        </tbody>
      </table>
      <div id="l-pager"></div>`
  });
  renderPager({
    container: document.getElementById("l-pager"),
    total, page, pageSize,
    summary: `共 ${total} 条`,
    onPage: p => { LOGS_STATE.page = p; loadLogs({ resetPage: false }); },
  });
}
async function retryLog(id) {
  try {
    await api(`/api/logs/${id}/retry`, { method: "POST" });
    toast("已排队重试");
    setTimeout(loadLogs, 1500);
  } catch (e) { toast(e.message, "err"); }
}
