// ---------- 6d. Batch onboarding ----------
async function loadDepartmentOptions() {
  const { items } = await api("/api/local-departments?limit=1000");
  return items || [];
}

async function loadSiteDepartmentOptions() {
  const { items } = await api("/api/departments?limit=500");
  return items || [];
}

async function refreshOnboardingPreview() {
  const ids = Array.from(REGISTRY_SELECTION);
  const box = document.getElementById("ob-preview");
  if (!ids.length) {
    box.innerHTML = `<div class="card p-8 text-center text-slate-400 text-sm">请先去「全局栏目目录」勾选栏目。</div>`;
    return;
  }
  const payload = {
    registry_ids: ids,
    site_department_id: document.getElementById("ob-site-dept").value ? Number(document.getElementById("ob-site-dept").value) : null,
    dept_id: document.getElementById("ob-local-dept").value ? Number(document.getElementById("ob-local-dept").value) : null,
    entry_url_template: document.getElementById("ob-entry-template").value.trim() || null,
    content_category: document.getElementById("ob-cat").value.trim() || null,
    content_subcategory: document.getElementById("ob-subcat").value.trim() || null,
    expected_cadence_days: document.getElementById("ob-cadence").value ? Number(document.getElementById("ob-cadence").value) : null,
    interval_sec: document.getElementById("ob-interval").value ? Number(document.getElementById("ob-interval").value) : null,
  };
  box.innerHTML = `<div class="text-slate-400 text-sm">预览计算中…</div>`;
  try {
    const { count, items } = await api("/api/column-registry/batch-preview", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(payload),
    });
    window.__onboardingPreview = items;
    box.innerHTML = card({
      title: "批量接入预览",
      actions: `<button onclick="runBatchSubscribe()" class="text-xs px-3 py-1 rounded bg-emerald-600 text-white hover:bg-emerald-700">执行批量接入</button>`,
      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="text-left px-4 py-2">栏目</th>
              <th class="text-left px-4 py-2">建议 target_code</th>
              <th class="text-left px-4 py-2">entry_url</th>
              <th class="px-4 py-2">状态</th>
              <th class="text-left px-4 py-2">说明</th>
            </tr>
          </thead>
          <tbody>
            ${items.map(row => `
              <tr class="border-t border-slate-100 hover:bg-slate-50/60">
                <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 mono text-xs">${esc(row.target_code || "—")}</td>
                <td class="px-4 py-2 text-xs max-w-[340px] truncate" title="${esc(row.entry_url || "")}">${esc(row.entry_url || "—")}</td>
                <td class="px-4 py-2 text-center">${row.ready ? pill("可接入", "green") : pill("待补充", "amber")}${row.existing_target_code ? `<div class="mono text-[10px] mt-1 text-slate-500">${esc(row.existing_target_code)}</div>` : ""}</td>
                <td class="px-4 py-2 text-xs text-slate-500">${row.warnings?.length ? row.warnings.map(w => `<div>${esc(w)}</div>`).join("") : "—"}</td>
              </tr>`).join("")}
          </tbody>
        </table>`
    });
  } catch (e) {
    box.innerHTML = `<div class="card p-6 text-sm text-red-600">预览失败：${esc(e.message)}</div>`;
  }
}

async function runBatchSubscribe() {
  const ids = Array.from(REGISTRY_SELECTION);
  if (!ids.length) { toast("请先勾选栏目", "err"); return; }
  const payload = {
    registry_ids: ids,
    site_department_id: document.getElementById("ob-site-dept").value ? Number(document.getElementById("ob-site-dept").value) : null,
    dept_id: document.getElementById("ob-local-dept").value ? Number(document.getElementById("ob-local-dept").value) : null,
    entry_url_template: document.getElementById("ob-entry-template").value.trim() || null,
    content_category: document.getElementById("ob-cat").value.trim() || null,
    content_subcategory: document.getElementById("ob-subcat").value.trim() || null,
    expected_cadence_days: document.getElementById("ob-cadence").value ? Number(document.getElementById("ob-cadence").value) : null,
    interval_sec: document.getElementById("ob-interval").value ? Number(document.getElementById("ob-interval").value) : null,
  };
  try {
    const { count } = await api("/api/column-registry/batch-subscribe", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(payload),
    });
    toast(`已批量接入 ${count} 条`);
    REGISTRY_SELECTION.clear();
    saveRegistrySelection();
    go("subscriptions");
  } catch (e) { toast(e.message, "err"); }
}

PAGES.onboarding = async () => {
  const ws = document.getElementById("workspace");
  ws.innerHTML = `<div class="text-slate-400 text-sm">加载中…</div>`;
  try {
    const [localDepts, siteDepts] = await Promise.all([loadDepartmentOptions(), loadSiteDepartmentOptions()]);
    const localOptions = [`<option value="">— 不绑定 —</option>`]
      .concat(localDepts.map(d => `<option value="${d.dept_id}">${esc(d.dept_id)} · ${esc(d.full_name || d.dept_name || "")}</option>`))
      .join("");
    const siteDeptOptions = [`<option value="">— 不指定 —</option>`]
      .concat(siteDepts.map(d => `<option value="${d.id}">${esc(d.site_code)} · ${esc(d.dept_path)} · ${esc(d.dept_display_name || d.local_dept_full_name || "")}</option>`))
      .join("");
    ws.innerHTML = `
      <div class="card p-4 space-y-4">
        <div class="text-sm text-slate-600">已从栏目目录勾选 <span class="font-semibold">${REGISTRY_SELECTION.size}</span> 条。未勾选时无法预览。</div>
        <div class="grid grid-cols-2 gap-4 text-sm">
          <label class="space-y-1"><div class="text-slate-600">站点部门映射（可选）</div><select id="ob-site-dept" class="w-full border border-slate-200 rounded px-3 py-2">${siteDeptOptions}</select></label>
          <label class="space-y-1"><div class="text-slate-600">本地部门（可选）</div><select id="ob-local-dept" class="w-full border border-slate-200 rounded px-3 py-2">${localOptions}</select></label>
          <label class="space-y-1 col-span-2"><div class="text-slate-600">entry_url_template（可选）</div><input id="ob-entry-template" class="w-full border border-slate-200 rounded px-3 py-2 mono" placeholder="{base_url}/{dept_path}/gkmlpt/index#{column_id}" /></label>
          <label class="space-y-1"><div class="text-slate-600">content_category</div><input id="ob-cat" class="w-full border border-slate-200 rounded px-3 py-2" placeholder="如：规划计划"/></label>
          <label class="space-y-1"><div class="text-slate-600">content_subcategory</div><input id="ob-subcat" class="w-full border border-slate-200 rounded px-3 py-2" placeholder="可选"/></label>
          <label class="space-y-1"><div class="text-slate-600">expected_cadence_days</div><input id="ob-cadence" type="number" value="30" min="1" class="w-full border border-slate-200 rounded px-3 py-2"/></label>
          <label class="space-y-1"><div class="text-slate-600">interval_sec</div><input id="ob-interval" type="number" value="5" min="0" class="w-full border border-slate-200 rounded px-3 py-2"/></label>
        </div>
        <div class="flex gap-2 justify-end">
          <button onclick="go('registry')" class="text-xs px-3 py-1.5 rounded border border-slate-200 hover:bg-slate-50">返回栏目目录</button>
          <button onclick="refreshOnboardingPreview()" class="text-xs px-4 py-1.5 rounded bg-[#1D4ED8] text-white hover:bg-blue-700">生成预览</button>
        </div>
      </div>
      <div id="ob-preview"></div>`;
    refreshOnboardingPreview();
  } catch (e) {
    ws.innerHTML = `<div class="card p-6 text-sm text-red-600">加载失败：${esc(e.message)}</div>`;
  }
}
