import type { ExtraProps } from 'react-markdown';
import { CodeSurface } from './CodeSurface';

/**
 * The `<pre>` react-markdown produces for a fenced block, on the shared code surface.
 *
 * This file is only the adapter: pull the source and the language back out of the hast node, and hand
 * them to `CodeSurface`, which is also what a tool call renders into. `children` is kept as the fallback
 * for a `<pre>` that arrived without a `<code>` inside — markdown does not produce one, but raw html
 * surviving the sanitiser might.
 */

const getNodeText = (node: unknown): string => {
  const n = node as { value?: string; children?: unknown[] } | undefined;
  if (!n) return '';
  if (typeof n.value === 'string') return n.value;
  return (n.children ?? []).map(getNodeText).join('');
};

function readFence(node: ExtraProps['node']): { code: string; lang: string } {
  const child = node?.children[0];
  if (!child || child.type !== 'element' || child.tagName !== 'code') return { code: '', lang: '' };
  const classes = (child.properties?.className ?? []) as string[];
  const lang = classes.find((c) => c.startsWith('language-'))?.slice('language-'.length) ?? '';
  return { code: getNodeText(child).replace(/\n$/, ''), lang };
}

export const CodeBlock = ({ children, node }: React.ComponentPropsWithoutRef<'pre'> & ExtraProps) => {
  const { code, lang } = readFence(node);
  return <CodeSurface code={code} lang={lang} fallback={children} />;
};
