import React, { FC } from 'react';
import parse from 'html-react-parser';
import Link from '../../../molecules/Link';
import { traverseJsxTree } from '../../../utils/traverseJsxTree';
import { toKebabCase } from '../../../utils/toKebabCase';

interface HTMLProps {
  rawHtml: string;
}

export const HtmlParser: FC<HTMLProps> = ({ rawHtml }) => {
  const reactNodes = parse(rawHtml);
  if (!Array.isArray(reactNodes)) {
    return null;
  }

  const parsedNodes = traverseJsxTree(reactNodes, node => {
    switch (node.type) {
      case 'a':
        return <Link {...node.props} />;
      case 'h1':
      case 'h2':
      case 'h3':
        const Heading = node.type;
        return <Heading {...node.props} id={toKebabCase(node.props.children)} className="tw-scroll-mt-28" />;
      case 'br':
      default:
        return null;
    }
  });

  return (
    <div className="tw-scroll-smooth">
      <div className="html_parser">{parsedNodes}</div>
    </div>
  );
};
