'use client'

import { Loader2 } from 'lucide-react'
import { H5MarkdownRenderer } from '@/components/h5/h5-markdown-renderer'
import { H5AttachmentList } from '@/components/h5/h5-message-render'
import { parseStreamingMedia } from '@/lib/h5/format'
import type { StreamingAttachment } from '@/lib/h5/types'

/**
 * 流式输出气泡：assistant 消息位上的实时渲染。
 *
 * 三态：
 *   error     → 错误提示
 *   有文本/附件 → markdown + 真实附件卡片 + MEDIA: 占位（去重）
 *   空        → 「正在思考...」
 *
 * 后端 attachment 事件带来的真实文件与从 MEDIA: 文本剥出的 pendingFiles 按 name 去重，
 * 避免同一文件在「文本剥离占位」与「attachment 接管」阶段双重显示。
 */
export function H5StreamingBubble({
  streamingText,
  streamingError,
  streamingAttachments,
  streamingActivity,
}: {
  streamingText: string
  streamingError: string | null
  streamingAttachments: StreamingAttachment[]
  streamingActivity?: string | null
}): React.JSX.Element {
  return (
    <div className="h5-msg assistant">
      <div className="h5-msg-content">
        {streamingError ? (
          <div className="h5-tool-bubble error">错误：{streamingError}</div>
        ) : streamingText || streamingAttachments.length > 0 ? (
          (() => {
            const { displayText, pendingFiles } = parseStreamingMedia(streamingText)
            const realNames = new Set(streamingAttachments.map((a) => a.name))
            const pendingOnly = pendingFiles.filter((p) => !realNames.has(p.name))
            return (
              <>
                {displayText ? <H5MarkdownRenderer content={displayText} /> : null}
                <H5AttachmentList attachments={streamingAttachments} />
                {pendingOnly.length > 0 ? (
                  <div className="h5-attachments">
                    {pendingOnly.map((f, i) => (
                      <div key={`pending-${i}`} className="h5-attachment-file pending">
                        <Loader2 size={16} className="h5-attachment-icon" />
                        <span className="h5-attachment-name">{f.name}</span>
                      </div>
                    ))}
                  </div>
                ) : null}
                {streamingActivity ? (
                  <div className="h5-activity-status">
                    <span className="h5-activity-dot" />
                    <span>{streamingActivity}</span>
                  </div>
                ) : null}
              </>
            )
          })()
        ) : (
          <div className="h5-tool-bubble">
            <span className="h5-typing-dots" aria-label={streamingActivity ?? '正在思考'}>
              <span className="h5-typing-dot" />
              <span className="h5-typing-dot" />
              <span className="h5-typing-dot" />
            </span>
            {streamingActivity ?? '正在思考...'}
          </div>
        )}
      </div>
    </div>
  )
}
