// ---------- 7. Attachments ----------
PAGES.attachments = async () => {
  const ws = document.getElementById("workspace");
  ws.innerHTML = `
    <div class="card p-4">
      <div class="flex gap-2 flex-wrap items-center">
        <input id="at-site" placeholder="site_code" class="border border-slate-200 rounded px-3 py-1.5 text-sm w-32 mono"/>
        <input id="at-target" placeholder="target_code" class="border border-slate-200 rounded px-3 py-1.5 text-sm w-48 mono"/>
        <input id="at-ext" placeholder="ext (pdf / docx…)" class="border border-slate-200 rounded px-3 py-1.5 text-sm w-32 mono"/>
        <input id="at-q" placeholder="文件名关键字" class="border border-slate-200 rounded px-3 py-1.5 text-sm w-64"/>
        <button onclick="loadAttachments()" class="bg-[#1D4ED8] hover:bg-blue-700 text-white text-sm rounded px-4 py-1.5">刷新</button>
      </div>
    </div>
    <div id="at-results"></div>`;
  loadAttachments();
};
function _humanSize(n) {
  if (n == null) return "—";
  const u = ["B","KB","MB","GB"]; let i = 0; let v = Number(n);
  while (v >= 1024 && i < u.length - 1) { v /= 1024; i++; }
  return v.toFixed(v < 10 && i ? 1 : 0) + " " + u[i];
}
const ATTS_STATE = { page: 1, pageSize: 20, rows: [], total: 0 };

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

function _renderAttsTable() {
  const { rows, page, pageSize, total } = ATTS_STATE;
  // Server already paginated — no client slicing.
  const slice = rows;
  document.getElementById("at-results").innerHTML = card({
    title: "附件列表",
    body: `
      <table class="w-full text-sm">
        <thead class="bg-slate-50 text-slate-500 text-xs uppercase">
          <tr>
            <th class="text-left px-4 py-2">文件名</th>
            <th class="px-4 py-2">ext</th>
            <th class="px-4 py-2">大小</th>
            <th class="text-left px-4 py-2">文章</th>
            <th class="px-4 py-2">site</th>
            <th class="px-4 py-2">target</th>
            <th class="px-4 py-2">下载时间</th>
          </tr>
        </thead>
        <tbody>
          ${slice.map(a => `
            <tr class="border-t border-slate-100 hover:bg-slate-50/60">
              <td class="px-4 py-2 mono text-xs max-w-[320px] truncate" title="${esc(a.file_name || "")}">${esc(a.file_name || "—")}</td>
              <td class="px-4 py-2 text-center text-xs">${a.file_ext ? pill(a.file_ext, "blue") : "—"}</td>
              <td class="px-4 py-2 text-right mono text-xs text-slate-500">${_humanSize(a.size_bytes)}</td>
              <td class="px-4 py-2 max-w-[280px] truncate"><a class="hover:underline" target="_blank" href="${esc(a.article_url || "")}">${esc(a.article_title || "(无标题)")}</a></td>
              <td class="px-4 py-2 text-center mono text-xs text-slate-500">${esc(a.site_code || "")}</td>
              <td class="px-4 py-2 text-center mono text-xs text-slate-500">${esc(a.target_code || "")}</td>
              <td class="px-4 py-2 text-center mono text-xs text-slate-500">${fmt(a.downloaded_at)}</td>
            </tr>`).join("") || `<tr><td colspan="7" class="p-8 text-center text-slate-400">无附件</td></tr>`}
        </tbody>
      </table>
      <div id="at-pager"></div>`
  });
  renderPager({
    container: document.getElementById("at-pager"),
    total, page, pageSize,
    summary: `共 ${total} 个附件`,
    // Page change re-fetches from server (real pagination).
    onPage: p => { ATTS_STATE.page = p; loadAttachments({ resetPage: false }); },
  });
}
