// Centralized consent viewer JS
// Attaches a single delegated click handler to load consent markdown fragments
(function() {
  function initConsentViewer() {
    const viewerSection = document.getElementById('consent-viewer-section');
    const viewer = document.getElementById('consent-document-viewer');
    const vType = document.getElementById('viewer-type');
    const vVer = document.getElementById('viewer-version');
    const loading = document.getElementById('viewer-loading');

    if (!viewerSection || !viewer) {
      // Page without consent viewer; do nothing
      return;
    }

    document.addEventListener('click', async function(e) {
      const btn = e.target.closest('.btn-view-consent');
      if (!btn) return;
      e.preventDefault();

      const url = btn.getAttribute('data-url');
      const type = btn.getAttribute('data-consent-type') || '';
      const version = btn.getAttribute('data-version') || '';
      if (!url) {
        console.warn('Consent viewer: data-url missing on button');
        return;
      }

      try {
        viewerSection.style.display = 'block';
        if (vType) vType.textContent = type;
        if (vVer) vVer.textContent = version;
        if (loading) loading.style.display = 'block';
        viewer.innerHTML = '';

        const resp = await fetch(url, { headers: { 'X-Requested-With': 'XMLHttpRequest' } });
        const html = await resp.text();
        viewer.innerHTML = html;
      } catch (e) {
        viewer.innerHTML = '<div class="alert alert-danger">Failed to load document.</div>';
      } finally {
        if (loading) loading.style.display = 'none';
        viewerSection.scrollIntoView({ behavior: 'smooth' });
      }
    });
  }

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initConsentViewer);
  } else {
    initConsentViewer();
  }
})();
