"use client";

import { useEffect, useState } from "react";

import { highlightCode, type HighlightLang } from "@/lib/highlight-code";
import { cn } from "@/lib/utils";

type DocCodeProps = {
  children: string;
  language?: HighlightLang;
  className?: string;
};

export function DocCode({
  children,
  language = "json",
  className,
}: DocCodeProps): React.ReactElement {
  const [html, setHtml] = useState<string | null>(null);
  const code = children.trimEnd();

  useEffect(() => {
    let cancelled = false;

    void highlightCode(code, language).then((result) => {
      if (!cancelled) {
        setHtml(result);
      }
    });

    return () => {
      cancelled = true;
    };
  }, [code, language]);

  return (
    <div
      className={cn(
        "overflow-x-auto rounded-xl border border-border bg-[#f6f8fa]",
        className,
      )}
    >
      {html ? (
        <div
          className="[&_code]:font-mono [&_pre]:m-0 [&_pre]:overflow-x-auto [&_pre]:bg-transparent [&_pre]:p-4 [&_pre]:text-[13px] [&_pre]:leading-7"
          dangerouslySetInnerHTML={{ __html: html }}
        />
      ) : (
        <pre className="m-0 overflow-x-auto p-4 font-mono text-[13px] leading-7 text-foreground">
          {code}
        </pre>
      )}
    </div>
  );
}
