// Expirements - MD to HTML

function toHtml(md, style) {
    var smd = md.split("\n");
    var style_code = style ? `<link rel="stylesheet" href="${style}">` : `<!-- Here can be style code -->`;

    var htmlCode = smd.map(line => {
        line = line
            .replaceAll(/\*\*(.*?)\*\*/g, '<strong>$1</strong>') // Bold
            .replaceAll(/\*(.*?)\*/g, '<em>$1</em>') // Italic
            .replaceAll(/`(.*?)`/g, '<code>$1</code>') // Inline code

        if (line.startsWith('# ')) {
            return `<h1>${line.substring(2)}</h1>\n`;
        }
        if (line.startsWith('## ')) {
            return `<h2>${line.substring(3)}</h2>\n`;
        }
        if (line.startsWith('### ')) {
            return `<h3>${line.substring(4)}</h3>\n`;
        }
        if (line.startsWith('- ')) {
            return `<ul><li>${line.substring(2)}</li></ul>\n`;
        }
        if (line.substring(1).startsWith('. ')) {
            return `<ul style="list-style-type: none;"><li>${line}</li></ul>\n`;
        }
        if (line.startsWith('> ')) {
            return `<blockquote>${line.substring(2)}</blockquote>\n`;
        }
        if (line === "---") {
            return `<hr>\n`;
        }

        return `<p>${line}</p>\n`;
    }).join("");

    return `<!DOCTYPE html>
<html>
    <head>
        <title>${smd[0]}</title>
        ${style_code}
    </head>
    <body>
        <main>
            ${htmlCode}
        </main>
    </body>
</html>`;
}

// USAGE EXAMPLE (not by license)
var fs = require('fs')
fs.writeFileSync("index.html", toHtml(fs.readFileSync("index.md").toString(), "styles/terminal.css"))