import * as sass from "sass";
import Image, { eleventyImageTransformPlugin } from "@11ty/eleventy-img";
import { DateTime } from "luxon";
import markdownit from "markdown-it";
import syntaxHighlight from '@11ty/eleventy-plugin-syntaxhighlight';
import cacheBuster from 'eleventy-auto-cache-buster';

export default async function (eleventyConfig) {
	// Filters
	eleventyConfig.addFilter("dateLocale", function (value) {
		return DateTime.fromJSDate(new Date(value)).toLocaleString({
			year: 'numeric',
			month: 'short',
			day: '2-digit',
		});
	});

	// SCSS
	eleventyConfig.addTemplateFormats("scss");

	eleventyConfig.addExtension("scss", {
		outputFileExtension: "css",
		compile: async function (inputContent) {
			let result = sass.compileString(inputContent);

			return async (data) => {
				return result.css;
			};
		}
	});

	//Images
	eleventyConfig.addPlugin(eleventyImageTransformPlugin, {
		widths: ["700"]
	});
	eleventyConfig.addShortcode("figure", (url, alt, caption, width) => {
		return `
		<figure class="styled-figure">
			<img src="${url}" alt="${alt}" width="${width || "700"}" />
			<figcaption>${caption}</figcaption>
		</figure>
		`;
	});

	eleventyConfig.addShortcode("imageUrl", async (image, width) => {
		const img = await Image(`./content${image}`, {
			outputDir: 'dist/img/',
			useCache: true
		});

		return img.jpeg[0].url;
	});

	//Markdown
	const md = markdownit({
		html: true,
		breaks: true
	});

	eleventyConfig.setLibrary("md", md);

	// Syntax Highlighting
	eleventyConfig.addPlugin(syntaxHighlight);

	// Cache busting
	eleventyConfig.addPlugin(cacheBuster);

	//File passthrough
	eleventyConfig.addPassthroughCopy("content/robots.txt");

	// Portfolio sort
	eleventyConfig.addCollection("portfolioSorted", (collectionsAPi) => {
		const portfolio = collectionsAPi.getFilteredByTag("portfolio");
		const sorted = portfolio.sort((a, b) => a.data.order - b.data.order);
		return sorted;
	});

	eleventyConfig.addWatchTarget("content/portfolio/**/*");

}

export const config = {
	dir: {
		input: "content",
		includes: "includes",
		layouts: "layouts",
		output: "dist"
	}
};