
export function write_mnote_text_to_clipboard(text) {
  try {
    if (navigator?.clipboard?.writeText) {
      return navigator.clipboard.writeText(String(text)).then(() => true, () => false);
    }
  } catch (_error) {}
  return Promise.resolve(false);
}

export function find_mnote_block_anchor(blockId) {
  const wanted = String(blockId || '');
  if (!wanted) return null;
  const root = document.querySelector('.editor-surface .ProseMirror');
  if (!root) return null;
  return Array.from(root.querySelectorAll('[data-block-id]')).find((node) => node.getAttribute('data-block-id') === wanted) || null;
}

export function select_mnote_image_node(image) {
  try {
    const root = image?.closest?.('.ProseMirror');
    const editor = root?.editor;
    const view = editor?.view;
    if (!editor || !view || typeof view.posAtDOM !== 'function') return false;
    const pos = view.posAtDOM(image, 0);
    if (!Number.isFinite(pos)) return false;
    return editor.chain().focus().setNodeSelection(pos).run() === true;
  } catch (error) {
    console.warn('mnote image NodeSelection failed', error);
    return false;
  }
}

function mnoteImageExtension(url, contentType) {
  const urlMatch = String(url || '').match(/\.([a-zA-Z0-9]+)(?:[?#].*)?$/);
  if (urlMatch?.[1]) return `.${urlMatch[1].toLowerCase()}`;
  const mimeMap = {
    'image/jpeg': '.jpg',
    'image/jpg': '.jpg',
    'image/png': '.png',
    'image/gif': '.gif',
    'image/webp': '.webp',
    'image/svg+xml': '.svg',
    'image/bmp': '.bmp',
  };
  return mimeMap[String(contentType || '').toLowerCase()] || '.jpg';
}

function mnoteImageFilename(image, url) {
  const raw = image.getAttribute('title') || image.getAttribute('alt') || `image-${Date.now()}`;
  const base = raw.replace(/[\/:*?"<>|]+/g, '-').trim() || `image-${Date.now()}`;
  return /\.[a-zA-Z0-9]+$/.test(base) ? base : `${base}${mnoteImageExtension(url)}`;
}

export function download_mnote_selected_image() {
  try {
    const image = document.querySelector('.editor-surface .ProseMirror img.ProseMirror-selectednode[src]');
    if (!(image instanceof HTMLImageElement)) return false;
    const src = image.getAttribute('src');
    if (!src) return false;
    const url = new URL(src, window.location.href);
    if (!(url.protocol === 'http:' || url.protocol === 'https:' || url.protocol === 'data:')) return false;
    const link = document.createElement('a');
    link.href = url.href;
    link.download = mnoteImageFilename(image, url.href);
    link.style.display = 'none';
    document.body.appendChild(link);
    link.click();
    link.remove();
    return true;
  } catch (error) {
    console.warn('mnote image download failed', error);
    return false;
  }
}

export function bump_mnote_e27_ai_bridge_request_count() {
  try {
    const key = '__MNOTE_E27_AI_BRIDGE_REQUEST_COUNT__';
    window[key] = Number(window[key] || 0) + 1;
    return window[key];
  } catch (_error) {
    return 0;
  }
}

export async function post_mnote_document_save(body) {
  const response = await fetch('/api/documents/save', {
    method: 'POST',
    headers: { 'content-type': 'application/json' },
    body: String(body || '{}'),
  });
  const text = await response.text();
  if (!response.ok) {
    throw new Error(`document save failed: HTTP ${response.status}; ${text.slice(0, 1200)}`);
  }
  return text || '{}';
}
