const yaml = require("js-yaml");
const fs = require("fs");
const path = require("path");

module.exports = function (eleventyConfig) {
  // Parsear archivos YAML
  eleventyConfig.addDataExtension("yaml,yml", (contents) =>
    yaml.load(contents)
  );

  // Copiar archivos estáticos al build
  // static/logo → _site/logo, static/games → _site/games
  eleventyConfig.addPassthroughCopy({ "static/logo": "logo" });
  eleventyConfig.addPassthroughCopy({ "static/games": "games" });
  eleventyConfig.addPassthroughCopy("downloads");
  eleventyConfig.addPassthroughCopy("src/css");
  eleventyConfig.addPassthroughCopy("src/js");

  // Colección: todos los juegos ordenados por fecha
  eleventyConfig.addCollection("games", function () {
    const gamesDir = path.join(__dirname, "src", "games");
    const files = fs.readdirSync(gamesDir).filter((f) => f.endsWith(".yaml"));
    return files
      .map((f) => {
        const data = yaml.load(
          fs.readFileSync(path.join(gamesDir, f), "utf-8")
        );
        return data;
      })
      .sort((a, b) => new Date(b.release_date) - new Date(a.release_date));
  });

  // Filtro para formatear fechas en español
  eleventyConfig.addFilter("dateFormat", function (dateStr) {
    const d = new Date(dateStr + "T00:00:00");
    return d.toLocaleDateString("ca-ES", {
      year: "numeric",
      month: "long",
      day: "numeric",
    });
  });

  // Filtro Markdown para descripciones
  const markdownIt = require("markdown-it");
  const md = markdownIt({ html: true });
  eleventyConfig.addFilter("markdown", (content) => md.render(content || ""));

  return {
    dir: {
      input: "src",
      includes: "_includes",
      data: "_data",
      output: "_site",
    },
    templateFormats: ["njk", "md"],
    htmlTemplateEngine: "njk",
  };
};
