(function ($, Drupal) {
  Drupal.behaviors.clippableContent = {
    attach: function (context, settings) {
      // Find all elements with the class and apply the functionality
      const elems = once('clippable-content', '.clippable-content__link', context);
      elems.forEach(function (elem) {
        elem.addEventListener('click', function () {

          let embedCode = elem.dataset.clipboardText;

          if (navigator.clipboard) {
            navigator.clipboard.writeText(embedCode).then(function () {
              alert('Embed code copied to clipboard!');
            }, function (err) {
              this.fallbackCopy(embedCode);
            });
          }
          else {
            this.fallbackCopy(embedCode);
          }

        });
      });
    },

    fallbackCopy: function (text) {
      const textarea = document.createElement('textarea');
      textarea.value = text;
      document.body.appendChild(textarea);
      textarea.focus();
      textarea.select();
      try {
        let successful = document.execCommand('copy');
        if (successful) {
          alert('Embed code copied to clipboard!');
        }
        else {
          alert('Failed to copy embed code to clipboard...');
        }
      } catch (err) {
        console.error('Failed to copy embed code: ', err);
      }
      textarea.remove();
    }
  };
})(jQuery, Drupal);
