// ---------- 6b. Global Column Registry ----------
PAGES.registry = async () => {
  const ws = document.getElementById("workspace");
  ws.innerHTML = `
    <div class="card p-4">
      <div class="flex gap-2 flex-wrap items-center">
        <input id="r-q" placeholder="栏目名 / 路径 / column_id" class="border border-slate-200 rounded px-3 py-1.5 text-sm w-72"/>
        <input id="r-site" placeholder="site_code" class="border border-slate-200 rounded px-3 py-1.5 text-sm w-32 mono"/>
        <input id="r-adapter" placeholder="adapter_id" class="border border-slate-200 rounded px-3 py-1.5 text-sm w-32 mono"/>
        <input id="r-topic" placeholder="topic tag" class="border border-slate-200 rounded px-3 py-1.5 text-sm w-32"/>
        <select id="r-sub" class="border border-slate-200 rounded px-3 py-1.5 text-sm">
          <option value="">全部订阅状态</option>
          <option value="yes">已订阅</option>
          <option value="no">未订阅</option>
        </select>
        <button onclick="loadRegistry()" class="bg-[#1D4ED8] hover:bg-blue-700 text-white text-sm rounded px-4 py-1.5">刷新</button>
        <button onclick="go('onboarding')" class="text-sm rounded px-4 py-1.5 border border-slate-200 hover:bg-slate-50">批量接入</button>
      </div>
    </div>
    <div id="r-results"></div>`;
  loadRegistry();
};
function toggleRegistryRow(id, checked) {
  if (checked) REGISTRY_SELECTION.add(id);
  else REGISTRY_SELECTION.delete(id);
  saveRegistrySelection();
  const c = document.getElementById("r-selected-count");
  if (c) c.textContent = REGISTRY_SELECTION.size;
}
function toggleRegistryAll(source) {
  document.querySelectorAll(".registry-check").forEach(el => {
    el.checked = source.checked;
    toggleRegistryRow(Number(el.value), source.checked);
  });
}
function clearRegistrySelection() {
  REGISTRY_SELECTION.clear();
  saveRegistrySelection();
  loadRegistry();
}
function queueSingleRegistry(id) {
  REGISTRY_SELECTION = new Set([id]);
  saveRegistrySelection();
  go("onboarding");
}
const REGISTRY_STATE = { page: 1, pageSize: 20, rows: [] };

async function loadRegistry() {
  const qs = new URLSearchParams({ limit: "500" });
  [["q","r-q"],["site","r-site"],["adapter","r-adapter"],["topic","r-topic"],["subscribed","r-sub"]].forEach(([k,id]) => {
    const v = document.getElementById(id).value.trim();
    if (v) qs.set(k, v);
  });
  const box = document.getElementById("r-results");
  box.innerHTML = `<div class="text-slate-400 text-sm">加载中…</div>`;
  try {
    const { items } = await api("/api/column-registry?" + qs);
    REGISTRY_STATE.rows = items;
    REGISTRY_STATE.page = 1;
    _renderRegistryTable();
  } catch (e) {
    box.innerHTML = `<div class="card p-6 text-sm text-red-600">加载失败：${esc(e.message)}</div>`;
  }
}

function _renderRegistryTable() {
  const { rows, page, pageSize } = REGISTRY_STATE;
  const total = rows.length;
  const slice = rows.slice((page - 1) * pageSize, page * pageSize);
  document.getElementById("r-results").innerHTML = card({
    title: "全局栏目目录",
    actions: `<div class="text-xs text-slate-500">已勾选 <span id="r-selected-count">${REGISTRY_SELECTION.size}</span> 条</div>
      <button onclick="clearRegistrySelection()" class="text-xs px-3 py-1 rounded border border-slate-200">清空勾选</button>
      <button onclick="go('onboarding')" class="text-xs px-3 py-1 rounded bg-[#1D4ED8] text-white">打开批量接入</button>`,
    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"><input type="checkbox" onclick="toggleRegistryAll(this)"/></th>
            <th class="text-left px-4 py-2">站点</th>
            <th class="text-left px-4 py-2">栏目</th>
            <th class="text-left px-4 py-2">路径</th>
            <th class="px-4 py-2">topic_tags</th>
            <th class="px-4 py-2">文章数</th>
            <th class="px-4 py-2">最近探测</th>
            <th class="px-4 py-2">订阅状态</th>
            <th class="px-4 py-2 text-right">操作</th>
          </tr>
        </thead>
        <tbody>
          ${slice.map(row => `
            <tr class="border-t border-slate-100 hover:bg-slate-50/60">
              <td class="px-4 py-2 text-center"><input class="registry-check" type="checkbox" value="${row.id}" ${REGISTRY_SELECTION.has(row.id) ? "checked" : ""} onchange="toggleRegistryRow(${row.id}, this.checked)"/></td>
              <td class="px-4 py-2 text-xs"><div>${esc(row.site_name || "")}</div><div class="mono text-slate-500">${esc(row.site_code || "")}</div></td>
              <td class="px-4 py-2 text-xs"><div>${esc(row.column_name || "—")}</div><div class="mono text-slate-500">${esc(row.column_id)}</div></td>
              <td class="px-4 py-2 text-xs text-slate-500 max-w-[260px] truncate" title="${esc(row.column_path || "")}">${esc(row.column_path || "—")}</td>
              <td class="px-4 py-2 text-center text-xs">${(row.topic_tags || []).length ? (row.topic_tags || []).map(t => pill(t, "slate")).join(" ") : "—"}</td>
              <td class="px-4 py-2 text-center text-xs">${row.post_count ?? "—"}</td>
              <td class="px-4 py-2 text-center mono text-xs text-slate-500">${fmt(row.last_seen_at)}</td>
              <td class="px-4 py-2 text-center">${row.target_code ? pill("已订阅", "green") + `<div class="mono text-[10px] mt-1 text-slate-500">${esc(row.target_code)}</div>` : pill("未订阅", "amber")}</td>
              <td class="px-4 py-2 text-right">
                <button onclick="queueSingleRegistry(${row.id})" class="text-xs px-2 py-1 rounded border border-slate-200 hover:bg-slate-50">${row.target_code ? "重新订阅" : "订阅"}</button>
              </td>
            </tr>`).join("") || `<tr><td colspan="9" class="p-8 text-center text-slate-400">无栏目记录</td></tr>`}
        </tbody>
      </table>
      <div id="r-pager"></div>`
  });
  renderPager({
    container: document.getElementById("r-pager"),
    total, page, pageSize,
    summary: `共 ${total} 条栏目`,
    onPage: p => { REGISTRY_STATE.page = p; _renderRegistryTable(); },
  });
}
