import { RenderPlugin, IdAttributePlugin } from "@11ty/eleventy";
import eleventyNavigationPlugin from "@11ty/eleventy-navigation";
import markdownIt from "markdown-it";
import markdownItFootnote from "markdown-it-footnote";
import { DateTime } from "luxon";

export default function (eleventyConfig) {
  const MARKDOWN_OPTIONS = {
    html: true,
    breaks: true,
    linkify: true,
    typographer: true,
  };

  let md = markdownIt(MARKDOWN_OPTIONS).use(markdownItFootnote);

  // Libraries
  eleventyConfig.setLibrary("md", md);

  // Plugins
  eleventyConfig.addPlugin(RenderPlugin);
  eleventyConfig.addPlugin(IdAttributePlugin);
  eleventyConfig.addPlugin(eleventyNavigationPlugin);

  // Filters
  eleventyConfig.addFilter("formatDate", function (date, format) {
    return DateTime.fromJSDate(date).toFormat(format);
  });

  eleventyConfig.addFilter("formatDateRel", function (date) {
    return DateTime.fromJSDate(date).toRelative();
  });

  eleventyConfig.addFilter("md", function (content = "") {
    return md.render(content);
  });

  eleventyConfig.addFilter("mdInline", function (content = "") {
    return md.renderInline(content);
  });

  // Passthrough copies
  ["src/assets"].forEach((path) => {
    eleventyConfig.addPassthroughCopy(path);
  });

  // Watch targets
  eleventyConfig.addWatchTarget("./src/assets/css");

  // Frontmatter parsing
  eleventyConfig.setFrontMatterParsingOptions({ excerpt: true });

  // COLLECTIONS
  ////// Journal categories
  eleventyConfig.addCollection("categories", function (collectionApi) {
    let categories = new Set();
    let posts = collectionApi.getFilteredByTag("post");
    posts.forEach((p) => {
      let cats = p.data.categories;
      cats.forEach((c) => categories.add(c));
    });
    return Array.from(categories);
  });

  return {
    dir: {
      input: "src",
      output: "public",
      includes: "_includes",
      layouts: "_layouts",
    },
  };
}
