'use strict';

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

var ClipboardJS = require('clipboard');
var icons = require('../icons.js');

// 前向声明插件实例类型
// 事件监听器状态管理

// 全局状态实例，用于跨调用保持状态
const globalState = {
  copyButtonIdCounter: 0,
  cleanupFunctions: new WeakMap()
};

/**
 * 处理代码块事件监听器的挂载逻辑
 * 用于在 onMounted 钩子中调用
 */
function handleCodeEventListenerMount(pluginInstance, element) {
  // 检查是否包含代码块
  const codeBlocks = element.querySelectorAll('.code-block-wrapper');
  if (codeBlocks.length === 0) {
    return;
  }

  // 清理之前的事件监听器
  cleanupElement(element, globalState);

  // 设置复制功能
  const cleanup = setupCopyCodeEventForElement(element, globalState, pluginInstance);

  // 存储清理函数
  if (cleanup) {
    globalState.cleanupFunctions.set(element, cleanup);
  }

  // 绑定其他代码块相关事件
  bindCodeBlockEvents(element);
}

/**
 * 处理代码块事件监听器的清理逻辑
 * 用于在 onUnmounted 钩子中调用
 */
function handleCodeEventListenerCleanup(element) {
  if (element) {
    cleanupElement(element, globalState);
  } else {
    // 清理所有存储的清理函数
    globalState.cleanupFunctions = new WeakMap();
    globalState.copyButtonIdCounter = 0;
  }
}

/**
 * 为单个元素设置复制代码事件
 */
function setupCopyCodeEventForElement(container, state, pluginInstance) {
  const buttonsInContainer = container.querySelectorAll('.code-block-wrapper .copy-code-button');
  if (buttonsInContainer.length === 0) return null;

  // 为每个按钮创建独立的 ClipboardJS 实例
  const clipboardInstances = [];
  buttonsInContainer.forEach(button => {
    // 确保按钮有正确的初始图标
    if (!button.innerHTML.trim() || !button.querySelector('svg')) {
      button.innerHTML = icons.copyIconSvg;
    }

    // 为每个按钮创建唯一的 ID（如果没有的话）
    if (!button.id) {
      button.id = `copy-button-${state.copyButtonIdCounter++}`;
    }
    const clipboard = new ClipboardJS(`#${button.id}`, {
      text(trigger) {
        const wrapper = trigger.closest('.code-block-wrapper');
        const codeElement = wrapper?.querySelector('pre > code');
        const text = codeElement?.textContent || '';
        return text;
      }
    });
    clipboard.on('success', e => {
      const button = e.trigger;
      const wrapper = button.closest('.code-block-wrapper');
      const codeElement = wrapper?.querySelector('pre > code');
      const codeText = codeElement?.textContent || '';

      // 发射复制成功事件
      pluginInstance.emit('copy-code-clicked', {
        code: codeText
      });
      button.innerHTML = icons.successIconSvg;
      button.classList.add('copied');
      button.disabled = true;
      button.setAttribute('aria-label', '已复制');
      setTimeout(() => {
        if (document.body.contains(button) && button.classList.contains('copied')) {
          button.innerHTML = icons.copyIconSvg;
          button.classList.remove('copied');
          button.disabled = false;
          button.setAttribute('aria-label', '复制代码');
        }
      }, 2000);
      e.clearSelection();
    });
    clipboard.on('error', e => {
      console.error('[CodeEventListener] ClipboardJS error:', e);
      const button = e.trigger;
      button.innerHTML = icons.errorIconSvg;
      button.classList.add('error');
      button.disabled = true;
      button.setAttribute('aria-label', '复制失败');
      setTimeout(() => {
        if (document.body.contains(button) && button.classList.contains('error')) {
          button.innerHTML = icons.copyIconSvg;
          button.classList.remove('error');
          button.disabled = false;
          button.setAttribute('aria-label', '复制代码');
        }
      }, 2000);
    });
    clipboardInstances.push(clipboard);
  });

  // 返回清理函数
  return () => {
    clipboardInstances.forEach(clipboard => {
      clipboard.destroy();
    });
  };
}

/**
 * 绑定代码块相关事件
 */
function bindCodeBlockEvents(container) {
  // 绑定代码块悬停事件
  const codeBlocks = container.querySelectorAll('.code-block-wrapper');
  codeBlocks.forEach(element => {
    const codeBlock = element;
    codeBlock.addEventListener('mouseenter', event => onCodeBlockHover(event, codeBlock));
    codeBlock.addEventListener('mouseleave', event => onCodeBlockLeave(event, codeBlock));
  });
}

/**
 * 处理代码块悬停事件
 */
function onCodeBlockHover(_event, element) {
  element.classList.add('hovered');
}

/**
 * 处理代码块离开事件
 */
function onCodeBlockLeave(_event, element) {
  element.classList.remove('hovered');
}

/**
 * 清理元素的事件监听器
 */
function cleanupElement(element, state) {
  const cleanup = state.cleanupFunctions.get(element);
  if (cleanup) {
    cleanup();
    state.cleanupFunctions.delete(element);
  }
}

exports.handleCodeEventListenerCleanup = handleCodeEventListenerCleanup;
exports.handleCodeEventListenerMount = handleCodeEventListenerMount;
