import React from 'react'
// import './index.css'

type AITextRenderProps = {
  text: string
}

// 定义解析后的节点类型
type TextStyle = 'dialogue' | 'emphasis' | 'emphasis2' | 'supplement'

type TextNode = {
  styles: TextStyle[]
  content: string
}

/**
 * 解析文本为节点数组
 * @param text 原始文本
 * @returns 解析后的节点数组
 */
const parseText = (text: string): TextNode[] => {
  const nodes: TextNode[] = []
  const activeStyles = new Set<TextStyle>()
  let buffer = ''

  const flush = () => {
    if (!buffer) return
    nodes.push({ styles: Array.from(activeStyles), content: buffer })
    buffer = ''
  }

  let i = 0
  while (i < text.length) {
    const char = text[i]

    // 换行符: \n
    if (char === '\n') {
      flush()
      nodes.push({ styles: [], content: '\n' })
      i += 1
      continue
    }

    // 一级强调: *
    // 不保留标记符号
    if (char === '*') {
      flush()
      if (activeStyles.has('emphasis')) {
        activeStyles.delete('emphasis')
      } else {
        activeStyles.add('emphasis')
      }
      i += 1
      continue
    }

    // 二级强调: ^
    // 不保留标记符号
    if (char === '^') {
      flush()
      if (activeStyles.has('emphasis2')) {
        activeStyles.delete('emphasis2')
      } else {
        activeStyles.add('emphasis2')
      }
      i += 1
      continue
    }

    // 对话: "" (英文双引号)
    if (char === '"') {
      if (activeStyles.has('dialogue')) {
        // Closing: include quote, flush, remove style
        buffer += char
        flush()
        activeStyles.delete('dialogue')
      } else {
        // Opening: flush prev, add style, include quote
        flush()
        activeStyles.add('dialogue')
        buffer += char
      }
      i += 1
      continue
    }

    // 对话: “” (中文双引号)
    if (char === '“') {
      flush()
      activeStyles.add('dialogue')
      buffer += char
      i += 1
      continue
    }

    if (char === '”') {
      buffer += char
      flush()
      activeStyles.delete('dialogue')
      i += 1
      continue
    }

    // 对话：「」
    if (char === '「') {
      flush()
      activeStyles.add('dialogue')
      buffer += char
      i += 1
      continue
    }
    if (char === '」') {
      buffer += char
      flush()
      activeStyles.delete('dialogue')
      i += 1
      continue
    }

    // 补充: () or （）
    if (char === '(' || char === '（') {
      flush()
      activeStyles.add('supplement')
      buffer += char
      i += 1
      continue
    }

    if (char === ')' || char === '）') {
      buffer += char
      flush()
      activeStyles.delete('supplement')
      i += 1
      continue
    }

    buffer += char
    i += 1
  }

  flush()

  return nodes
}

/**
 * 渲染单个节点
 * @param node 文本节点
 * @param index 节点索引
 * @returns React 元素
 */
const renderNode = (node: TextNode, index: number): React.ReactNode => {
  const { styles, content } = node

  // 处理换行符
  if (content === '\n') {
    return <br key={index} />
  }

  let className = ''

  if (styles.length === 0) {
    return <span key={index}>{content}</span>
  }

  // 叠加样式
  if (styles.includes('dialogue')) {
    className += ' text-[rgba(255,236,159,1)]'
  }

  if (styles.includes('emphasis')) {
    className += ' font-semibold'
  }

  if (styles.includes('emphasis2')) {
    className += ' underline'
  }

  if (styles.includes('supplement')) {
    className += ' text-[rgba(181,177,207,1)]'
  }

  return (
    <span key={index} className={className.trim()}>
      {content}
    </span>
  )
}

/**
 * AI 文本渲染组件
 */
const AITextRender = React.memo(({ text }: AITextRenderProps) => {
  // 1. 解析文本
  const nodes = parseText(text)

  // 2. 渲染节点
  // 这里的 className "ai-text-render" 对应 CSS 中的根类，用于控制全局字体、行高等
  return (
    <span className="ai-text-render">{nodes.map((node, index) => renderNode(node, index))}</span>
  )
})

export default AITextRender
