const t=`
  var active = false;
  var hovered = null;
  var selectedEl = null;
  var hoverOverlay = null;
  var selectOverlay = null;
  var HOVER_OUTLINE = '2px solid rgba(110, 168, 254, 0.6)';
  var SELECT_OUTLINE = '2px solid rgba(110, 168, 254, 0.9)';
  var SELECT_BG = 'rgba(110, 168, 254, 0.08)';
  var OUTLINE_RADIUS = '4px';

  function createOverlayDiv(rect, isSelect) {
    var div = document.createElement('div');
    div.style.position = 'fixed';
    div.style.left = rect.left + 'px';
    div.style.top = rect.top + 'px';
    div.style.width = rect.width + 'px';
    div.style.height = rect.height + 'px';
    div.style.outline = isSelect ? SELECT_OUTLINE : HOVER_OUTLINE;
    div.style.outlineOffset = '2px';
    div.style.borderRadius = OUTLINE_RADIUS;
    if (isSelect) div.style.backgroundColor = SELECT_BG;
    div.style.pointerEvents = 'none';
    div.style.zIndex = '99999';
    div.setAttribute('data-pneuma-overlay', 'true');
    document.body.appendChild(div);
    return div;
  }

  function clearHover() {
    if (hoverOverlay) { hoverOverlay.remove(); hoverOverlay = null; }
    hovered = null;
  }

  function clearSelected() {
    if (selectOverlay) { selectOverlay.remove(); selectOverlay = null; }
    selectedEl = null;
  }

  function applySelectedStyle(el) {
    clearSelected();
    selectedEl = el;
    var rect = el.getBoundingClientRect();
    selectOverlay = createOverlayDiv(rect, true);
  }
`,a=`
  // Semantic HTML elements — always a good selection target
  var SEMANTIC_RE = /^(h[1-6]|p|li|ul|ol|pre|code|blockquote|img|section|article|nav|aside|header|footer|main|table|thead|tbody|tr|td|th|figure|figcaption|details|summary|a|button|svg)$/i;

  // Minimum size to consider an element "visible enough" to select
  var MIN_SELECT_SIZE = 8;

  /**
   * Find the meaningful element to select for a given click/hover target.
   *
   * Unlike the previous closest(SEL) approach, this starts from the target
   * itself and walks up only when the element is too small or invisible.
   * This means ANY element with visual presence can be selected — images
   * inside plain divs, cards without semantic tags, icons, etc.
   */
  function findMeaningfulElement(target) {
    var el = target;

    // Skip text nodes — move to parent element
    if (el.nodeType === 3) el = el.parentElement;
    if (!el || el === document.body || el === document.documentElement) return null;

    // Skip script/style elements
    if (el.tagName === 'SCRIPT' || el.tagName === 'STYLE') return null;

    // Walk up until we find an element with reasonable visual size
    while (el && el !== document.body && el !== document.documentElement) {
      // data-selectable is always a valid target
      if (el.hasAttribute && el.hasAttribute('data-selectable')) return el;

      var rect = el.getBoundingClientRect();

      // Semantic elements are always good targets (even if small — e.g. inline code)
      if (SEMANTIC_RE.test(el.tagName)) return el;

      // Element has visual size — use it
      if (rect.width >= MIN_SELECT_SIZE && rect.height >= MIN_SELECT_SIZE) {
        // But if it's very small (< 24px both axes), try to find a better parent
        if (rect.width < 24 && rect.height < 24) {
          var parent = el.parentElement;
          if (parent && parent !== document.body) {
            var pRect = parent.getBoundingClientRect();
            // Parent is meaningfully larger — prefer it
            if (pRect.width > rect.width * 1.5 || pRect.height > rect.height * 1.5) {
              el = parent;
              continue;
            }
          }
        }
        return el;
      }

      // Element too small/invisible — walk up
      el = el.parentElement;
    }

    return null;
  }
`,r=`
  /**
   * Get CSS class names cleaned of module hashes.
   * E.g. "card_a8f3x" -> "card", deduped.
   */
  function getElementClasses(el) {
    var cn = el.className;
    if (typeof cn !== 'string' || !cn) return '';
    var parts = cn.split(/\\s+/);
    var seen = {};
    var result = [];
    for (var i = 0; i < parts.length; i++) {
      if (!parts[i]) continue;
      // Strip CSS module hash suffix (e.g. card_a8f3x -> card)
      var match = parts[i].match(/^([a-zA-Z][a-zA-Z0-9_-]*?)(?:_[a-zA-Z0-9]{5,})?$/);
      var clean = match ? match[1] : parts[i];
      if (!seen[clean]) {
        seen[clean] = true;
        result.push(clean);
      }
    }
    return result.join(', ');
  }

  /**
   * Identify an element with a human-readable label.
   * Returns a string like 'button "Submit"', 'h2 "Our Solution"', 'image "logo"'.
   */
  function identifyElement(el) {
    // Check data-element attribute first (explicit labeling)
    if (el.dataset && el.dataset.element) return el.dataset.element;

    var tag = el.tagName.toLowerCase();

    // SVG elements
    if (tag === 'svg') {
      var svgParent = el.parentElement;
      if (svgParent && svgParent.tagName.toLowerCase() === 'button') {
        var btnText = (svgParent.textContent || '').trim();
        return btnText ? 'icon in "' + btnText.slice(0, 25) + '" button' : 'button icon';
      }
      return 'icon';
    }

    // Interactive elements
    if (tag === 'button') {
      var ariaLabel = el.getAttribute('aria-label');
      if (ariaLabel) return 'button [' + ariaLabel + ']';
      var text = (el.textContent || '').trim();
      return text ? 'button "' + text.slice(0, 25) + '"' : 'button';
    }
    if (tag === 'a') {
      var linkText = (el.textContent || '').trim();
      var href = el.getAttribute('href');
      if (linkText) return 'link "' + linkText.slice(0, 25) + '"';
      if (href) return 'link to ' + href.slice(0, 30);
      return 'link';
    }
    if (tag === 'input') {
      var inputType = el.getAttribute('type') || 'text';
      var placeholder = el.getAttribute('placeholder');
      var name = el.getAttribute('name');
      if (placeholder) return 'input "' + placeholder + '"';
      if (name) return 'input [' + name + ']';
      return inputType + ' input';
    }

    // Headings
    if (/^h[1-6]$/.test(tag)) {
      var hText = (el.textContent || '').trim();
      return hText ? tag + ' "' + hText.slice(0, 35) + '"' : tag;
    }

    // Text elements
    if (tag === 'p') {
      var pText = (el.textContent || '').trim();
      if (pText) return 'paragraph: "' + pText.slice(0, 40) + (pText.length > 40 ? '...' : '') + '"';
      return 'paragraph';
    }
    if (tag === 'span' || tag === 'label') {
      var sText = (el.textContent || '').trim();
      if (sText && sText.length < 40) return '"' + sText + '"';
      return tag;
    }
    if (tag === 'li') {
      var liText = (el.textContent || '').trim();
      if (liText && liText.length < 40) return 'list item: "' + liText.slice(0, 35) + '"';
      return 'list item';
    }
    if (tag === 'blockquote') return 'blockquote';
    if (tag === 'code') {
      var codeText = (el.textContent || '').trim();
      if (codeText && codeText.length < 30) return 'code: \`' + codeText + '\`';
      return 'code';
    }
    if (tag === 'pre') return 'code block';

    // Media
    if (tag === 'img') {
      var alt = el.getAttribute('alt');
      return alt ? 'image "' + alt.slice(0, 30) + '"' : 'image';
    }

    // Containers — try to infer meaningful name
    if (/^(div|section|article|nav|header|footer|aside|main)$/.test(tag)) {
      var role = el.getAttribute('role');
      var cAriaLabel = el.getAttribute('aria-label');
      if (cAriaLabel) return tag + ' [' + cAriaLabel + ']';
      if (role) return role;

      var classes = getElementClasses(el);
      if (classes) {
        // Use first 2 cleaned class names
        var words = classes.split(', ').slice(0, 2);
        if (words.length > 0) return words.join(' ');
      }
      return tag === 'div' ? 'container' : tag;
    }

    return tag;
  }
`,i=`
  /**
   * Get text content from element and siblings for context.
   * Returns a string like '[before: "The Challenge"] Our Solution [after: "Key Benefits"]'.
   */
  function getNearbyText(el) {
    var texts = [];

    // Own text (skip if too long)
    var ownText = (el.textContent || '').trim();
    if (ownText && ownText.length < 100) {
      texts.push(ownText);
    }

    // Previous sibling text
    var prev = el.previousElementSibling;
    if (prev) {
      var prevText = (prev.textContent || '').trim();
      if (prevText && prevText.length < 50) {
        texts.unshift('[before: "' + prevText.slice(0, 40) + '"]');
      }
    }

    // Next sibling text
    var next = el.nextElementSibling;
    if (next) {
      var nextText = (next.textContent || '').trim();
      if (nextText && nextText.length < 50) {
        texts.push('[after: "' + nextText.slice(0, 40) + '"]');
      }
    }

    return texts.join(' ');
  }

  /**
   * Get accessibility information for an element.
   * Returns a string like 'role="heading", focusable'.
   */
  function getAccessibilityInfo(el) {
    var parts = [];

    var role = el.getAttribute('role');
    var ariaLabel = el.getAttribute('aria-label');
    var ariaDescribedBy = el.getAttribute('aria-describedby');
    var tabIndex = el.getAttribute('tabindex');
    var ariaHidden = el.getAttribute('aria-hidden');

    if (role) parts.push('role="' + role + '"');
    if (ariaLabel) parts.push('aria-label="' + ariaLabel + '"');
    if (ariaDescribedBy) parts.push('aria-describedby="' + ariaDescribedBy + '"');
    if (tabIndex) parts.push('tabindex=' + tabIndex);
    if (ariaHidden === 'true') parts.push('aria-hidden');

    // Check focusability
    var focusable = el.matches('a, button, input, select, textarea, [tabindex]');
    if (focusable) parts.push('focusable');

    return parts.join(', ');
  }
`,l=`
  /** Build a unique CSS selector path for an element */
  function buildSelector(el) {
    var parts = [];
    var current = el;
    while (current && current !== document.body && current !== document.documentElement) {
      var tag = current.tagName.toLowerCase();
      var part = tag;
      if (current.id) {
        part = tag + '#' + current.id;
        parts.unshift(part);
        break;
      }
      var cls = (typeof current.className === 'string' ? current.className : '').trim();
      if (cls) {
        // Use first 2 classes max to keep selector readable
        var classes = cls.split(/\\s+/).slice(0, 2).join('.');
        part = tag + '.' + classes;
      }
      // Add nth-child if there are siblings with same tag
      var parent = current.parentElement;
      if (parent) {
        var siblings = parent.children;
        var sameTag = 0, position = 0;
        for (var i = 0; i < siblings.length; i++) {
          if (siblings[i].tagName === current.tagName) {
            sameTag++;
            if (siblings[i] === current) position = sameTag;
          }
        }
        if (sameTag > 1) part += ':nth-child(' + (Array.prototype.indexOf.call(siblings, current) + 1) + ')';
      }
      parts.unshift(part);
      current = current.parentElement;
    }
    return parts.join(' > ');
  }
`,n=`
  /** Capture an SVG thumbnail of an element using foreignObject */
  function captureElementThumbnail(el) {
    try {
      var elRect = el.getBoundingClientRect();
      var elW = Math.ceil(elRect.width);
      var elH = Math.ceil(elRect.height);
      if (elW <= 0 || elH <= 0) return null;

      // Clone the element
      var clone = el.cloneNode(true);
      // Remove scripts from clone
      var scripts = clone.querySelectorAll('script');
      for (var s = 0; s < scripts.length; s++) scripts[s].remove();

      // Measure actual content size by rendering clone off-screen in the iframe
      // Use position:fixed to avoid expanding scrollable area (prevents scroll flash)
      var measure = document.createElement('div');
      measure.style.cssText = 'position:fixed;left:-99999px;top:-99999px;width:fit-content;max-width:' + elW + 'px;pointer-events:none;visibility:hidden;';
      measure.appendChild(clone);
      document.body.appendChild(measure);
      var fitRect = clone.getBoundingClientRect();
      var fitW = Math.ceil(fitRect.width) || elW;
      var fitH = Math.ceil(fitRect.height) || elH;
      document.body.removeChild(measure);

      // Collect all CSS rules
      var cssText = '';
      try {
        var sheets = document.styleSheets;
        for (var i = 0; i < sheets.length; i++) {
          try {
            var rules = sheets[i].cssRules;
            for (var j = 0; j < rules.length; j++) {
              cssText += rules[j].cssText + '\\n';
            }
          } catch(ex) { /* cross-origin */ }
        }
      } catch(ex) {}

      // Reset clone's margin so it renders at (0,0) in the standalone SVG context
      // (the original element may have margin/position from its parent layout)
      clone.style.margin = '0';
      if (clone.style.position === 'absolute' || clone.style.position === 'fixed') {
        clone.style.position = 'relative';
      }
      clone.style.top = '0';
      clone.style.left = '0';

      // Serialize clone directly in iframe context (preserves SVG namespaces)
      var cloneHtml = new XMLSerializer().serializeToString(clone);

      // Escape CSS for XHTML CDATA
      var safeCss = cssText.replace(/]]>/g, ']]]]><![CDATA[>');
      var sizeCSS = 'html,body{margin:0;padding:0;overflow:hidden;width:' + fitW + 'px;height:' + fitH + 'px;}';

      var xhtml = '<html xmlns="http://www.w3.org/1999/xhtml"><head>'
        + '<style><![CDATA[' + safeCss + ']]></style>'
        + '<style>' + sizeCSS + '</style>'
        + '</head><body>' + cloneHtml + '</body></html>';

      var svg = '<svg xmlns="http://www.w3.org/2000/svg" width="' + fitW + '" height="' + fitH + '">' +
        '<foreignObject width="' + fitW + '" height="' + fitH + '">' + xhtml + '</foreignObject></svg>';
      var encoded = 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(svg);

      // Skip if too large (> 200KB)
      if (encoded.length > 200 * 1024) return null;
      return encoded;
    } catch(ex) {
      return null;
    }
  }
`,s=`
  /** Classify element type */
  function classifyElement(el) {
    var tag = el.tagName.toLowerCase();
    var type = 'container';
    var level;
    if (/^h[1-6]$/.test(tag)) { type = 'heading'; level = parseInt(tag[1]); }
    else if (tag === 'p') type = 'paragraph';
    else if (tag === 'li') type = 'list';
    else if (tag === 'ul' || tag === 'ol') type = 'list';
    else if (tag === 'pre' || tag === 'code') type = 'code';
    else if (tag === 'blockquote') type = 'blockquote';
    else if (tag === 'img') type = 'image';
    else if (tag === 'table' || tag === 'thead' || tag === 'tbody' || tag === 'tr' || tag === 'td' || tag === 'th') type = 'table';
    else if (tag === 'section' || tag === 'article' || tag === 'nav' || tag === 'aside' || tag === 'header' || tag === 'footer' || tag === 'main') type = 'section';
    else if (tag === 'a') type = 'link';
    else if (tag === 'button') type = 'interactive';
    else if (tag === 'figure' || tag === 'figcaption') type = 'container';
    return { type: type, level: level };
  }
`,o=`
  window.addEventListener('message', function(e) {
    if (!e.data) return;
    if (e.data.type === 'pneuma:selectMode') {
      active = !!e.data.enabled;
      document.body.style.cursor = active ? 'crosshair' : '';
      if (!active) {
        clearHover();
        clearSelected();
      }
    }
    if (e.data.type === 'pneuma:highlight') {
      try {
        var target = document.querySelector(e.data.selector);
        if (target) {
          // Skip scrollIntoView if this element is already selected by the user's click
          // (avoids scroll flash when parent echoes back the selection as a highlight)
          var alreadySelected = (target === selectedEl);
          applySelectedStyle(target);
          if (!alreadySelected) {
            target.scrollIntoView({ behavior: 'smooth', block: 'center' });
          }
        }
      } catch(ex) {}
    }
    if (e.data.type === 'pneuma:highlightMultiple') {
      // Clear previous annotation overlays
      var prevOverlays = document.querySelectorAll('[data-pneuma-annotation-overlay]');
      for (var pi = 0; pi < prevOverlays.length; pi++) {
        prevOverlays[pi].remove();
      }
      // Create overlay for each selector
      var selectors = e.data.selectors || [];
      for (var ai = 0; ai < selectors.length; ai++) {
        try {
          var ael = document.querySelector(selectors[ai]);
          if (ael) {
            var arect = ael.getBoundingClientRect();
            var adiv = createOverlayDiv(arect, true);
            adiv.setAttribute('data-pneuma-annotation-overlay', 'true');
            adiv.removeAttribute('data-pneuma-overlay');
          }
        } catch(ex) {}
      }
    }
    if (e.data.type === 'pneuma:clearHighlight') {
      clearSelected();
      // Also clear annotation overlays
      var annotOverlays = document.querySelectorAll('[data-pneuma-annotation-overlay]');
      for (var ci = 0; ci < annotOverlays.length; ci++) {
        annotOverlays[ci].remove();
      }
    }
  });

  // Forward keyboard events from iframe to parent (iframe events don't bubble)
  document.addEventListener('keydown', function(e) {
    if (!active) return;
    if (e.key === 'Escape') {
      e.preventDefault();
      window.parent.postMessage({ type: 'pneuma:escapeKey' }, '*');
    }
    if (e.key === 'Alt') {
      window.parent.postMessage({ type: 'pneuma:altKey', pressed: true }, '*');
    }
  });

  document.addEventListener('keyup', function(e) {
    if (!active) return;
    if (e.key === 'Alt') {
      window.parent.postMessage({ type: 'pneuma:altKey', pressed: false }, '*');
    }
  });

  document.addEventListener('mouseover', function(e) {
    if (!active) return;
    var el = findMeaningfulElement(e.target);
    if (!el) return;
    if (hovered && hovered !== el) clearHover();
    if (el === selectedEl) return;
    hovered = el;
    var rect = el.getBoundingClientRect();
    hoverOverlay = createOverlayDiv(rect, false);
  });

  document.addEventListener('mouseout', function(e) {
    if (!active) return;
    clearHover();
  });

  document.addEventListener('click', function(e) {
    if (!active) return;
    e.preventDefault();
    e.stopPropagation();
    var el = findMeaningfulElement(e.target);
    if (!el) {
      clearSelected();
      window.parent.postMessage({ type: 'pneuma:select', selection: null }, '*');
      return;
    }

    // Remove hover overlay before thumbnail capture (no blue border in preview)
    clearHover();

    // Capture thumbnail with clean styles
    var thumbnail = captureElementThumbnail(el);

    applySelectedStyle(el);

    var tag = el.tagName.toLowerCase();
    var info = classifyElement(el);
    var classes = (typeof el.className === 'string' ? el.className : '').trim();
    var selector = buildSelector(el);

    // New: rich identification from agentation-ported functions
    var label = identifyElement(el);
    var nearbyText = getNearbyText(el);
    var accessibility = getAccessibilityInfo(el);

    var content = tag === 'img'
      ? (el.getAttribute('alt') || el.getAttribute('src') || 'image')
      : (el.textContent || '').trim().slice(0, 200);

    var elRect = el.getBoundingClientRect();

    window.parent.postMessage({
      type: 'pneuma:select',
      selection: {
        type: info.type,
        content: content,
        level: info.level,
        tag: tag,
        classes: classes,
        selector: selector,
        thumbnail: thumbnail,
        label: label,
        nearbyText: nearbyText,
        accessibility: accessibility,
        rect: { left: elRect.left, top: elRect.top, right: elRect.right, bottom: elRect.bottom, width: elRect.width, height: elRect.height }
      }
    }, '*');
  });
`;function u(e){return`<script>
(function() {${[t,a,r,i,l,n,s,...e?.extensions??[],o].join(`
`)}
})();
<\/script>`}export{u as b};
