import React from "react";

import { Text } from "../Text";
import { BlockSpec } from "./index";

const mapTree = (node: BlockSpec, nodeIndex: number, options) => {
  if (node.type === "text" && node.text && !node.content && !node.marks) {
    return (
      <Text inherit key={nodeIndex}>
        {node.text}
      </Text>
    );
  }

  const typeHandler = options.typeMap[node.type];
  if (!typeHandler) {
    return null;
  }

  const props =
    typeof typeHandler === "string" ? node.attrs || {} : { ...options, node };
  props.key = nodeIndex;

  if (node.content && node.content.length > 0) {
    return React.createElement(
      typeHandler,
      props,
      node.content.map((child, index) => mapTree(child, index, options))
    );
  }

  return React.createElement(typeHandler, props);
};

export default mapTree;
