(() => {
  /* one-time CSS */
  if (!window.__holBadgeCSS) {
    document.head.insertAdjacentHTML('beforeend', `<style>
      .hol-badge-link{display:inline-block;text-decoration:none;color:inherit;cursor:pointer}
      .hol-badge{--hol-badge-size:96px;--hol-badge-pad:8px;--hol-badge-color:currentColor;
        display:inline-block;width:calc(var(--hol-badge-size) + var(--hol-badge-pad)*2);
        height:calc(var(--hol-badge-size)*1.437 + var(--hol-badge-pad)*2);
        line-height:0;padding:var(--hol-badge-pad);color:var(--hol-badge-color)}
      .hol-badge svg{width:100%;height:auto;fill:currentColor}
    </style>`);
    window.__holBadgeCSS = true;
  }

  /* data-attributes */
  const s   = document.currentScript;
  const id  = (s.dataset.badge || 'holacracy-powered-1').replace(/\.svg$/i,'').trim();
  const org = (s.dataset.org   || '').trim();
  const sizeAttr = s.dataset.size;
  const sizeCSS  = sizeAttr ? (/^\d+$/.test(sizeAttr) ? sizeAttr+'px' : sizeAttr) : null;

  /* colors */
  const theme = (s.dataset.theme || 'light').toLowerCase();
  const hex   = s.dataset.color;
  const fg = hex || (theme==='dark' ? '#fff' : theme==='brand' ? '#5E84E7' : '#222');

  /* skeleton */
  const ph = document.createElement('span');
  ph.className = 'hol-badge hol-badge--placeholder';
  if (sizeCSS) ph.style.setProperty('--hol-badge-size', sizeCSS);
  s.insertAdjacentElement('afterend', ph);

  /* fetch → inject */
  (async () => {
    try {
      const svgURL = new URL(id + '.svg', s.src).href;
      const res    = await fetch(svgURL);
      if (!res.ok) throw new Error(res.status);
      const svg = await res.text();
	  if (!svg.trim()) throw new Error('Empty SVG');

      const a = Object.assign(document.createElement('a'), {
        href: org ? `https://www.holacracy.org/org/${org}` : 'https://www.holacracy.org/directory',
        target:'_blank', rel:'noopener', className:'hol-badge-link'
      });

      const span = document.createElement('span');
      span.className = `hol-badge hol-badge--${id} ${s.dataset.class||''}`.trim();
      span.style.setProperty('--hol-badge-color', fg);
      if (sizeCSS) span.style.setProperty('--hol-badge-size', sizeCSS);
      span.setAttribute('role','img');
      span.setAttribute('aria-label','Holacracy badge');
      span.innerHTML = svg;

      a.appendChild(span);
      ph.replaceWith(a);
    } catch (err) {
      console.error('Holacracy badge error:', err);
    } finally {
      s.remove();                 /* keep markup clean */
    }
  })();
})();