import React, { useEffect, useRef } from "react";
import "katex/dist/katex.min.css";

import marked, { getTocContent, cleanToc } from "../common/marked";

let preRegex = /<pre[^>]*>/g;

export default ({ value = "", is_md = true, className, style = {} }) => {
  let str = String(value);
  let html = is_md ? marked(str) : value;
  if (str.match(/\[TOC\]/)) {
    html = html.replace("<p>[TOC]</p>", getTocContent());
    cleanToc();
  }

  html = html.replace(/▁/g, "▁▁▁");
  const el = useRef();

  function onAncherHandler(e) {
    let target = e.target;
    if (target.tagName.toUpperCase() === "A") {
      let ancher = target.getAttribute("href");
      if (ancher.startsWith("#")) {
        e.preventDefault();
        let viewEl = document.getElementById(ancher.replace("#", ""));
        if (viewEl) {
          viewEl.parentNode.scrollTop = viewEl.offsetTop;
        }
      }
    }
  }

  useEffect(() => {
    if (el.current && html) {
      if (html.match(preRegex)) {
        window.PR.prettyPrint();
      }
    }
    if (el.current) {
      el.current.addEventListener("click", onAncherHandler);
      return () => {
        el.current.removeEventListener("click", onAncherHandler);
      };
    }
  }, [html, el.current, onAncherHandler]);

  return (
    <div
      ref={el}
      style={style}
      className={`${className ? className : ""} markdown-body`}
      dangerouslySetInnerHTML={{ __html: html }}
    ></div>
  );
};
