<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link rel="stylesheet" href="/assets/packages/highlight/highlight.min.css">
    <script src="/assets/packages/highlight/highlight.min.js"></script>

    <% if (type === "md_render") { %>
        <script src="/assets/packages/marked/marked.min.js"></script>
    <% } %>

    <link rel="stylesheet" href="/assets/css/style.css">
    <title>OpenAPI - Codebin</title>
</head>
<body>

    <%- include("../navbar.ejs") %>

    <div class="container">
        <div class="form form-container" id="content">
            <% if (type !== "md_render") { %>
                <pre class="code"><code <% if (type !== "auto") { %> class="language-<%- type %>" <% } %>><%= content %></code></pre>
            <% } else { %>
                <textarea id="markdown" class="hidden"><%= content %></textarea>
            <% } %>
        </div>
    </div>

    <% if (type !== "md_render") { %>
        <script>hljs.highlightAll();</script>
    <% } else { %>
        <script>
            const renderer = new marked.Renderer();

            renderer.image = function(href, title, text) {
                if (/youtube\.com\/watch\?v=([^\s]+)/.test(href) || /youtu\.be\/([^\s]+)/.test(href)) {
                    const videoId = href.match(/(?:youtube\.com\/(?:[^\/]+\/.+\/|(?:v|e(?:mbed)?)\/|[^#]*[?&]v=|youtu\.be\/)([^\s&]+))/)[1];
                    return `<iframe width="560" height="315" src="https://www.youtube.com/embed/${videoId}" frameborder="0" allowfullscreen></iframe>`;
                } else if (/vimeo\.com\/([^\s]+)/.test(href)) {
                    const videoId = href.match(/vimeo\.com\/([^\s]+)/)[1];
                    return `<iframe src="https://player.vimeo.com/video/${videoId}" width="560" height="315" frameborder="0" allow="autoplay; fullscreen" allowfullscreen></iframe>`;
                } else if (/\.(mp4)$/i.test(href)) return `<video controls><source src="${href}" type="video/mp4">Your browser does not support the video tag.</video>`;
                else if (/\.(mp3)$/i.test(href)) return `<audio controls><source src="${href}" type="audio/mpeg">Your browser does not support the audio tag.</audio>`;

                return marked.Renderer.prototype.image.apply(this, arguments);
            };

            renderer.code = function(code, language) {
                if (language && hljs.getLanguage(language)) return `<pre><code class="hljs ${language}">${hljs.highlight(code, { language }).value}</code></pre>`;
                else return `<pre><code>${code}</code></pre>`;
            };

            renderer.heading = function (text, level) {
                const anchor = text.replace(/\s+/g, '-').toLowerCase();
                return `<h${level} id="${anchor}"><a href="#${anchor}">#</a> ${text}</h${level}>`;
            };

            function extensionTOC(markdown) {
                const codeBlockRegex = /(```.*?```|`[^`]*`)/gs;
                const headingRegex = /^(#+)\s+(.*)$/gm;

                function generateTOC(markdown) {
                    const headings = [];
                    let match;
                    while ((match = headingRegex.exec(markdown)) !== null) {
                        const level = match[1].length;
                        const text = match[2];
                        headings.push({ level, text });
                    }

                    let tocMarkdown = '';
                    headings.forEach(heading => {
                        const indent = ' '.repeat((heading.level - 1) * 2);
                        tocMarkdown += `${indent}- [${heading.text}](#${heading.text.replace(/\s+/g, '-').toLowerCase()})\n`;
                    });

                    return tocMarkdown;
                }

                return markdown.replace(/\[TOC\]/gi, '[TOC]')
                    .replace(/\[TOC\]/g, (match, offset, string) => {
                        const isInCodeBlock = codeBlockRegex.test(string.slice(0, offset));
                        return isInCodeBlock ? generateTOC(markdown) : match;
                    });
            }

            marked.setOptions({ renderer: renderer });

            document.getElementById('content').innerHTML = marked.parse(extensionTOC(document.getElementById('markdown').value));

            hljs.highlightAll();
        </script>
    <% } %>

</body>
</html>