'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var icons = require('../icons.js');
var highlightCode = require('../utils/highlight-code.js');
var escapeHtml = require('../utils/escape-html.js');

// 全局高亮器实例缓存
let globalHighlighter = null;

// 预加载高亮器
async function preloadHighlighter() {
  if (!globalHighlighter) {
    try {
      globalHighlighter = await highlightCode.getHighlighterInstance();
    } catch (error) {
      console.error('[MarkdownCodePlugin] Failed to load syntax highlighter:', error);
      globalHighlighter = null;
    }
  }
}

// 在模块加载时开始预加载
preloadHighlighter();

/**
 * 渲染代码块包装器（包含高亮、语言标签、复制按钮等）
 */
function renderCodeBlockWrapper(code, language) {
  let codeContent;

  // 如果高亮器可用，使用Shiki进行高亮
  if (globalHighlighter) {
    try {
      const highlightedCode = highlightCode.highlightCode(globalHighlighter, code, language);

      // 提取Shiki生成的高亮代码内容（移除外层的pre标签）
      const preMatch = highlightedCode.match(/<pre[^>]*><code[^>]*>([\s\S]*?)<\/code><\/pre>/);
      codeContent = preMatch?.[1] || highlightedCode;
    } catch (error) {
      console.error('[MarkdownCodePlugin] Syntax highlighting failed for language:', language, error);
      // 回退到基本转义
      codeContent = escapeHtml.escapeHtml(code);
    }
  } else {
    // 回退方案：基本HTML转义
    codeContent = escapeHtml.escapeHtml(code);
  }
  return `<div class="code-block-wrapper">
  <div class="code-block-header">
    <div class="code-language">
      <span class="code-language-text">${language}</span>
    </div>
    <div class="code-block-buttons">
      <button class="copy-code-button" title="复制代码" aria-label="复制代码">${icons.copyIconSvg}</button>
    </div>
  </div>
  <div class="code-block-content">
    <pre><code class="language-${language}">${codeContent}</code></pre>
  </div>
</div>`;
}

exports.renderCodeBlockWrapper = renderCodeBlockWrapper;
