import { Marked } from "https://cdn.jsdelivr.net/npm/marked@15.0.7/+esm"
import { gfmHeadingId } from "https://cdn.jsdelivr.net/npm/marked-gfm-heading-id/+esm"
import { markedSmartypants } from "https://cdn.jsdelivr.net/npm/marked-smartypants/+esm"
import { markedXhtml } from "https://cdn.jsdelivr.net/npm/marked-xhtml/+esm"
import markedFootnote from "https://cdn.jsdelivr.net/npm/marked-footnote/+esm"
import grayMatter from "https://cdn.jsdelivr.net/npm/gray-matter@4.0.3/+esm"
export const take = [
  { type: "code", label: "Markdown" },
  { type: "toggle", label: "Preview" },
  {
    type: "group",
    label: "Options",
    value: [
      {
        type: "toggle",
        key: "gfm",
        label: "GitHub Flavored Markdown",
        detail: "Follow the GitHub Flavored Markdown (GFM) specification.",
      },
      {
        type: "toggle",
        key: "headerIds",
        label: "Add IDs to headings",
        detail: "Include an `id` attribute on headings (h1, h2, h3, etc).",
      },
      {
        type: "toggle",
        key: "smartypants",
        label: "Smart typography",
        detail: 'Use "smart" typographic punctuation for quotes and dashes.',
      },
      {
        type: "toggle",
        key: "footnotes",
        label: "Footnotes",
        detail: "Compile footnotes from `[^1]` style references.",
      },
      {
        type: "toggle",
        key: "breaks",
        label: "Line breaks",
        detail:
          'Add `<br>` after a single line break. Requires "GitHub Flavored Markdown".',
      },
      {
        type: "toggle",
        key: "xhtml",
        label: "XHTML",
        detail: "Use self-closing tags for void elements, like `<br/>`.",
      },
      {
        type: "toggle",
        key: "pedantic",
        label: "Pedantic",
        detail: "Conform to original `markdown.pl`. Disables GFM.",
      },
    ],
  },
]
export const make = ([
  markdown,
  preview,
  { gfm, breaks, headerIds, smartypants, footnotes, xhtml, pedantic },
]) => {
  const marked = new Marked({ gfm, breaks, pedantic })
  if (headerIds) marked.use(gfmHeadingId())
  if (xhtml) marked.use(markedXhtml())
  if (smartypants) marked.use(markedSmartypants())
  if (footnotes) marked.use(markedFootnote())
  const { content, data } = grayMatter(markdown)
  const value = marked.parse(content)
  return preview
    ? [
        {
          type: "html",
          label: "Preview",
          value,
          height: 400,
        },
      ]
    : [
        {
          type: "code",
          label: "HTML",
          value,
        },
        Object.keys(data).length > 0
          ? {
              type: "json",
              label: "Front matter",
              value: data,
            }
          : null,
      ]
}