import { useEffect, useRef } from 'react'
import hljs from 'highlight.js/lib/core'
import python from 'highlight.js/lib/languages/python'
import json from 'highlight.js/lib/languages/json'
import 'highlight.js/styles/atom-one-dark.css'

hljs.registerLanguage('python', python)
hljs.registerLanguage('json', json)

/**
 * CodeBlock — a syntax-highlighted <pre><code> block.
 *
 * Dark, compact styling tuned to match the Claude-ish palette. Uses hljs's
 * atom-one-dark theme then overrides the background with our canvas so it
 * blends with the card surface.
 */
export function CodeBlock({ code, language = 'python', className = '' }) {
  const ref = useRef(null)

  useEffect(() => {
    if (ref.current) {
      // Remove the hljs "highlighted" marker so reruns pick up the new code
      delete ref.current.dataset.highlighted
      hljs.highlightElement(ref.current)
    }
  }, [code, language])

  return (
    <pre className={`rounded-lg border border-border overflow-x-auto
                     bg-[#14120f] my-1 ${className}`}>
      <code ref={ref} className={`language-${language} block p-4 text-[0.82rem]
                                  leading-relaxed font-mono !bg-transparent`}>
        {code}
      </code>
    </pre>
  )
}
