/** JS snippets evaluated in Cursor renderer (composer scope only). */
export const NORMALIZE_IMAGE_SRC_FN = `
function normalizeImageSrc(src) {
  if (!src) return null;
  const raw = src.trim();
  if (!raw) return null;
  if (/^https?:\\/\\//i.test(raw)) return raw;
  if (raw.startsWith('vscode-file://vscode-app')) {
    const rest = raw.slice('vscode-file://vscode-app'.length);
    const q = rest.indexOf('?');
    try {
      return decodeURIComponent(q >= 0 ? rest.slice(0, q) : rest);
    } catch {
      return null;
    }
  }
  if (raw.startsWith('file://')) {
    try {
      return decodeURIComponent(raw.replace(/^file:\\/\\//, ''));
    } catch {
      return null;
    }
  }
  return null;
}
`;
export function extractComposerDraftImagesScript() {
    return `(() => {
    ${NORMALIZE_IMAGE_SRC_FN}
    const scopes = [
      document.querySelector('[class*="agent-panel"]'),
      document.querySelector('[class*="composer-panel"]'),
      document.querySelector('.composer-bar'),
      document.querySelector('[class*="composer-bar"]'),
    ].filter(Boolean);
    const seen = new Set();
    const out = [];
    for (const scope of scopes) {
      for (const img of scope.querySelectorAll(
        'img.image-pill-img, .image-pill-container img, img[alt="Attached image"]'
      )) {
        if (img.closest('[data-flat-index]')) continue;
        const path = normalizeImageSrc(img.getAttribute('src'));
        if (!path || seen.has(path)) continue;
        seen.add(path);
        out.push(path);
      }
    }
    return out;
  })()`;
}
/** Empty TipTap/contenteditable composer (used before send from Connect). */
export function clearComposerInputScript(inputSelectors) {
    const sels = JSON.stringify(inputSelectors);
    return `(() => {
    const inputSels = ${sels};
    const scopes = [
      document.querySelector('[class*="agent-panel"]'),
      document.querySelector('[class*="composer-panel"]'),
      document.querySelector('.composer-bar'),
      document.querySelector('[class*="composer-bar"]'),
      document,
    ].filter(Boolean);
    let input = null;
    for (const sel of inputSels) {
      try {
        for (const scope of scopes) {
          const el = scope.querySelector(sel);
          if (el) {
            input = el;
            break;
          }
        }
        if (input) break;
      } catch {}
    }
    if (!input) return false;
    input.scrollIntoView({ block: 'center' });
    input.focus();
    input.click();
    const root = input.querySelector('[data-lexical-editor="true"]') || input;
    try {
      const sel = window.getSelection();
      const range = document.createRange();
      range.selectNodeContents(root);
      sel?.removeAllRanges();
      sel?.addRange(range);
      document.execCommand('selectAll', false, null);
      document.execCommand('delete', false, null);
    } catch {}
    const fireInput = () => {
      root.dispatchEvent(
        new InputEvent('input', { bubbles: true, inputType: 'deleteContentBackward' })
      );
    };
    let left = (root.innerText || root.textContent || '')
      .replace(/\\u200b/g, ' ')
      .replace(/\\s+/g, ' ')
      .trim();
    if (left) {
      root.textContent = '';
      fireInput();
      left = (root.innerText || root.textContent || '').trim();
    }
    if (left) {
      try {
        root.dispatchEvent(
          new KeyboardEvent('keydown', { key: 'a', code: 'KeyA', metaKey: true, bubbles: true })
        );
        root.dispatchEvent(
          new KeyboardEvent('keydown', { key: 'a', code: 'KeyA', ctrlKey: true, bubbles: true })
        );
        document.execCommand('delete', false, null);
        fireInput();
      } catch {}
    }
    return true;
  })()`;
}
export function clearComposerAttachmentsScript() {
    return `(() => {
    const inputRoots = [
      document.querySelector('.composer-bar'),
      document.querySelector('[class*="composer-bar"]'),
      document.querySelector('[class*="ui-prompt-input"]'),
    ].filter(Boolean);
    let removed = 0;
    const isQueuedTray = (el) =>
      !!el.closest(
        '[class*="ui-tray--queued"], [class*="queue-item"], [class*="queue-sortable"], [class*="composer-queue"]'
      );
    for (const root of inputRoots) {
      for (const btn of root.querySelectorAll(
        'button[aria-label="Remove"], button[aria-label*="Remove image"], button[aria-label*="remove" i]'
      )) {
        if (btn.closest('[data-flat-index]')) continue;
        if (isQueuedTray(btn)) continue;
        if (!btn.closest('.image-pill-container, [class*="image-pill"], [class*="composer-attachment"]')) {
          continue;
        }
        btn.click();
        removed++;
      }
    }
    return removed;
  })()`;
}
