import { ParsedSegment } from './types';

/**
 * 解析包含提及的文本
 * 将 @{value|label} 格式的文本解析为结构化的片段
 */
export function parseValue(text: string): ParsedSegment[] {
  const segments: ParsedSegment[] = [];
  const mentionRegex = /@\{([^|]+)\|([^}]+)\}/g;
  let lastIndex = 0;
  let match;

  while ((match = mentionRegex.exec(text)) !== null) {
    // 添加提及之前的文本
    if (match.index > lastIndex) {
      segments.push({
        type: 'text',
        content: text.slice(lastIndex, match.index),
      });
    }

    // 添加提及
    segments.push({
      type: 'mention',
      content: match[0],
      value: match[1],
      label: match[2],
    });

    lastIndex = match.index + match[0].length;
  }

  // 添加剩余文本
  if (lastIndex < text.length) {
    segments.push({
      type: 'text',
      content: text.slice(lastIndex),
    });
  }

  return segments;
}

/**
 * 从 HTML 元素中提取纯文本内容
 * 将提及元素转换为 @{value|label} 格式
 */
export function extractTextFromHTML(element: HTMLElement): string {
  const tempDiv = document.createElement('div');
  tempDiv.innerHTML = element.innerHTML;

  // 处理提及元素
  const mentions = tempDiv.querySelectorAll('[data-mention]');
  mentions.forEach((mention) => {
    const value = mention.getAttribute('data-mention');
    const label = mention.textContent?.replace('@', '') || '';
    mention.textContent = `@{${value}|${label}}`;
  });

  return tempDiv.textContent || '';
}

/**
 * 检查文本中 @ 后是否应该触发提及菜单
 */
export function shouldShowMentionPopover(textAfterAt: string): boolean {
  return (
    !textAfterAt.includes(' ') &&
    !textAfterAt.includes('\n') &&
    !textAfterAt.match(/\{[^|]+\|[^}]+\}/)
  );
}

/**
 * 过滤匹配的选项
 */
export function filterOptions<T extends { label: string }>(options: T[], searchText: string): T[] {
  return options.filter((option) => option.label.toLowerCase().includes(searchText.toLowerCase()));
}
