import React from "react";

import { Text, TextProps } from "../Text";
import { Mark } from "./index";

const normalizeMark = (mark: Mark) => {
  if (typeof mark === "string") {
    return { type: mark };
  } else if (typeof mark._ === "string") {
    const { _, ...markProps } = mark;

    return {
      ...markProps,
      type: mark._,
    };
  }

  return mark;
};

const TextNode = ({ markMap, node }) => {
  return (node.marks || []).reduceRight((child, mark) => {
    const normalized = normalizeMark(mark);
    const markHandler = markMap[normalized.type];

    if (!markHandler) {
      return child;
    }

    return React.createElement(
      markHandler,
      { ...mark.attrs, inherit: true },
      child
    );
  }, <Text inherit>{node.text}</Text>);
};

export default TextNode;

export const withText = (textProps: TextProps) => {
  const Component = (props: TextProps) => <Text {...textProps} {...props} />;
  Component.displayName = "Text";

  return Component;
};
