import React, { useMemo } from "react";
import { createAstUsingUnified } from "./utils";
import { useMDController } from "./hooks";
import { StyledMarkdown } from "./styled";

export interface MarkdownProps {
  content: string;
  style?: React.CSSProperties;
  className?: string;
}

export function Markdown(props: MarkdownProps) {
  const { content, style, className } = props;

  const controller = useMDController();

  const element = useMemo(() => {
    if (!content || !controller?.renderRoot) return null;

    let rendered;
    try {
      const ast = createAstUsingUnified(content);
      rendered = controller.renderRoot(ast);
    } catch (err) {
      console.error("Markdown AST 解析失败", err);
      return null;
    }

    // 👇 关键：如果返回的是数组，必须包一层 Fragment 并确保 key
    if (Array.isArray(rendered)) {
      console.warn("renderRoot 返回了数组，正在自动修复...", rendered);
      return (
        <>
          {rendered.map((child, index) =>
            child == null ? (
              <span key={index} style={{ color: "red" }}>
                [空节点]
              </span>
            ) : React.isValidElement(child) ? (
              React.cloneElement(child, { key: child.key ?? index })
            ) : (
              <span key={index}>{String(child)}</span>
            )
          )}
        </>
      );
    }

    if (rendered == null) {
      return null;
    }

    // 如果是字符串
    if (typeof rendered === "string") {
      return <>{rendered}</>; // 包装一下
    }

    // 最后兜底：确保是合法 React Element
    if (!React.isValidElement(rendered)) {
      console.error("renderRoot 返回了非 React 元素:", rendered);
      return null;
    }

    return rendered;
  }, [controller, content]);

  return (
    <StyledMarkdown style={style} className={className}>
      {element}
    </StyledMarkdown>
  );
}
