const metalsmith = require('metalsmith');
const collections = require('metalsmith-collections');
const excerpts = require('metalsmith-excerpts');
const layouts = require('metalsmith-layouts');
const markdown = require('metalsmith-markdown');
const marked = require('marked');
const metalsmithDebug = require('metalsmith-debug');
const moment = require('metalsmith-moment');
const syntaxHighlighting = require('metalsmith-prism');

const metadata = require('./data/metadata.json');

const filesToIgnore = [
  '.DS_Store'
];

const mdRenderer = new marked.Renderer();

mdRenderer.image = (href, title, alt) => {
  if (title) {
    return `<figure><img src="${href}" alt="${alt}" title="${title}"><figcaption>${title}</figcaption></figure>`;
  }
  else {
    return `<img src="${href}" alt="${alt}">`;
  }
}
// https://github.com/markedjs/marked/issues/773
mdRenderer.paragraph = (text) => {
  if (text.startsWith('<figure') && text.endsWith('</figure>')) {
    return text;
  }
  else {
    return `<p>${text}</p>`;
  }
}

metalsmith(__dirname)
.metadata(metadata)
.source('./src')
.destination('./build')
.clean(false)
.ignore(filesToIgnore)
.use(markdown({
  renderer: mdRenderer
}))
.use(collections({
  writing: {
    pattern: ['writing/**/*.html'],
    sortBy: 'published',
    reverse: true
  }
}))
.use(syntaxHighlighting())
.use(excerpts())
.use(moment([
  'published',
  'updated'
]))
.use(layouts({
  engine: 'ejs',
  directory: 'layouts',
  default: 'article.ejs',
  pattern: ['**/*.html', '*.html']
}))
.use(metalsmithDebug())
.build(err => {
  if (err) {
    console.log('❌ Build failed:', err)
  }
  else {
    console.log('✅ Build complete.')
  }
});

@@ -1012,16 +1012,238 @@
 %60;%0A  %7D%0A%7D
+%0AmdRenderer.heading = (text, level, raw, slugger) =%3E %7B%0A  const slug = slugger.slug(text);%0A  return %60%0A    %3Ch$%7Blevel%7D id=%22$%7Bslug%7D%22%3E%0A      %3Ca href=%22#$%7Bslug%7D%22 title=%22Permalink to '$%7Btext%7D'%22%3E$%7Btext%7D%3C/a%3E%0A    %3C/h$%7Blevel%7D%3E%0A  %60;%0A%7D;
 %0A%0Ametals

Bring back permalinks for headings (Considered everything on https://amberwilson.co.uk/blog/are-your-anchor-links-accessible/ but went with a simple link inside the heading tag for now, biggest drawback: harder selection of heading text)