import { lazy, Suspense } from 'react'
import { ChatAgentMessage } from './chat-agent-message'
import type { ChatAgentMessageMarkdownProps } from '../types'

// Lazy-loaded so the markdown engine (`react-markdown` + remark/rehype plugins)
// stays in a separate async chunk: consumers only pay its bundle cost when they
// actually import this component. The Suspense fallback renders the raw text
// until the chunk resolves.
const MarkdownContent = lazy(() =>
  import('../../widgets-v2/markdown/markdown-content').then((m) => ({
    default: m.MarkdownContent,
  })),
)

/**
 * Agent reply bubble that renders its (string) children as GitHub-Flavored
 * Markdown through the library's sanitized renderer — raw HTML is skipped and
 * images are stripped, since the content is model output; tables / task lists /
 * strikethrough pick up the bubble's element styling. Composition over
 * `ChatAgentMessage`, which stays a plain styles container.
 */
export function ChatAgentMessageMarkdown({
  children,
  ...props
}: ChatAgentMessageMarkdownProps) {
  return (
    <ChatAgentMessage {...props}>
      <Suspense fallback={children}>
        <MarkdownContent content={children} gfm />
      </Suspense>
    </ChatAgentMessage>
  )
}
ChatAgentMessageMarkdown.displayName = 'ChatAgentMessageMarkdown'
