// Vditor Markdown 渲染 + 外部链接处理 + 提交审核按钮
(function() {
    // ====== Vditor 渲染 ======
    var el = document.getElementById('postContent');
    var mdEl = document.getElementById('postMdContent');
    if (el && mdEl) {
        var md = mdEl.value;
        Vditor.preview(el, md, {
            cdn: '/static/vditor',
            theme: { current: 'light', path: '/static/vditor/dist/css/content-theme' },
            hljs: { style: 'github-dark', enable: true },
            after: function() {
                var host = window.location.host;
                var links = el.querySelectorAll('a[href^="http"]');
                for (var i = 0; i < links.length; i++) {
                    var a = links[i];
                    if (a.host && a.host !== host) {
                        a.setAttribute('rel', 'nofollow noopener noreferrer');
                        a.setAttribute('target', '_blank');
                    }
                }
            }
        });
        // shortcode 占位 div 替换为对应卡片 UI
        renderShortcodes(el);
    }

    // ====== 提交审核按钮 ======
    var submitBtn = document.getElementById('submitAuditBtn');
    if (submitBtn) {
        submitBtn.addEventListener('click', function() {
            showConfirm('确认', '确认提交审核？审核通过后将公开发布。').then(function(ok) {
                if (!ok) return;
                fetch('/api/posts/' + submitBtn.dataset.id + '/submit', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-Token': getCSRFToken()
                    }
                })
                .then(function(r) { return r.json(); })
                .then(function(d) {
                    if (d.success) { window.location.reload(); }
                    else { alert(d.message || '提交失败'); }
                })
                .catch(function() { alert('请求失败'); });
            });
        });
    }
})();
