import { IdAttributePlugin } from "@11ty/eleventy";
import { eleventyImageTransformPlugin } from "@11ty/eleventy-img";
import eleventyNavigationPlugin from "@11ty/eleventy-navigation";
import { feedPlugin } from "@11ty/eleventy-plugin-rss";
import syntaxHighlight from "@11ty/eleventy-plugin-syntaxhighlight";
import { attrs } from "@mdit/plugin-attrs";
import { chunk } from "lodash-es";
import path from "node:path";

import pluginFilters from "./_config/filters.js";

export default async function(eleventyConfig) {
	/* Markdown HTML attribute parsing */
	eleventyConfig.amendLibrary("md", (mdLib) => mdLib.use(attrs));

	/* Bundles */
	/* CSS */
	eleventyConfig.addBundle("css", {
		toFileDirectory: "dist",
		bundleHtmlContentFromSelector: "style",
	});

	/* Javascript */
	eleventyConfig.addBundle("js", {
		toFileDirectory: "dist",
		bundleHtmlContentFromSelector: "script",
	});

	/* Collections */
	/* Tag pagination */
	eleventyConfig.addCollection("tagPagination", function(collection) {
		let tagSet = new Set(collection.getAllSorted().flatMap((post) => post.data.tags || []));
		tagSet = tagSet.difference(new Set(["posts", "gallery", "reference", "blur"]));

		let paginationSize = 13;
		let tagMap = [];
		let tagArray = [...tagSet];

		for( let tagName of tagArray) {
			let tagItems = collection.getFilteredByTag(tagName);
			let pagedItems = chunk(tagItems.reverse(), paginationSize);			// console.log( tagName, tagItems.length, pagedItems.length );

			for( let pageNumber = 0, max = pagedItems.length; pageNumber < max; pageNumber++) {
				tagMap.push({
					tagName: tagName,
					pageNumber: pageNumber,
					pageSize: pagedItems.length,
					pageData: pagedItems[pageNumber]
				});
			}
		}

		return tagMap;
	});

	/* Passthrough */
	eleventyConfig
		.addPassthroughCopy("favicon.ico")
		.addPassthroughCopy("robots.txt");

	/* Plugins */
	/* All filters from _config/filters.js */
	eleventyConfig.addPlugin(pluginFilters);

	/* RSS */
	eleventyConfig.addPlugin(feedPlugin, {
		type: "atom", // or "rss", "json"
		outputPath: "/feed.xml",
		stylesheet: "/feed.xsl",
		collection: {
			name: "posts", // iterate over `collections.posts`
			limit: 10,     // 0 means no limit
		},
		metadata: {
			language: "en",
			title: "hello hello",
			subtitle: "Lee Cattarin... on the internet!",
			base: "https://leecat.art",
			author: {
				name: "Lee Cattarin",
				email: "lee.cattarin@gmail.com",
			}
		}
	});

	/* Images */
	eleventyConfig.addPlugin(eleventyImageTransformPlugin, {
		// output image formats
		formats: ["auto"],

		// output image widths
		widths: [1000],

		// optional, attributes assigned on <img> nodes override these values
		htmlOptions: {
			imgAttributes: {
				loading: "lazy",
				decoding: "async",
			},
		},
		filenameFormat: function (hash, src, width, format, options) {
			// If you're building multiple widths
			// const extension = path.extname(src);
			// const name = path.basename(src, extension);

			// return `${name}-${width}.${extension}`;
			return path.basename(src);
		},
	});

	/* Navigation */
	eleventyConfig.addPlugin(eleventyNavigationPlugin);

	/* `id` attributes */
	eleventyConfig.addPlugin(IdAttributePlugin);

	/* Syntax highlighting */
	eleventyConfig.addPlugin(syntaxHighlight);

	/* Draft handling */
	eleventyConfig.addPreprocessor("drafts", "*", (data, content) => {
		if (data.draft) {
			data.title = `${data.title} (draft)`;
		}

		if(data.draft && process.env.ELEVENTY_RUN_MODE === "build") {
			return false;
		}
	});

	/* Shortcodes */
	eleventyConfig.addShortcode("currentBuildDate", () => {
		return (new Date()).toISOString();
	});

	/* Watch when serving */
	eleventyConfig.addWatchTarget("css");
};

export const config = {
  dir: {
    input: "src",
		includes: "../_includes",
		layouts: "../_includes/layouts",
		data: "../_data"
  },
	markdownTemplateEngine: "njk",
	htmlTemplateEngine: "njk",
	templateFormats: ["html", "md", "njk"],
};
