(function () {
  const meta = document.querySelector('meta[name="reserve-api-base"]');
  const apiBase = (meta && meta.content) || '/api/v1';
  const institutional = document.body.dataset.institutional === '1';

  const els = {
    status: document.getElementById('load-status'),
    refreshed: document.getElementById('refreshed-at'),
    quorum: document.getElementById('quorum-summary'),
    metrics: document.getElementById('metrics-grid'),
    proof: document.getElementById('proof-points'),
    gate: document.getElementById('gate-kv'),
    triple: document.getElementById('triple-kv'),
    raw: document.getElementById('raw-json'),
    rawSection: document.getElementById('raw-section'),
  };

  function fmtUsd(n) {
    if (n == null || Number.isNaN(n)) return '—';
    if (n >= 1e12) return `$${(n / 1e12).toFixed(3)}T`;
    if (n >= 1e9) return `$${(n / 1e9).toFixed(2)}B`;
    if (n >= 1e6) return `$${(n / 1e6).toFixed(2)}M`;
    return `$${n.toLocaleString(undefined, { maximumFractionDigits: 2 })}`;
  }

  function fmtBps(bps) {
    if (bps == null) return '—';
    const pct = Number(bps) / 100;
    return `${pct.toFixed(2)}% (${bps} bps)`;
  }

  function badge(status) {
    const s = status || 'skip';
    return `<span class="badge ${s}">${s}</span>`;
  }

  function kv(rows) {
    return rows
      .map(([k, v]) => `<div class="metric"><div class="label">${k}</div><div class="value small">${v}</div></div>`)
      .join('');
  }

  async function load(refresh) {
    els.status.className = 'status-bar loading';
    els.status.textContent = 'Loading reserve capacity…';
    try {
      const url = `${apiBase}/reserve/capacity${refresh ? '?refresh=1' : ''}`;
      const res = await fetch(url, { cache: 'no-store' });
      const data = await res.json();
      if (data.error) throw new Error(data.error);

      const q = data.proofQuorum || {};
      const cap = data.capacity || {};
      const passed = !!q.passed;

      els.status.className = `status-bar ${passed ? 'pass' : 'fail'}`;
      els.status.textContent = passed
        ? `Proof quorum PASS (${q.passCount}/${q.requiredCount}) — semi-public live attestation`
        : `Proof quorum PARTIAL (${q.passCount}/${q.requiredCount}) — see proof points below`;

      els.refreshed.textContent = `Snapshot: ${data.generatedAt} · SLA freshness ≤ ${data.sla?.freshnessMaxAgeSeconds ?? 60}s`;

      els.quorum.innerHTML = kv([
        ['Minimum set', data.minimumSet || 'reserveCapacityLive'],
        ['Quorum', `${q.passCount ?? 0} / ${q.requiredCount ?? 3} (need ${q.minimumRequired ?? 3})`],
        ['Issuance', cap.issuanceBlocked ? 'BLOCKED' : 'Allowed'],
        ['Coverage', fmtBps(cap.coverageRatioBps)],
      ]);

      els.metrics.innerHTML = kv([
        ['Physical reserve (USD)', fmtUsd(cap.reserveUsd)],
        ['M1 c* circulating', fmtUsd(cap.m1Usd)],
        ['M00 Li* notional', fmtUsd(cap.m00Usd)],
        ['Velocity zone', cap.velocityZone || '—'],
        ['Block reasons', (cap.issuanceBlockReasons || []).join(', ') || 'none'],
      ]);

      const points = q.points || {};
      els.proof.innerHTML = Object.values(points)
        .map((p) => `<div class="proof-row"><div class="proof-id">${p.id}</div><div><strong>${p.name || ''}</strong><div class="proof-detail">${p.detail || ''}</div></div>${badge(p.status)}</div>`)
        .join('') || '<p class="sub">No proof points in response.</p>';

      const g = data.onChainGate || {};
      els.gate.innerHTML = kv([
        ['Gate address', g.address ? `<code>${g.address}</code>` : '—'],
        ['RPC reachable', g.rpcReachable ? 'yes' : 'no'],
        ['Coverage (on-chain)', g.coverageRatioBps != null ? fmtBps(g.coverageRatioBps) : '—'],
        ['M1/M00 util', g.m1ToM00Utilization != null ? String(g.m1ToM00Utilization) : '—'],
        ['Issuance paused', g.issuancePaused == null ? '—' : String(g.issuancePaused)],
      ]);

      const t = data.tripleState || {};
      els.triple.innerHTML = kv([
        ['Aligned', t.aligned == null ? '—' : String(t.aligned)],
        ['Breaks', t.breaksCount != null ? String(t.breaksCount) : '—'],
        ['As of', t.generatedAt || '—'],
      ]);

      els.raw.textContent = JSON.stringify(data, null, 2);
    } catch (e) {
      els.status.className = 'status-bar fail';
      els.status.textContent = `Error: ${e.message || e}`;
    }
  }

  document.getElementById('btn-refresh')?.addEventListener('click', () => load(true));
  document.getElementById('btn-toggle-raw')?.addEventListener('click', () => {
    els.rawSection?.classList.toggle('hidden');
  });

  if (institutional) {
    setInterval(() => load(false), 30000);
  }
  load(false);
})();
