// Renders an assistant message: markdown for prose, and a small "Ran N
// actions" pill in place of any ```action``` fenced blocks (which are the
// machine-readable instructions the bus has already executed).

import { useMemo } from "react"
import ReactMarkdown from "react-markdown"
import { Sparkles } from "lucide-react"

import { extractActionBlocks } from "@crema/action-bus"

const ACTION_BLOCK_RE = /```action\s*\n[\s\S]*?```/g

export function MessageBody({ content }: { content: string }) {
  const { prose, actionCount } = useMemo(() => {
    const blocks = extractActionBlocks(content)
    return {
      prose: content.replace(ACTION_BLOCK_RE, "").trim(),
      actionCount: blocks.length,
    }
  }, [content])

  return (
    <div className="prose prose-sm max-w-none dark:prose-invert">
      {prose && (
        <ReactMarkdown
          components={{
            // Tight overrides — keep paragraphs compact in chat bubbles
            p: ({ children }) => <p className="my-1.5 leading-relaxed">{children}</p>,
            code: ({ children, className }) => {
              const isBlock = className?.startsWith("language-")
              if (isBlock) {
                return (
                  <pre className="my-2 overflow-x-auto rounded-md bg-muted p-3 text-xs">
                    <code className="font-mono">{children}</code>
                  </pre>
                )
              }
              return (
                <code className="rounded bg-muted px-1 py-0.5 font-mono text-[0.85em]">
                  {children}
                </code>
              )
            },
            ul: ({ children }) => <ul className="my-1.5 list-disc pl-5">{children}</ul>,
            ol: ({ children }) => <ol className="my-1.5 list-decimal pl-5">{children}</ol>,
            li: ({ children }) => <li className="my-0.5">{children}</li>,
            a: ({ children, href }) => (
              <a href={href} className="text-primary underline underline-offset-2" target="_blank" rel="noreferrer">
                {children}
              </a>
            ),
          }}
        >
          {prose}
        </ReactMarkdown>
      )}
      {actionCount > 0 && (
        <span
          className="mt-1 inline-flex items-center gap-1.5 rounded-full border border-primary/30 bg-primary/10 px-2.5 py-0.5 text-xs font-medium text-primary"
          title="Action block executed by the command bus"
        >
          <Sparkles className="size-3" />
          Ran {actionCount} action{actionCount > 1 ? "s" : ""}
        </span>
      )}
    </div>
  )
}
