import {
  Component,
  splitProps,
  JSX,
  createEffect,
  createSignal,
} from "solid-js";
import { unified } from "unified";
import remarkParse from "remark-parse";
import remarkBreaks from "remark-breaks";
import remarkRehype from "remark-rehype";
import rehypeStringify from "rehype-stringify";
import rehypeSlug from "rehype-slug";
import remarkToc from "remark-toc";
import remarkCustomHeadingId from "remark-heading-id";
import remarkGfm from "remark-gfm";
import HelpIcon from "~icons/carbon/help";

export const markdownHelpUrl =
  "https://drdanielappel.de/tipps-tools/markdown-eine-einfach-zu-erlernende-auszeichnungssprache/#cmtoc_anchor_id_0";

export const MarkdownHelpLabel: Component = () => (
  <a
    class="link flex items-center text-xs gap-1"
    rel="noopener"
    target="_blank"
    href={markdownHelpUrl}
  >
    Markdown
    <HelpIcon />
  </a>
);

const Markdown: Component<
  { value: string } & JSX.HTMLAttributes<HTMLDivElement>
> = (p) => {
  const [props, rest] = splitProps(p, ["value", "class"]);
  const [html, setHtml] = createSignal("");

  createEffect(function () {
    const markdown = props.value;
    (async () => {
      const result = await unified()
        .use(remarkParse)
        .use(remarkGfm)
        .use(remarkBreaks)
        .use(remarkCustomHeadingId)
        .use(remarkToc, {
          maxDepth: 3,
          tight: true,
          ordered: true,
          heading: "inhalt|inhaltsverzeichnis|toc|table[ -]of[ -]contents?",
        })
        .use(remarkRehype)
        .use(rehypeSlug)
        .use(rehypeStringify)
        .process(markdown);
      setHtml(String(result));
    })();
  });

  return (
    <div
      class={
        "text-base-content leading-snug break-words hyphenate max-w-none prose whitespace-normal " +
        (props.class || "")
      }
      innerHTML={html()}
      {...rest}
    />
  );
};

export default Markdown;
