/**
 * Post share modal: copy the permalink to the clipboard.
 */
(function () {
  document.addEventListener('click', function (e) {
    const btn = e.target.closest('.js-post-share-copy-url');
    if (!btn) return;

    const input = btn.parentElement.querySelector('input');
    if (!input) return;

    const copyText = input.value;
    const originalText = btn.innerText;
    const copiedText = btn.dataset.copiedText || 'Copied!';

    const onSuccess = function () {
      btn.innerText = copiedText;
      btn.classList.add('is-success');
      setTimeout(function () {
        btn.innerText = originalText;
        btn.classList.remove('is-success');
      }, 2000);
    };

    // Try the Clipboard API first.
    if (navigator.clipboard && window.isSecureContext) {
      navigator.clipboard.writeText(copyText).then(onSuccess);
    } else {
      // Fallback for non-secure contexts.
      input.select();
      input.setSelectionRange(0, 99999);
      try {
        document.execCommand('copy');
        onSuccess();
      } catch (err) {
        console.error('Fallback: Oops, unable to copy', err);
      }
    }
  });
})();
