import { useState, useEffect } from 'react';
import { TextRenderer } from './TextRenderer';
import { highlight } from './highlight';

type CodeRendererProps = {
  content: string;
  lang: string;
};

export const CodeRenderer = ({ content, lang }: CodeRendererProps) => {
  const [html, setHtml] = useState<string | null>(null);

  useEffect(() => {
    let cancelled = false;
    highlight(content, lang).then((result) => {
      if (!cancelled) setHtml(result);
    });
    return () => {
      cancelled = true;
    };
  }, [content, lang]);

  if (html === null) {
    return <TextRenderer content={content} />;
  }

  return (
    <div
      className="code-highlight text-sm leading-relaxed [&_pre]:p-4 [&_pre]:overflow-x-auto [&_pre]:rounded-none [&_code]:font-mono"
      dangerouslySetInnerHTML={{ __html: html }}
    />
  );
};
