// live-data.jsx — live backend probes and summary counts.
(function () {
  async function refreshLiveSummary() {
    if (!window.AstroAuth?.state?.signedIn) return;

    const res = await window.AstroAuth.fetch('/api/catalog/summary');
    if (!res.ok) throw new Error(`summary ${res.status}`);
    const payload = await res.json();
    if (!payload.ok) throw new Error(payload.error || 'summary failed');

    const counts = payload.counts || {};
    window.CATALOG_STATS = {
      ...(window.CATALOG_STATS || {}),
      works: { ...((window.CATALOG_STATS || {}).works || {}), total: counts.works || 0 },
      recordings: { ...((window.CATALOG_STATS || {}).recordings || {}), total: counts.recordings || 0 },
      agreements: { ...((window.CATALOG_STATS || {}).agreements || {}), total: counts.agreements || 0 },
      claims: { ...((window.CATALOG_STATS || {}).claims || {}), open: counts.claims || 0 }
    };

    window.dispatchEvent(new CustomEvent('astro-live-data', {
      detail: { ok: true, counts }
    }));
  }

  async function checkBackend() {
    try {
      const res = await fetch('/api/health', { headers: { accept: 'application/json' } });
      const payload = await res.json();
      window.dispatchEvent(new CustomEvent('astro-backend', {
        detail: { ok: res.ok && payload.ok, checks: payload.checks || {}, error: payload.error || null }
      }));
    } catch (err) {
      window.dispatchEvent(new CustomEvent('astro-backend', {
        detail: { ok: false, checks: {}, error: err.message }
      }));
    }
  }

  window.AstroLiveData = { refreshLiveSummary, checkBackend };
  window.addEventListener('astro-auth', (e) => {
    if (e.detail?.signedIn) refreshLiveSummary().catch(() => {});
  });
  checkBackend();
})();
