{% if messages %}
<style>
.messagelist li .copy-message {
  float: right;
  margin-left: 1em;
}
</style>
<ul class="messagelist">{% for message in messages %}
  <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>
    <span class="message-content">{{ message|capfirst }}</span>
    <a href="#" class="copy-message">Copy</a>
  </li>
{% endfor %}</ul>
<script>
document.querySelectorAll('.messagelist .copy-message').forEach(function(btn) {
  btn.addEventListener('click', function(e) {
    e.preventDefault();
    const li = btn.closest('li');
    const content = li.querySelector('.message-content');
    const html = content.innerHTML;
    const text = content.innerText;
    let copied = false;

    function fallbackCopy() {
      const textarea = document.createElement('textarea');
      textarea.value = text;
      textarea.setAttribute('readonly', '');
      textarea.style.position = 'absolute';
      textarea.style.left = '-9999px';
      document.body.appendChild(textarea);
      textarea.select();
      try {
        copied = document.execCommand('copy');
      } catch (err) {
        console.error('Fallback copy failed:', err);
      }
      textarea.remove();
    }

    if (navigator.clipboard) {
      try {
        if (window.ClipboardItem && navigator.clipboard.write) {
          const item = new ClipboardItem({
            'text/plain': new Blob([text], {type: 'text/plain'}),
            'text/html': new Blob([html], {type: 'text/html'})
          });
          navigator.clipboard.write([item]).then(function() {
            copied = true;
          }).catch(function(err) {
            console.error('Clipboard API copy failed:', err);
            if (!copied) {
              fallbackCopy();
            }
          });
        } else if (navigator.clipboard.writeText) {
          navigator.clipboard.writeText(text).then(function() {
            copied = true;
          }).catch(function(err) {
            console.error('Clipboard API copy failed:', err);
            if (!copied) {
              fallbackCopy();
            }
          });
        } else {
          fallbackCopy();
        }
      } catch (err) {
        console.error('Clipboard API copy failed:', err);
      }
    } else {
      fallbackCopy();
    }
  });
});
</script>
{% endif %}
