/**
 * RagGo Copy-to-Clipboard Utility
 *
 * Usage: Add class="copy-trigger" data-copy-target="<CSS selector>" to a button.
 * The button will copy the text content of the target element to clipboard on click.
 * Auto-attaches on DOMContentLoaded and after HTMX swaps.
 */
;(function () {
  'use strict';

  var COPY_ICON_SVG = '<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="13" height="13" rx="2" ry="2"></rect><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"></path></svg>';
  var CHECK_ICON_SVG = '<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"></polyline></svg>';

  function copyText(btn) {
    var selector = btn.getAttribute('data-copy-target');
    var target = null;
    if (selector) {
      target = document.querySelector(selector);
    }
    if (!target) {
      // Fallback: look for target relative to common parent
      var wrapper = btn.closest('.code-block-wrapper, .mcp-ref-row, .result-card');
      if (wrapper) target = wrapper.querySelector('code, .mcp-ref-value, .result-snippet');
    }
    if (!target) return;

    var text = target.textContent || target.innerText || '';
    navigator.clipboard.writeText(text.trim()).then(function () {
      showCopied(btn);
    }).catch(function () {
      // Fallback for older browsers
      var ta = document.createElement('textarea');
      ta.value = text.trim();
      ta.style.position = 'fixed';
      ta.style.opacity = '0';
      document.body.appendChild(ta);
      ta.select();
      document.execCommand('copy');
      document.body.removeChild(ta);
      showCopied(btn);
    });
  }

  function showCopied(btn) {
    btn.classList.add('copied');
    // Store original content and swap to checkmark
    if (!btn._origHTML) btn._origHTML = btn.cloneNode(true);
    // Safe DOM manipulation: clear and add check icon
    while (btn.firstChild) btn.removeChild(btn.firstChild);
    var tmp = document.createElement('span');
    tmp.textContent = '';
    // Use a static trusted SVG for the checkmark
    var ns = 'http://www.w3.org/2000/svg';
    var svg = document.createElementNS(ns, 'svg');
    svg.setAttribute('width', '14');
    svg.setAttribute('height', '14');
    svg.setAttribute('viewBox', '0 0 24 24');
    svg.setAttribute('fill', 'none');
    svg.setAttribute('stroke', 'currentColor');
    svg.setAttribute('stroke-width', '2.5');
    svg.setAttribute('stroke-linecap', 'round');
    svg.setAttribute('stroke-linejoin', 'round');
    var pl = document.createElementNS(ns, 'polyline');
    pl.setAttribute('points', '20 6 9 17 4 12');
    svg.appendChild(pl);
    btn.appendChild(svg);

    setTimeout(function () {
      btn.classList.remove('copied');
      // Restore original content
      if (btn._origHTML) {
        while (btn.firstChild) btn.removeChild(btn.firstChild);
        var orig = btn._origHTML;
        while (orig.firstChild) {
          btn.appendChild(orig.firstChild.cloneNode(true));
        }
      }
    }, 1500);
  }

  function createCopyButton() {
    var btn = document.createElement('button');
    btn.className = 'copy-trigger';
    btn.setAttribute('title', 'Copy');
    var ns = 'http://www.w3.org/2000/svg';
    var svg = document.createElementNS(ns, 'svg');
    svg.setAttribute('width', '14');
    svg.setAttribute('height', '14');
    svg.setAttribute('viewBox', '0 0 24 24');
    svg.setAttribute('fill', 'none');
    svg.setAttribute('stroke', 'currentColor');
    svg.setAttribute('stroke-width', '2');
    svg.setAttribute('stroke-linecap', 'round');
    svg.setAttribute('stroke-linejoin', 'round');
    var rect = document.createElementNS(ns, 'rect');
    rect.setAttribute('x', '9');
    rect.setAttribute('y', '9');
    rect.setAttribute('width', '13');
    rect.setAttribute('height', '13');
    rect.setAttribute('rx', '2');
    rect.setAttribute('ry', '2');
    svg.appendChild(rect);
    var path = document.createElementNS(ns, 'path');
    path.setAttribute('d', 'M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1');
    svg.appendChild(path);
    btn.appendChild(svg);
    return btn;
  }

  function autoInjectCodeBlocks() {
    // Auto-inject copy buttons into .mcp-code blocks that don't already have one
    document.querySelectorAll('.mcp-code:not([data-copy-injected])').forEach(function (pre) {
      pre.setAttribute('data-copy-injected', '1');
      // Wrap in a position:relative container if not already wrapped
      if (!pre.parentElement.classList.contains('code-block-wrapper')) {
        var wrapper = document.createElement('div');
        wrapper.className = 'code-block-wrapper';
        pre.parentNode.insertBefore(wrapper, pre);
        wrapper.appendChild(pre);
      }
      var btn = createCopyButton();
      pre.parentElement.appendChild(btn);
      btn.setAttribute('data-copy-bound', '1');
      btn.addEventListener('click', function (e) {
        e.preventDefault();
        e.stopPropagation();
        var code = pre.querySelector('code') || pre;
        var text = code.textContent || code.innerText || '';
        navigator.clipboard.writeText(text.trim()).then(function () {
          showCopied(btn);
        }).catch(function () {
          var ta = document.createElement('textarea');
          ta.value = text.trim();
          ta.style.position = 'fixed';
          ta.style.opacity = '0';
          document.body.appendChild(ta);
          ta.select();
          document.execCommand('copy');
          document.body.removeChild(ta);
          showCopied(btn);
        });
      });
    });
  }

  function attach() {
    // Bind manually-placed copy triggers
    document.querySelectorAll('.copy-trigger:not([data-copy-bound])').forEach(function (btn) {
      btn.setAttribute('data-copy-bound', '1');
      btn.addEventListener('click', function (e) {
        e.preventDefault();
        e.stopPropagation();
        copyText(btn);
      });
    });
    // Auto-inject copy buttons into code blocks
    autoInjectCodeBlocks();
  }

  // Auto-attach on load and after HTMX swaps
  document.addEventListener('DOMContentLoaded', attach);
  document.addEventListener('htmx:afterSettle', attach);

  // Public API
  window.RagGoClipboard = { attach: attach };
})();
