import markdownIt from "markdown-it";
const md = markdownIt();

export default {
  layout: "default",
  tags: "post",
  permalink:
    "/{{ page.date | date: '%Y/%m/%d', 'Etc/UTC' }}/{{ page.fileSlug }}.html",
  showDate: true,
  eleventyComputed: {
    description: async (data) => {
      if (data.description !== undefined && data.description !== "")
        return data.description.trim();
      if (data.page.rawInput === undefined) return null;
      const markdownAST = md.parse(data.page.rawInput, {});
      let firstParagraph = "";
      let skippingBlockquote = false;
      let skippingStrikethrough = false;
      extractParagraph: for (const astNode of markdownAST) {
        if (skippingBlockquote) {
          if (astNode.type === "blockquote_close") skippingBlockquote = false;
          continue;
        }
        switch (astNode.type) {
          case "paragraph_open":
            continue;
          case "inline":
            for (const child of astNode.children) {
              if (skippingStrikethrough) {
                if (child.type === "s_close") {
                  skippingStrikethrough = false;
                  // hopefully this is just never wrong
                  if (firstParagraph.endsWith(" ")) {
                    firstParagraph = firstParagraph.replace(/ $/, "");
                  }
                }
                continue;
              }
              switch (child.type) {
                case "text":
                case "code_inline":
                  firstParagraph += child.content;
                  break;
                case "softbreak":
                  firstParagraph += " ";
                  break;
                case "link_open":
                case "link_close":
                case "em_open":
                case "em_close":
                case "strong_open":
                case "strong_close":
                  break;
                case "s_open":
                  skippingStrikethrough = true;
                  break;
                default:
                  console.log(data.page.fileSlug, "inline", child);
              }
            }
            break;
          case "paragraph_close":
            break extractParagraph;
          case "blockquote_open":
            skippingBlockquote = true;
            break;
          case "ordered_list_open":
            throw TypeError(
              `Can't auto-generate description for ${data.page.inputPath} - starts with list`,
            );
          default:
            console.log(data.page.fileSlug, "block", astNode);
        }
      }
      return firstParagraph;
    },
  },
};
