const handlebarsPlugin = require("@11ty/eleventy-plugin-handlebars");
const handlebars = require('handlebars');
const sass = require("sass");
const pluginRss = require("@11ty/eleventy-plugin-rss");
const handlebarsHelpers = require('handlebars-helpers')
const markdownit = require('markdown-it')
const md = markdownit()
const htmlmin = require("html-minifier");
require('dotenv').config();

module.exports = function(eleventyConfig) {
  // Passthrough episodes directory to include both markdown and audio files
  eleventyConfig.addPassthroughCopy("content/episodes/*/*.mp3");
  eleventyConfig.addPassthroughCopy("content/episodes/**/*.jpg");
  eleventyConfig.addPassthroughCopy("content/episodes/**/*.webp");
  eleventyConfig.addPassthroughCopy("content/episodes/**/*.png");
  eleventyConfig.addPassthroughCopy("content/images/*.jpg");
  eleventyConfig.addPassthroughCopy("content/images/*.webp");
  eleventyConfig.addPassthroughCopy("content/feeds/*.jpg");
  eleventyConfig.addPlugin(handlebarsPlugin);
  eleventyConfig.addPlugin(pluginRss);

  // handlebars helpers
  handlebars.registerHelper("formatSeasonEpisode", function(season, episode) {
    // Convert strings to integers and pad with zeros
    const seasonNumber = parseInt(season, 10).toString().padStart(2, '0');
    const episodeNumber = parseInt(episode, 10).toString().padStart(2, '0');
    
    // Return the formatted string
    return `<span class="season">S${seasonNumber}</span><span class="episode">E${episodeNumber}</span>`;
    // return `S${seasonNumber}E${episodeNumber}`;
  });

  handlebarsHelpers({
    handlebars
  })

  eleventyConfig.addFilter("seasonEpisodeFormat", function (season, episode, separator="") {
    const seasonNumber = parseInt(season, 10).toString().padStart(2, '0');
    const episodeNumber = parseInt(episode, 10).toString().padStart(2, '0');
    return [seasonNumber, episodeNumber].join(separator)
		return value;
	});

  // Shortcodes
  eleventyConfig.addPairedShortcode(
    "prologue", 
    function(content) { return `<h2>Prologue</h2><section class="prologue">${md.render(content)}</section>` }
  );
  eleventyConfig.addPairedShortcode(
    "masthead", 
    function(content) { 
      return `<hgroup class="masthead" markdown="1">${md.render(content)}<time datetime="${this.page.date.toISOString()}">${this.page.date.toLocaleDateString()}</time></hgroup>` }
  );
  eleventyConfig.addPairedShortcode(
    "headline", 
    function(content) { 
      return `
      <hgroup class="headline">${md.render(content.trim())}</hgroup>` }
  );
  eleventyConfig.addPairedShortcode(
    "alternateTitles", 
    function(content) { return `<section class="alternate-titles"><h2>Alternate Titles</h2>${md.render(content)}</section>` }
  );

  eleventyConfig.addTransform("htmlmin", (content, outputPath) => {
    if (outputPath.endsWith(".html")) {
      return htmlmin.minify(content, {
        collapseWhitespace: true,
        removeComments: true,  
        useShortDoctype: true,
      });
    }

    return content;
  });

  // Register Helpers
  handlebars.registerHelper('ifEquals', function(arg1, arg2, options) {
    return (arg1 == arg2) ? options.fn(this) : options.inverse(this);
  });

  handlebars.registerHelper('ifIncludes', function(set, candidate, options) {
    return (set.includes(candidate)) ? options.fn(this) : options.inverse(this);
  });

  // Creates the extension for use
  eleventyConfig.addTemplateFormats("scss");
	eleventyConfig.addExtension("scss", {
		outputFileExtension: "css", // optional, default: "html"
		// `compile` is called once per .scss file in the input directory
		compile: async function (inputContent) {
			let result = sass.compileString(inputContent, {
				loadPaths: ["node_modules/bootstrap/scss", ] 
			});

			// This is the render function, `data` is the full data cascade
			return async (data) => result.css;
		},
	});

  eleventyConfig.addNunjucksFilter("podcastUrl", function(post) {
    // Convert the season and episode to zero-padded numbers
    const seasonNumber = parseInt(post.data.season, 10).toString().padStart(2, '0');
    const episodeNumber = parseInt(post.data.episode, 10).toString().padStart(2, '0');

    // Construct the podcast URL
    return `/episodes/s${seasonNumber}/s${seasonNumber}e${episodeNumber}.mp3`;
  });

  return {
    dir: {
      data: "data",
      input: "content",
      includes: "../layouts"
    }
  };
};