const { marked } = require("marked");

module.exports = function mdChunkLoader(source) {
  this.cacheable && this.cacheable();

  const html = marked.parse(source, { breaks: true, gfm: true });

  const lazyHtml = html.replace(/<img /g, '<img loading="lazy" decoding="async" ');

  let rawChunks = lazyHtml.split(/(?=<h1[\s>])/i).filter(c => c.trim());
  if (rawChunks.length <= 1) {
    rawChunks = lazyHtml.split(/(?=<h2[\s>])/i).filter(c => c.trim());
  }

  const headers = [];
  const headerRegex = /<h1[^>]*>(.*?)<\/h1>/gi;
  let m;
  while ((m = headerRegex.exec(lazyHtml)) !== null) {
    headers.push(m[1].replace(/<[^>]+>/g, ""));
  }

  const chunks = rawChunks.map(chunkHtml => {
    const imgCount = (chunkHtml.match(/<img /g) || []).length;
    const textLen = chunkHtml.replace(/<[^>]+>/g, "").length;
    const estimatedHeight = Math.max(300, Math.round(textLen * 0.6 + imgCount * 350));
    return { html: chunkHtml, estimatedHeight };
  });

  return [
    "export var chunks = " + JSON.stringify(chunks) + ";",
    "export var headers = " + JSON.stringify(headers) + ";",
  ].join("\n");
};
