// components/markdown/markdown-viewer.tsx
"use client"

import { useEffect, useRef } from "react"
import { marked } from "marked"
import DOMPurify from "dompurify"

interface MarkdownViewerProps {
  content: string
  className?: string
}

export function MarkdownViewer({ content, className = "" }: MarkdownViewerProps) {
  const containerRef = useRef<HTMLDivElement>(null)

  useEffect(() => {
    if (containerRef.current) {
      const renderMarkdown = async () => {
        marked.setOptions({
          breaks: true,
          gfm: true,
        })

        const rawHtml = await marked(content)
        if (containerRef.current) {
          containerRef.current.innerHTML = DOMPurify.sanitize(rawHtml)
          const codeBlocks = containerRef.current.querySelectorAll("pre code")
          codeBlocks.forEach(block => {
            block.classList.add("bg-muted", "p-2", "rounded", "text-sm")
          })
        }
      }

      renderMarkdown()
    }
  }, [content])

  return (
    <div
      ref={containerRef}
      className={`prose prose-sm dark:prose-invert max-w-none ${className}`}
      style={{
        fontSize: "0.875rem",
        lineHeight: "1.5",
      }}
    />
  )
}
