import { useEffect, useRef } from "react";
import { renderMarkdownInto } from "../lib/markdown";
import { initPostToc, teardownPostTocUi } from "../lib/postToc";

export function MarkdownBody({ markdown }: { markdown: string }) {
  const ref = useRef<HTMLDivElement | null>(null);

  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    teardownPostTocUi();
    if (!markdown.trim()) {
      el.innerHTML = "";
      return;
    }
    el.classList.add("markdown-body", "markdown-pending");
    el.innerHTML = '<p class="markdown-loading">加载中…</p>';
    let cancelled = false;
    (async () => {
      try {
        await renderMarkdownInto(el, markdown);
        if (!cancelled) initPostToc(el);
      } catch {
        if (!cancelled) {
          el.innerHTML = "<p>渲染失败。</p>";
          el.classList.remove("markdown-pending");
        }
      }
    })();
    return () => {
      cancelled = true;
      teardownPostTocUi();
    };
  }, [markdown]);

  return <div ref={ref} className="markdown-body" />;
}
