import fs from 'node:fs';
import { env } from 'node:process';
import { eleventyImageTransformPlugin } from '@11ty/eleventy-img';
import { feedPlugin } from '@11ty/eleventy-plugin-rss';
import eleventyPluginCiu from '@alexcarpenter/eleventy-plugin-caniuse';
import eleventyPluginEmbedEverything from 'eleventy-plugin-embed-everything';
import eleventyPluginIcons from 'eleventy-plugin-icons';
import eleventyPluginLucideIcons from '@grimlink/eleventy-plugin-lucide-icons';
import eleventyPluginMetagen from 'eleventy-plugin-metagen';
import eleventyPluginNavigation from '@11ty/eleventy-navigation';
import eleventyPluginOgImage from 'eleventy-plugin-og-image';
import eleventyPluginReadingTime from '@myxotod/eleventy-plugin-readingtime';
import eleventyPluginRobotsTxt from 'eleventy-plugin-robotstxt';
import eleventyPluginSyntaxHighlight from '@11ty/eleventy-plugin-syntaxhighlight';
import markdownIt from 'markdown-it';
import markdownItAbbr from 'markdown-it-abbr';
import markdownItAnchor from 'markdown-it-anchor';
import markdownItCallouts from 'markdown-it-obsidian-callouts';
import markdownItCollapsible from 'markdown-it-collapsible';
import markdownItFootnote from 'markdown-it-footnote';

export default async function (eleventyConfig) {
  eleventyConfig.addPassthroughCopy('./src/css/prism.css');
  eleventyConfig.addWatchTarget('./src/css/');

  eleventyConfig.addPassthroughCopy('./src/fonts/');
  eleventyConfig.addWatchTarget('./src/fonts/');

  eleventyConfig.addPassthroughCopy('./src/img/sebin.png');
  eleventyConfig.addWatchTarget('./src/img/sebin.png');

  eleventyConfig.addCollection('posts', (collection) => collection.getFilteredByGlob('./src/posts/*.md'));

  eleventyConfig.addPlugin(eleventyPluginCiu);
  eleventyConfig.addPlugin(eleventyPluginEmbedEverything);
  eleventyConfig.addPlugin(eleventyPluginIcons, {
    sources: [{ name: 'simple', path: 'node_modules/simple-icons/icons' }]
  });
  eleventyConfig.addPlugin(eleventyPluginLucideIcons, { 'aria-hidden': 'true' });
  eleventyConfig.addPlugin(eleventyPluginMetagen);
  eleventyConfig.addPlugin(eleventyPluginNavigation);
  eleventyConfig.addPlugin(eleventyPluginReadingTime);
  eleventyConfig.addPlugin(eleventyPluginRobotsTxt, {
    sitemapURL: 'https://blog.sebin-nyshkim.net/sitemap.xml',
    shouldBlockAIRobots: true,
    rules: new Map([['*', [{ allow: '/' }, { disallow: '/404.html' }, { disallow: '/og-images' }]]])
  });
  eleventyConfig.addPlugin(eleventyPluginSyntaxHighlight);
  eleventyConfig.addPlugin(eleventyPluginOgImage, {
    shortcodeOutput: async (ogImage) => {
      const host = env.ELEVENTY_PRODUCTION ? 'https://blog.sebin-nyshkim.net' : 'http://localhost:8080';
      const src = await ogImage.outputUrl();
      return `<meta property="og:image" content="${host + src}">
      <meta name="twitter:image" content="${host + src}">`;
    },
    satoriOptions: {
      fonts: [
        {
          name: 'Tilt Warp',
          data: fs.readFileSync('./src/fonts/tilt-warp/tilt-warp.ttf'),
          weight: 400,
          style: 'normal'
        }
      ]
    }
  });
  eleventyConfig.addPlugin(eleventyImageTransformPlugin, {
    extensions: 'html',
    formats: ['avif', 'webp', 'auto'],
    sizes: ['1280', '720', '480', 'auto'],
    defaultAttributes: {
      loading: 'lazy',
      decoding: 'async'
    }
  });
  eleventyConfig.addPlugin(feedPlugin, {
    type: 'atom', // or "rss", "json"
    outputPath: '/feed.xml',
    collection: {
      name: 'posts', // iterate over `collections.posts`
      limit: 0 // 0 means no limit
    },
    metadata: {
      language: 'en',
      title: "Sebin's Blog",
      subtitle: 'Writing about stuff I have vague interests in and commenting on stuff I read.',
      base: 'https://blog.sebin-nyshkim.net/',
      author: {
        name: 'Sebin Nyshkim',
        email: '' // Optional
      }
    }
  });

  eleventyConfig.setLibrary('md', markdownIt({ html: true, linkify: true, typographer: true }));

  eleventyConfig.amendLibrary('md', (mdLib) =>
    mdLib
      .use(markdownItAbbr)
      .use(markdownItAnchor)
      .use(markdownItCollapsible)
      .use(markdownItCallouts)
      .use(markdownItFootnote)
  );

  eleventyConfig.addShortcode('year', () => `${new Date().getFullYear()}`);

  eleventyConfig.addFilter('toDateObj', (dateString) => new Date(dateString));
  eleventyConfig.addFilter('isoDate', (dateObj) => dateObj.toISOString());
  eleventyConfig.addFilter('longDate', (dateObj) => dateObj.toString());
  eleventyConfig.addFilter('readableDate', (dateObj) =>
    dateObj.toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' })
  );
}

export const config = {
  dir: {
    input: 'src',
    output: 'public',
    layouts: 'layouts',
    includes: 'includes'
  }
};
