const COPY_SELECTOR = '.badge[data-copy="true"]';
const COPIED_CLASS = 'is-copied';

const getCopyValue = (badge) => {
  const explicit = badge.getAttribute('data-copy-value');
  if (explicit !== null && explicit !== '') {
    return explicit;
  }
  return (badge.textContent || '').trim();
};

const copyText = async (value) => {
  if (!value) {return false;}
  if (navigator.clipboard?.writeText) {
    await navigator.clipboard.writeText(value);
    return true;
  }
  const textarea = document.createElement('textarea');
  textarea.value = value;
  textarea.setAttribute('readonly', 'true');
  textarea.style.position = 'fixed';
  textarea.style.opacity = '0';
  document.body.appendChild(textarea);
  textarea.select();
  const ok = document.execCommand('copy');
  document.body.removeChild(textarea);
  return ok;
};

const enhanceBadge = (badge) => {
  if (badge.querySelector('.badge-copy-icon')) {return;}
  const icon = document.createElement('span');
  icon.className = 'badge-copy-icon';
  icon.setAttribute('aria-hidden', 'true');
  icon.innerHTML = '<i class="bi bi-copy"></i><i class="bi bi-check2"></i>';
  badge.appendChild(icon);
  badge.setAttribute('role', 'button');
  badge.setAttribute('tabindex', '0');
  if (!badge.hasAttribute('aria-label')) {
    badge.setAttribute('aria-label', 'Copy to clipboard');
  }
  const handler = async (event) => {
    event.preventDefault();
    const value = getCopyValue(badge);
    const ok = await copyText(value);
    if (!ok) {return;}
    badge.classList.add(COPIED_CLASS);
    window.setTimeout(() => badge.classList.remove(COPIED_CLASS), 1200);
  };
  badge.addEventListener('click', handler);
  badge.addEventListener('keydown', (event) => {
    if (event.key === 'Enter' || event.key === ' ') {
      handler(event);
    }
  });
};

const initBadgeCopy = () => {
  document.querySelectorAll(COPY_SELECTOR).forEach(enhanceBadge);
};

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