import { Fragment, useMemo } from 'react';
import classnames from 'classnames';
import customizable from "../../../../utils/css/customizable.js";
import useMarkdownContext from '../context';
const tagNameMap = {
  h1: 'heading-one',
  h2: 'heading-two',
  h3: 'heading-three',
  h4: 'heading-four',
  h5: 'heading-five',
  h6: 'heading-six',
  p: 'paragraph',
  blockquote: 'blockquote',
  ol: 'numbered-list',
  ul: 'bulleted-list',
  li: 'list-item',
  hr: 'rule',
  img: 'image',
  a: 'link',
  strong: 'strong',
  em: 'emphasis',
  code: 'code',
  span: 'marker'
};
const inlineTags = new Set(['a', 'strong', 'em', 'code', 'span']);
const Node = function Node(props) {
  const {
    children,
    node
  } = props;
  const {
    components: customComponents = {},
    classes,
    inline,
    linksExternal,
    tracking
  } = useMarkdownContext();
  const tagMap = tagNameMap;
  const {
    tagName
  } = node;
  const nodeName = tagMap[tagName];
  const isFragment = inline && !inlineTags.has(tagName);
  const defaultTag = isFragment ? Fragment : tagName;
  const Tag = customComponents[nodeName] || defaultTag;
  const isCustomComponent = !!customComponents[nodeName];
  const [target, rel] = useMemo(() => {
    if (nodeName === 'link' && linksExternal) {
      return ['_blank', 'noreferrer'];
    }
    if (nodeName === 'link') {
      return ['_top', undefined];
    }
    return [undefined, undefined];
  }, [nodeName, linksExternal]);
  const customProps = {
    node,
    tracking
  };
  const defaultTagProps = {
    className: classnames(customizable(`MarkdownContent__${nodeName}`), classes[nodeName]),
    target,
    rel,
    ...(isCustomComponent ? customProps : {}),
    ...node.properties
  };
  const tagProps = isFragment ? {} : defaultTagProps;
  return <Tag {...tagProps}>
      {children}
    </Tag>;
};
export default Node;