{% extends "base.html" %}
{% block title %}{{ t(request, 'page.approval') }} — MoE Admin{% endblock %}

{% block content %}
<div class="d-flex align-items-center justify-content-between mb-3">
  <h5 class="mb-0 fw-bold">
    <i class="bi bi-check2-square me-2 text-primary"></i>{{ t(request, 'page.approval') }}
  </h5>
  <div class="d-flex align-items-center gap-2">
    <span class="text-muted small" id="approval-meta">–</span>
    <button class="btn btn-sm btn-outline-primary" onclick="loadApprovals()">
      <i class="bi bi-arrow-clockwise me-1"></i>{{ t(request, 'btn.refresh') }}
    </button>
  </div>
</div>

<p class="text-muted small">{{ t(request, 'lbl.approval_intro') }}</p>

<div class="card">
  <div class="card-body p-0">
    <div class="table-responsive">
      <table class="table table-sm table-hover mb-0">
        <thead class="table-light">
          <tr>
            <th>{{ t(request, 'lbl.branch') }}</th>
            <th>{{ t(request, 'lbl.source_tag') }}</th>
            <th class="text-end">{{ t(request, 'lbl.entities') }}</th>
            <th>{{ t(request, 'lbl.submitted_at') }}</th>
            <th class="text-end">{{ t(request, 'lbl.actions') }}</th>
          </tr>
        </thead>
        <tbody id="approval-body">
          <tr><td colspan="5" class="text-muted text-center py-3">
            <i class="bi bi-hourglass me-1"></i>{{ t(request, 'lbl.loading') }}
          </td></tr>
        </tbody>
      </table>
    </div>
  </div>
</div>

<div class="alert alert-warning mt-3 d-none" id="approval-status" role="alert"></div>

<script>
function fmtTs(iso) {
  if (!iso) return "–";
  if (typeof iso === "number") return new Date(iso * 1000).toLocaleString();
  try { return new Date(iso).toLocaleString(); } catch (e) { return iso; }
}

async function loadApprovals() {
  document.getElementById("approval-meta").textContent = "{{ t(request, 'lbl.loading') }}";
  try {
    const r = await fetch("/api/approval/list");
    const data = await r.json();
    const pending = data.pending || [];
    const body = document.getElementById("approval-body");
    if (!pending.length) {
      body.innerHTML = `<tr><td colspan="5" class="text-muted text-center py-3">{{ t(request, 'lbl.no_pending') }}</td></tr>`;
      document.getElementById("approval-meta").textContent = "0";
      return;
    }
    body.innerHTML = pending.map(p => {
      const meta = p.metadata || {};
      const tag = meta.source_tag || p.branch.replace(/^pending\//, "").replace(/-\d{8}T\d{6}Z$/, "");
      const count = meta.entity_count || meta.object_count || "–";
      const ts = p.created_at ? fmtTs(p.created_at) : "–";
      return `<tr>
        <td class="font-monospace small">${p.branch.replace(/[<>]/g, "")}</td>
        <td class="small">${tag.replace(/[<>]/g, "")}</td>
        <td class="text-end small">${count}</td>
        <td class="small">${ts}</td>
        <td class="text-end">
          <button class="btn btn-sm btn-success me-1" onclick="approveBranch('${p.branch}')">
            <i class="bi bi-check2"></i> {{ t(request, 'btn.approve') }}
          </button>
          <button class="btn btn-sm btn-outline-danger" onclick="rejectBranch('${p.branch}')">
            <i class="bi bi-x-lg"></i> {{ t(request, 'btn.reject') }}
          </button>
        </td>
      </tr>`;
    }).join("");
    document.getElementById("approval-meta").textContent = String(pending.length);
  } catch (e) {
    console.error("approval fetch failed", e);
  }
}

async function _post(path, body) {
  const r = await fetch(path, {
    method: "POST",
    headers: {"Content-Type": "application/json"},
    body: JSON.stringify(body || {}),
  });
  return await r.json();
}

async function approveBranch(branch) {
  if (!confirm(`{{ t(request, 'lbl.confirm_approve') }}\n\n${branch}`)) return;
  const status = document.getElementById("approval-status");
  status.classList.remove("d-none", "alert-danger", "alert-success");
  status.classList.add("alert-info");
  status.textContent = "{{ t(request, 'lbl.approving') }}…";
  try {
    const data = await _post("/api/approval/approve", {branch});
    if (data.status === "approved") {
      status.classList.remove("alert-info");
      status.classList.add("alert-success");
      const stats = data.imported || {};
      status.innerHTML = `<i class="bi bi-check-circle me-2"></i>${branch} — ` +
        `entities=${stats.entities_added ?? "?"}, relations=${stats.relations_added ?? "?"}`;
    } else {
      status.classList.remove("alert-info");
      status.classList.add("alert-danger");
      status.textContent = data.detail || JSON.stringify(data);
    }
    await loadApprovals();
  } catch (e) {
    status.classList.remove("alert-info");
    status.classList.add("alert-danger");
    status.textContent = String(e);
  }
}

async function rejectBranch(branch) {
  if (!confirm(`{{ t(request, 'lbl.confirm_reject') }}\n\n${branch}`)) return;
  const status = document.getElementById("approval-status");
  status.classList.remove("d-none", "alert-danger", "alert-success");
  status.classList.add("alert-info");
  status.textContent = "{{ t(request, 'lbl.rejecting') }}…";
  try {
    const data = await _post("/api/approval/reject", {branch});
    if (data.status === "rejected") {
      status.classList.remove("alert-info");
      status.classList.add("alert-success");
      status.innerHTML = `<i class="bi bi-trash me-2"></i>${branch} — {{ t(request, 'lbl.rejected') }}`;
    } else {
      status.classList.remove("alert-info");
      status.classList.add("alert-danger");
      status.textContent = data.detail || JSON.stringify(data);
    }
    await loadApprovals();
  } catch (e) {
    status.classList.remove("alert-info");
    status.classList.add("alert-danger");
    status.textContent = String(e);
  }
}

loadApprovals();
</script>
{% endblock %}
