import { useState, useCallback, type HTMLAttributes, type ReactElement } from 'react'; import { Check, Copy } from 'lucide-react'; /** Extract the language from the nested element's className (e.g. "language-ts"). */ function extractLanguage(children: React.ReactNode): string | null { const codeEl = children as ReactElement<{ className?: string }> | undefined; const className = codeEl?.props?.className; if (typeof className !== 'string') return null; const match = className.match(/language-(\S+)/); return match ? match[1] : null; } /** Pretty-print common language identifiers. */ const LANGUAGE_LABELS: Record = { js: 'JavaScript', jsx: 'JSX', ts: 'TypeScript', tsx: 'TSX', py: 'Python', rb: 'Ruby', rs: 'Rust', go: 'Go', sh: 'Shell', bash: 'Bash', zsh: 'Zsh', yml: 'YAML', yaml: 'YAML', md: 'Markdown', json: 'JSON', html: 'HTML', css: 'CSS', sql: 'SQL', dockerfile: 'Dockerfile', toml: 'TOML', }; function formatLanguage(lang: string): string { return LANGUAGE_LABELS[lang] || lang; } /** * Custom
 renderer for ReactMarkdown.
 * Wraps code blocks with a language label and a floating copy button.
 */
export function CodeBlock(props: HTMLAttributes) {
  const [copied, setCopied] = useState(false);
  const language = extractLanguage(props.children);

  const handleCopy = useCallback(() => {
    // Extract text from the nested  element
    const code = (props.children as ReactElement<{ children?: string }> | undefined)?.props?.children;
    if (typeof code === 'string') {
      navigator.clipboard.writeText(code).then(() => {
        setCopied(true);
        setTimeout(() => setCopied(false), 2000);
      });
    }
  }, [props.children]);

  return (
    
{language && (
{formatLanguage(language)}
)}
      
    
); }