/**
 * DUET ELEVENTY CONFIGURATION
 */
const hydrate = require("@duetds/components/hydrate")
const htmlmin = require("html-minifier")
const UglifyJS = require("uglify-js")

module.exports = function (config) {
  // Enable data deep merge https://www.11ty.dev/docs/data-deep-merge/
  config.setDataDeepMerge(true)

  // Dom diffing doesn't work well with shadow DOM.
  config.setServerOptions({
    domDiff: false,
  })

  // Copy static assets to dist on build.
  // You can add more here if and when needed.
  config.addPassthroughCopy("./src/assets")
  config.addPassthroughCopy("./src/js")
  config.addPassthroughCopy("./src/favicon.ico")
  config.addPassthroughCopy("./src/manifest.json")

  // Add JSMIN filter to Eleventy.
  config.addFilter("jsmin", function (code) {
    if (process.env.ELEVENTY_ENV == "production") {
      let minified = UglifyJS.minify(code)
      if (minified.error) {
        console.log("UglifyJS error: ", minified.error)
        return code
      }
      return minified.code
    } else {
      return code
    }
  })

  // Server side render Duet’s components in production environment.
  config.addTransform("hydrate", async (content, outputPath) => {
    if (process.env.ELEVENTY_ENV == "production") {
      if (outputPath.endsWith(".html")) {
        try {
          const results = await hydrate.renderToString(content, {
            clientHydrateAnnotations: true,
            removeScripts: false,
            removeUnusedStyles: false,
          })
          return results.html
        } catch (error) {
          return error
        }
      }
    }
    return content
  })

  // Minify HTML in production environment.
  config.addTransform("htmlmin", function (content, outputPath) {
    if (process.env.ELEVENTY_ENV == "production") {
      if (outputPath.endsWith(".html")) {
        let minified = htmlmin.minify(content, {
          useShortDoctype: true,
          // Clientside hydration of components won’t work if comments are removed
          removeComments: false,
          collapseWhitespace: false,
        })
        return minified
      }
    }
    return content
  })

  return {
    // If your site lives in a different subdirectory, change this.
    // Leading or trailing slashes are all normalized away, so don’t worry about it.
    // If you don’t have a subdirectory, use "" or "/" (they do the same thing)
    // This is only used for URLs (it does not affect your file structure)
    pathPrefix: "/",
    templateFormats: ["md", "njk", "html"],
    markdownTemplateEngine: "njk",
    htmlTemplateEngine: "njk",
    dataTemplateEngine: false,
    passthroughFileCopy: true,
    dir: {
      input: "src",
      includes: "includes",
      data: "data",
      output: "dist",
    },
  }
}
