import {
  h, useEffect, useProp, useRef,
} from "atomico";
import "../kun-ex-link/kun-ex-link";
// import style1 from "highlight.js/styles/github.css";
import hljs from "highlight.js";
import scala from "highlight.js/lib/languages/scala";
import style from "./kun-rich-html.scss";
import { getComponentOrDefine } from "../../hooks/aync-hook/redirect";
import { styleEditor } from "../kun-editor/const-editor-style";
import { useAsyncHook } from "../../hooks/use-async-hook/use-async-hook";

const KunRichHtml = () => {
  const ref = useRef();
  const [kunHtml] = useProp<string>("kunHtml");

  useEffect(() => {
    if (ref != null && ref.current != null) {
      const f1 = kunHtml || "<div>暂未填写内容</div>";
      (ref.current as HTMLInputElement).innerHTML = f1;
    }
  }, [kunHtml]);

  useAsyncHook(async () => {
    hljs.registerLanguage("scala", scala);
    hljs.initHighlightingOnLoad();
  }, []);

  const catchHref = (event: MouseEvent): void => {
    const tagName = event.target?.tagName;
    if (tagName === "A") {
      const el = event.target as HTMLElement;
      window.open(`/web/plume/redirect-page?url=${el.getAttribute("href")}`);
    }
    event.stopPropagation();
    event.preventDefault();
    console.log("evt", event.target?.tagName);
  };

  useEffect(() => {
    ref.current.addEventListener("click", catchHref);
    return () => {
      ref.current.removeEventListener("click", catchHref);
    };
  }, []);

  // TODO code style
  const allS = `${styleEditor}\n${style}\n`;

  return (
    <host>
      <style>{allS}</style>
      <div ref={ref} class="editor kun-rich-html-post editor__content html" />
    </host>
  );
};

KunRichHtml.props = {
  kunHtml: {
    type: String,
  },
};

export default getComponentOrDefine("kun-rich-html", KunRichHtml);
