"use client"; import { Children, isValidElement, useCallback, useRef, useState, type ComponentProps, type ReactNode, } from "react"; import { Check, Copy } from "lucide-react"; import { useI18n } from "@/i18n/i18n-context"; import { cn } from "@/lib/utils"; // Streamdown's `Components.pre` is a standard
 component plus an
// optional `node` (hast element) that we strip before forwarding.
type CodeBlockProps = ComponentProps<"pre"> & { node?: unknown };

/**
 * Custom 
 renderer that replaces Streamdown's built-in code block.
 * Works around streamdown#494: the default sticky + pointer-events trick
 * makes copy buttons unclickable inside nested scroll containers, which
 * is exactly our QA layout (dashboard scroll + chat scroll).
 *
 * Layout: a relative wrapper hosts an absolutely positioned header strip
 * with the language label on the left and a hover-revealed copy button
 * on the right, matching the pattern used by ChatGPT / Claude / v0.
 */
export function CodeBlock({
  className,
  children,
  // Streamdown injects a `node` prop (hast element) that would otherwise
  // leak into the DOM and trigger a React warning. Strip it here.
  node: _node,
  ...rest
}: CodeBlockProps) {
  void _node;
  const { t } = useI18n();
  const preRef = useRef(null);
  const [copied, setCopied] = useState(false);

  const language = extractLanguage(children) ?? "";

  const handleCopy = useCallback(async () => {
    const text = preRef.current?.innerText ?? "";
    if (!text) return;
    try {
      await navigator.clipboard.writeText(text);
      setCopied(true);
      window.setTimeout(() => setCopied(false), 2000);
    } catch {
      // Clipboard permission may be denied in insecure contexts; silently
      // no-op so we don't throw inside a render path.
    }
  }, []);

  return (
    
{language || "text"}
        {children}
      
); } /** * Streamdown renders code fences as
...
 * Walk the first element child to grab the language identifier so we can
 * display it in the header strip.
 */
function extractLanguage(children: ReactNode): string | undefined {
  for (const child of Children.toArray(children)) {
    if (!isValidElement(child)) continue;
    const props = child.props as { className?: unknown } | undefined;
    if (typeof props?.className !== "string") continue;
    const match = props.className.match(/language-([a-z0-9+#-]+)/i);
    if (match) return match[1];
  }
  return undefined;
}