<template>
    <div>
        <div class="uk-modal-header">
            <h3 class="uk-modal-title">{{ $t('Changelog') }}</h3>
        </div>

        <div class="uk-modal-body" uk-overflow-auto v-html="changelog"></div>
    </div>
</template>

<script>
import http from '@yootheme/http';

/* global marked */
export default {
    name: 'Changelog',

    data: () => ({
        changelog: '',
    }),

    created() {
        http('yooessentials/changelog')
            .get()
            .text((text) => {
                this.$asset({
                    js: 'https://cdn.jsdelivr.net/npm/marked@2.0.3/lib/marked.min.js',
                }).then(() => (this.changelog = this.parse(text)));
            });
    },

    methods: {
        parse(markdown) {
            let section;

            const renderer = new marked.Renderer();

            renderer.list = (text) => {
                const list = `<ul class="uk-list uk-list-square">${text}</ul>`;

                if (section) {
                    const type = {
                        'New Features': 'success',
                        'Bug Fixes': 'danger',
                        Changes: 'warning',
                    };

                    return `<h4 class="uk-success">
                            <span class="uk-label uk-label-${type[section]}">${section}</span>
                        </h4>${list}`;
                }

                return list;
            };

            renderer.listitem = (text) => {
                return `<li>${text}</li>`;
            };

            renderer.heading = (text, level) => {
                section = null;

                text = text.replace(/(\(.*?\))/, '<span class="uk-text-muted">$1</span>');

                if (level === 2) {
                    return `<h${level}>${text}</h${level}>`;
                }

                if (level === 3) {
                    section = text;
                }

                return '';
            };

            return marked(markdown, { renderer });
        },
    },
};
</script>
