<?php if (!defined('__TYPECHO_ROOT_DIR__')) exit;
$db = \Typecho\Db::get();

$cid = $this->request->get('cid');
$post = null;
$title = '';
$text = '';
$cover = '';
$excerpt = '';
$keywords = '';
$description = '';
$currentCategory = 0;
$editorType = isset($this->options->miraiEditorType) ? $this->options->miraiEditorType : 'default';
$useEditorMd = Mirai_featureEnabled('editor') && $editorType === 'editormd';
$useVditor = Mirai_featureEnabled('editor') && $editorType === 'vditor';
$editorConfig = [
    'height' => isset($this->options->miraiEditorHeight) ? max(360, intval($this->options->miraiEditorHeight)) : 640,
    'theme' => isset($this->options->miraiEditorTheme) ? $this->options->miraiEditorTheme : 'default',
    'previewTheme' => isset($this->options->miraiEditorPreviewTheme) ? $this->options->miraiEditorPreviewTheme : 'default',
    'editorTheme' => isset($this->options->miraiEditorEditorTheme) ? $this->options->miraiEditorEditorTheme : 'default',
];
$editorUploadUrl = \Widget\Security::alloc()->getTokenUrl(\Typecho\Common::url('/action/upload', $this->options->index));
$cloudTypesJs = json_encode(Mirai_cloudTypesForJs(), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
$cloudSvgBase = json_encode(Mirai_cloudAssetUrl(), JSON_UNESCAPED_SLASHES);

if ($cid) {
    $post = $db->fetchRow($db->select()->from('table.contents')
        ->where('cid = ?', $cid)
        ->where('authorId = ?', $this->user->uid)
        ->where('type = ?', 'post'));

    if ($post) {
        $title = $post['title'];
        $text = $post['text'];

        $cover = $post['cover'] ?? '';

        $prefix = $db->getPrefix();
        $edkTable = $prefix . 'mirai_contents_edk';
        if ($db->fetchRow("SHOW TABLES LIKE '{$edkTable}'")) {
            $edkData = $db->fetchRow($db->select()->from('table.mirai_contents_edk')->where('cid = ?', $cid));
            if ($edkData) {
                $excerpt = $edkData['excerpt'] ?? '';
                $keywords = $edkData['keywords'] ?? '';
                $description = $edkData['description'] ?? '';
            }
        }

        $categoryRel = $db->fetchRow($db->select('table.relationships.mid')->from('table.relationships')
            ->join('table.metas', 'table.relationships.mid = table.metas.mid')
            ->where('table.relationships.cid = ?', $cid)
            ->where('table.metas.type = ?', 'category')
            ->limit(1));
        if ($categoryRel) {
            $currentCategory = $categoryRel['mid'];
        }
    }
}
?>
<div class="user-module module-write">
    <div class="module-header">
        <div class="module-title"><?php echo $post ? '编辑文章' : '发布投稿'; ?></div>
    </div>

<?php if (!empty($message)): ?>
    <div class="alert alert-<?php echo $messageType; ?>"><?php echo $message; ?></div>
<?php endif; ?>

    <form method="post" action="" class="write-form">
        <input type="hidden" name="action" value="write_post">
        <?php if ($post): ?>
            <input type="hidden" name="cid" value="<?php echo $cid; ?>">
        <?php endif; ?>

        <div class="write-layout">
            <div class="write-main">
                <div class="form-group">
                    <input type="text" name="title" placeholder="请输入文章标题（选填）" class="form-control write-title" value="<?php echo htmlspecialchars($title); ?>">
                </div>

                <div class="form-group">
                    <textarea id="user-write-text" name="text" placeholder="在此输入文章内容...（选填）" class="form-control editor-area" rows="15"><?php echo htmlspecialchars($text); ?></textarea>
                </div>

                <div class="form-group">
                    <label class="field-label">文章摘要</label>
                    <textarea name="excerpt" placeholder="输入文章摘要，如不填写将自动截取文章内容" class="form-control" rows="3"><?php echo htmlspecialchars($excerpt); ?></textarea>
                </div>

                <div class="form-group seo-fields">
                    <label class="field-label">文章关键词</label>
                    <input type="text" name="keywords" placeholder="多个关键词用英文逗号分隔" class="form-control" value="<?php echo htmlspecialchars($keywords); ?>">
                </div>

                <div class="form-group seo-fields">
                    <label class="field-label">文章描述</label>
                    <textarea name="description" placeholder="输入文章描述，建议150-200字" class="form-control" rows="2"><?php echo htmlspecialchars($description); ?></textarea>
                </div>
            </div>

            <div class="write-sidebar">
                <div class="sidebar-section">
                    <h4 class="section-title">发布设置</h4>

                    <div class="form-group">
                        <label>选择分类</label>
                        <select name="category" class="form-control">
                            <option value="0">请选择分类...</option>
                            <?php
                            $categories = $db->fetchAll($db->select()->from('table.metas')
                                ->where('type = ?', 'category')
                                ->order('order', \Typecho\Db::SORT_ASC));
                            foreach ($categories as $category) {
                                $selected = ($category['mid'] == $currentCategory) ? 'selected' : '';
                                echo '<option value="' . $category['mid'] . '" ' . $selected . '>' . $category['name'] . '</option>';
                            }
                            ?>
                        </select>
                    </div>

                    <div class="form-group">
                        <label>文章封面</label>
                        <div class="cover-upload-wrapper">
                            <input type="text" name="cover" id="cover-input" placeholder="请输入图片URL或点击上传" class="form-control" value="<?php echo htmlspecialchars($cover); ?>">
                            <input type="hidden" name="cover_cid" id="cover-cid" value="">
                            <input type="file" id="cover-file-input" accept="image/*" style="display: none;">
                            <button type="button" class="btn btn-secondary btn-sm" onclick="document.getElementById('cover-file-input').click()">上传</button>
                        </div>
                        <div class="cover-preview" id="cover-preview" style="<?php echo $cover ? '' : 'display: none;'; ?>">
                            <img id="cover-preview-img" src="<?php echo htmlspecialchars($cover); ?>" alt="封面预览">
                            <button type="button" class="cover-remove" onclick="removeCover()" title="删除封面">
                                <i class="ri-close-line"></i>
                            </button>
                        </div>
                        <div class="cover-upload-progress" id="cover-progress" style="display: none;">
                            <div class="progress-bar">
                                <div class="progress-fill" id="cover-progress-fill"></div>
                            </div>
                            <span class="progress-text">上传中...</span>
                        </div>
                    </div>
                </div>

                <div class="sidebar-section">
                    <div class="form-actions form-actions-row">
                        <button type="submit" name="do" value="draft" class="btn btn-secondary">存为草稿</button>
                        <button type="submit" name="do" value="publish" class="btn btn-primary"><?php echo $post ? '保存并发布' : '立即发布'; ?></button>
                    </div>
                </div>
            </div>
        </div>
    </form>
</div>

<script>
(function () {
    var coverUploadUrl = <?php echo json_encode($editorUploadUrl, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); ?>;
    var coverDeleteUrl = <?php echo json_encode(\Widget\Security::alloc()->getTokenUrl(\Typecho\Common::url('/action/contents-attachment-edit', $this->options->index)), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); ?>;

    window.initCoverUpload = function() {
        var fileInput = document.getElementById('cover-file-input');
        var coverInput = document.getElementById('cover-input');
        var coverCidInput = document.getElementById('cover-cid');
        var preview = document.getElementById('cover-preview');
        var previewImg = document.getElementById('cover-preview-img');
        var progress = document.getElementById('cover-progress');
        var progressFill = document.getElementById('cover-progress-fill');

        if (!fileInput) return;

        fileInput.addEventListener('change', function(e) {
            var file = e.target.files[0];
            if (!file) return;

            if (!file.type.match(/^image\/(jpeg|jpg|png|gif|webp|avif)$/i)) {
                alert('请选择有效的图片文件 (jpg, jpeg, png, gif, webp, avif)');
                return;
            }

            progress.style.display = 'block';
            progressFill.style.width = '10%';

            var url = new URL(coverUploadUrl, window.location.origin);
            var cid = document.querySelector('input[name="cid"]');
            if (cid && cid.value) {
                url.searchParams.append('cid', cid.value);
            }

            var formData = new FormData();
            formData.append('file', file);

            fetch(url.toString(), {
                method: 'POST',
                body: formData
            }).then(function(response) {
                progressFill.style.width = '80%';
                if (response.ok) return response.json();
                throw new Error('上传失败');
            }).then(function(data) {
                progressFill.style.width = '100%';
                setTimeout(function() { progress.style.display = 'none'; }, 500);

                if (data && data[1]) {
                    var attachment = data[1];
                    coverInput.value = attachment.url;
                    if (attachment.cid) coverCidInput.value = attachment.cid;
                    previewImg.src = attachment.url;
                    preview.style.display = 'block';
                } else if (data && data.url) {
                    coverInput.value = data.url;
                    previewImg.src = data.url;
                    preview.style.display = 'block';
                } else {
                    alert('上传失败：返回数据格式错误');
                }
            }).catch(function(error) {
                progress.style.display = 'none';
                alert('上传失败：' + error.message);
            });
        });

        coverInput.addEventListener('input', function() {
            var url = this.value.trim();
            if (url) {
                previewImg.src = url;
                preview.style.display = 'block';
            } else {
                preview.style.display = 'none';
            }
        });
    };

    window.removeCover = function() {
        var coverInput = document.getElementById('cover-input');
        var coverCidInput = document.getElementById('cover-cid');
        var preview = document.getElementById('cover-preview');
        var fileInput = document.getElementById('cover-file-input');

        var cid = coverCidInput ? coverCidInput.value : '';
        if (cid) {
            if (!confirm('确定删除此内容资源吗？此操作将不可逆')) return;
            var formData = new FormData();
            formData.append('do', 'delete');
            formData.append('cid', cid);
            fetch(coverDeleteUrl, { method: 'POST', body: formData }).finally(clearCoverUI);
        } else {
            clearCoverUI();
        }

        function clearCoverUI() {
            if (coverInput) coverInput.value = '';
            if (coverCidInput) coverCidInput.value = '';
            if (preview) preview.style.display = 'none';
            if (fileInput) fileInput.value = '';
        }
    };
})();
</script>

<?php if ($useEditorMd || $useVditor): ?>
<link rel="stylesheet" href="<?php $this->options->themeUrl('assets/editor/editor.css'); ?>">
<script src="<?php $this->options->themeUrl('assets/editor/editor.js'); ?>"></script>
<script>
var miraiCloudTypes = <?php echo $cloudTypesJs; ?>;
var miraiCloudSvgBase = <?php echo $cloudSvgBase; ?>;
</script>
<?php endif; ?>

<?php if ($useEditorMd): ?>
<link rel="stylesheet" href="<?php $this->options->themeUrl('common/lib/editor.md/css/editormd.min.css'); ?>">
<script>
(function () {
    var editorConfig = <?php echo json_encode($editorConfig, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); ?>;
    var uploadUrl = <?php echo json_encode($editorUploadUrl, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); ?>;
    var libPath = <?php echo json_encode(rtrim($this->options->themeUrl, '/') . '/common/lib/editor.md/lib/', JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); ?>;
    var jqueryUrl = <?php echo json_encode(rtrim($this->options->adminUrl, '/') . '/js/jquery.js', JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); ?>;
    var editorScriptUrl = <?php echo json_encode(rtrim($this->options->themeUrl, '/') . '/common/lib/editor.md/editormd.min.js', JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); ?>;

    function loadScript(url, callback) {
        var script = document.createElement('script');
        script.src = url;
        script.onload = callback;
        script.onerror = callback;
        document.head.appendChild(script);
    }

    function ensureDependencies(callback) {
        var hasJquery = !!window.jQuery;
        var hasEditorMd = typeof window.editormd === 'function';

        if (hasJquery && hasEditorMd) {
            callback();
            return;
        }

        var next = function () {
            if (typeof window.editormd === 'function') {
                callback();
                return;
            }
            loadScript(editorScriptUrl, callback);
        };

        if (!hasJquery) {
            loadScript(jqueryUrl, next);
            return;
        }

        next();
    }

    function initMiraiUserWriteEditor() {
        if (typeof window.editormd !== 'function') {
            return;
        }

        var textarea = document.getElementById('user-write-text');
        if (!textarea || textarea.dataset.editorReady === '1') {
            return;
        }

        var editorContainer = document.createElement('div');
        editorContainer.id = 'mirai-user-write-editormd';
        textarea.parentNode.insertBefore(editorContainer, textarea);
        editorContainer.appendChild(textarea);
        textarea.style.display = 'none';
        textarea.dataset.editorReady = '1';

        var currentTheme = document.documentElement.getAttribute('data-theme') || 'light';
        var isDarkMode = currentTheme === 'dark';
        var resolvedTheme = editorConfig.theme || 'default';
        var resolvedPreviewTheme = editorConfig.previewTheme || 'default';
        var resolvedEditorTheme = editorConfig.editorTheme || 'default';

        if (isDarkMode) {
            if (resolvedTheme === 'default') {
                resolvedTheme = 'dark';
            }
            if (resolvedPreviewTheme === 'default') {
                resolvedPreviewTheme = 'dark';
            }
            if (resolvedEditorTheme === 'default') {
                resolvedEditorTheme = 'pastel-on-dark';
            }
        }

        var miraiUserEditor = window.editormd(editorContainer.id, {
            width: '100%',
            height: editorConfig.height || 640,
            path: libPath,
            theme: resolvedTheme,
            previewTheme: resolvedPreviewTheme,
            editorTheme: resolvedEditorTheme,
            markdown: textarea.value || '',
            watch: false,
            lineNumbers: false,
            codeFold: false,
            saveHTMLToTextarea: false,
            searchReplace: false,
            htmlDecode: true,
            taskList: true,
            tocm: false,
            tex: false,
            flowChart: false,
            sequenceDiagram: false,
            autoFocus: false,
            imageUpload: true,
            imageFormats: ['jpg', 'jpeg', 'gif', 'png', 'avif', 'webp'],
            imageUploadURL: uploadUrl,
            syncScrolling: 'single',
            toolbarIcons: function () {
                return [
                    'bold', 'del', 'italic', 'quote', '|',
                    'h1', 'h2', 'h3', '|',
                    'list-ul', 'list-ol', 'hr', '|',
                    'link', 'image', 'code', 'code-block', 'table', '|',
                    'textAlign', 'insertMedia', 'insertShortcode', 'insertCloud', '|',
                    'search', 'watch', 'preview', 'fullscreen', 'help'
                ];
            },
            toolbarIconsClass: {
                textAlign: "fa-align-justify",
                insertMedia: "fa-play-circle-o",
                insertShortcode: "fa-terminal",
                insertCloud: "fa-cloud-download"
            },
            lang: {
                toolbar: {
                    textAlign: "文本对齐",
                    insertMedia: "插入音视频",
                    insertShortcode: "插入短代码",
                    insertCloud: "网盘下载"
                }
            },
            toolbarHandlers: {
                textAlign: function(cm) {
                    MiraiEditor.toggleAlignMenu(MiraiEditor.createCmAdapter(cm), '.editormd-toolbar a[title="文本对齐"]');
                },
                insertMedia: function(cm) {
                    MiraiEditor.toggleMediaMenu(MiraiEditor.createCmAdapter(cm), '.editormd-toolbar a[title="插入音视频"]');
                },
                insertShortcode: function(cm) {
                    MiraiEditor.toggleHideMenu(MiraiEditor.createCmAdapter(cm), '.editormd-toolbar a[title="插入短代码"]');
                },
                insertCloud: function(cm) {
                    MiraiEditor.insertCloudModal(MiraiEditor.createCmAdapter(cm), miraiCloudSvgBase, miraiCloudTypes);
                }
            },
            onchange: function () {
                textarea.value = this.getMarkdown();
            }
        });

        var form = document.querySelector('.write-form');
        if (form) {
            form.addEventListener('submit', function () {
                if (miraiUserEditor && typeof miraiUserEditor.getMarkdown === 'function') {
                    textarea.value = miraiUserEditor.getMarkdown();
                }
            });
        }
    }

    function bootEditor() {
        ensureDependencies(initMiraiUserWriteEditor);
        window.initCoverUpload();
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', bootEditor);
    } else {
        bootEditor();
    }
})();
</script>
<?php endif; ?>

<?php if ($useVditor): ?>
<link rel="stylesheet" href="<?php $this->options->themeUrl('common/lib/vditor/3.11.2/dist/index.min.css'); ?>">
<script>
(function () {
    var editorConfig = <?php echo json_encode($editorConfig, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); ?>;
    var uploadUrl = <?php echo json_encode($editorUploadUrl, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); ?>;
    var vditorBaseUrl = <?php echo json_encode(rtrim($this->options->themeUrl, '/') . '/common/lib/vditor/3.11.2', JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); ?>;
    var vditorScriptUrl = <?php echo json_encode(rtrim($this->options->themeUrl, '/') . '/common/lib/vditor/3.11.2/dist/index.min.js', JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); ?>;

    function loadScript(url, callback) {
        var script = document.createElement('script');
        script.src = url;
        script.onload = callback;
        script.onerror = callback;
        document.head.appendChild(script);
    }

    function ensureVditor(callback) {
        if (typeof window.Vditor === 'function') {
            callback();
            return;
        }
        loadScript(vditorScriptUrl, callback);
    }

    function initMiraiUserVditor() {
        if (typeof window.Vditor !== 'function') return;

        var textarea = document.getElementById('user-write-text');
        if (!textarea || textarea.dataset.editorReady === '1') return;

        var editorContainer = document.createElement('div');
        editorContainer.id = 'mirai-user-write-vditor';
        textarea.parentNode.insertBefore(editorContainer, textarea);
        textarea.style.display = 'none';
        textarea.dataset.editorReady = '1';

        var currentTheme = document.documentElement.getAttribute('data-theme') || 'light';
        var isDarkMode = currentTheme === 'dark';
        var vditorTheme = isDarkMode ? 'dark' : ((editorConfig.theme === 'dark') ? 'dark' : 'classic');
        var contentTheme = isDarkMode ? 'dark' : ((editorConfig.previewTheme === 'dark') ? 'dark' : 'light');

        var miraiUserVditor = new Vditor(editorContainer.id, {
            cdn: vditorBaseUrl,
            height: editorConfig.height || 640,
            mode: 'wysiwyg',
            theme: vditorTheme,
            icon: 'ant',
            lang: 'zh_CN',
            value: textarea.value || '',
            placeholder: '开始撰写内容...',
            cache: { enable: false },
            counter: { enable: true, type: 'text' },
            toolbarConfig: { pin: true },
            customWysiwygToolbar: function() {},
            _lutePath: '',
            resize: { enable: true, position: 'bottom' },
            outline: { enable: false, position: 'left' },
            preview: {
                theme: { current: contentTheme, path: vditorBaseUrl + '/dist/css/content-theme' },
                hljs: { enable: false },
                markdown: { toc: true, mark: true, autoSpace: true, footnotes: true, html: true },
                math: { engine: 'KaTeX' },
                actions: [
                    { key: 'desktop', text: '桌面端' },
                    { key: 'tablet', text: '平板端' },
                    { key: 'mobile', text: '移动端' },
                    { key: 'mp-wechat', text: '微信公众号' },
                    { key: 'zhihu', text: '知乎' }
                ]
            },
            toolbar: [
                'emoji', 'headings', 'bold', 'italic', 'strike', 'link', '|',
                'list', 'ordered-list', 'check', 'outdent', 'indent', '|',
                'quote', 'line', 'code', 'inline-code', 'insert-before', 'insert-after', '|',
                'upload', 'table', '|',
                {
                    name: 'textAlign',
                    tip: '文本对齐',
                    icon: '<svg viewBox="0 0 32 32" width="14" height="14"><path d="M2 6h28v2H2zm0 6h18v2H2zm0 6h28v2H2zm0 6h18v2H2z" fill="currentColor"/></svg>',
                    click: function() { MiraiEditor.toggleAlignMenu(MiraiEditor.createVditorAdapter(miraiUserVditor), '.vditor-toolbar [data-type="textAlign"]'); }
                },
                {
                    name: 'insertMedia',
                    tip: '插入音视频',
                    icon: '<svg viewBox="0 0 32 32" width="14" height="14"><path d="M25.263 15.159l-17.308-14.927c-0.645-0.555-1.591-0.055-1.591 0.841v29.853c0 0.895 0.945 1.395 1.591 0.841l17.308-14.927c0.495-0.427 0.495-1.255 0-1.682z" fill="currentColor"/></svg>',
                    click: function() { MiraiEditor.toggleMediaMenu(MiraiEditor.createVditorAdapter(miraiUserVditor), '.vditor-toolbar [data-type="insertMedia"]'); }
                },
                {
                    name: 'insertShortcode',
                    tip: '插入短代码',
                    icon: '<svg viewBox="0 0 32 32" width="14" height="14"><path d="M14.545 4.364h2.909v23.273h-2.909zM4.364 9.455h2.909v13.091h-2.909zM24.727 9.455h2.909v13.091h-2.909z" fill="currentColor"/></svg>',
                    click: function() { MiraiEditor.toggleHideMenu(MiraiEditor.createVditorAdapter(miraiUserVditor), '.vditor-toolbar [data-type="insertShortcode"]'); }
                },
                {
                    name: 'insertCloud',
                    tip: '网盘下载',
                    icon: '<svg viewBox="0 0 24 24" width="16" height="16"><path d="M19.35 10.04A7.49 7.49 0 0 0 12 4C9.11 4 6.6 5.64 5.35 8.04A5.994 5.994 0 0 0 0 14c0 3.31 2.69 6 6 6h13c2.76 0 5-2.24 5-5 0-2.64-2.05-4.78-4.65-4.96zM17 13l-5 5-5-5h3V9h4v4h3z" fill="currentColor"/></svg>',
                    click: function() { MiraiEditor.insertCloudModal(MiraiEditor.createVditorAdapter(miraiUserVditor), miraiCloudSvgBase, miraiCloudTypes); }
                },
                '|',
                'undo', 'redo', '|',
                'edit-mode', 'both', 'preview', 'fullscreen', '|',
                'outline', 'export', 'help'
            ],
            upload: {
                url: uploadUrl,
                fieldName: 'file',
                max: 10 * 1024 * 1024,
                multiple: false,
                accept: 'image/*, .zip, .rar, .7z, .pdf, .doc, .docx, .xls, .xlsx, .ppt, .pptx',
                linkToImgUrl: <?php echo json_encode(\Typecho\Common::url('/action/mirai_api?api=upload_link_img&token=' . \Widget\Security::alloc()->getToken('api'), $this->options->index), JSON_UNESCAPED_SLASHES); ?>,
                handler: function(files) {
                    if (!files || files.length === 0) return null;
                    for (var i = 0; i < files.length; i++) {
                        uploadFileToTypecho(files[i]);
                    }
                    return null;
                }
            },
            hint: {
                extend: [{
                    key: '@',
                    hint: function(value) {
                        var keyword = value.substring(1);
                        return new Promise(function(resolve) {
                            if (!keyword) {
                                resolve([]);
                                return;
                            }
                            var formData = new FormData();
                            formData.append('_ajax', '1');
                            formData.append('keyword', keyword);
                            fetch(<?php echo json_encode(\Typecho\Common::url('/action/mirai_api?api=search_users', $this->options->index), JSON_UNESCAPED_SLASHES); ?>, {
                                method: 'POST',
                                body: formData
                            })
                            .then(function(r) { return r.json(); })
                            .then(function(data) {
                                if (data && data.success && data.users) {
                                    resolve(data.users.map(function(u) {
                                        return { value: '@' + u.name, html: u.screenName || u.name };
                                    }));
                                } else {
                                    resolve([]);
                                }
                            })
                            .catch(function() { resolve([]); });
                        });
                    }
                }]
            },
            input: function(value) {
                textarea.value = value;
            }
        });

        function uploadFileToTypecho(file) {
            var formData = new FormData();
            formData.append('file', file);
            var url = new URL(uploadUrl, window.location.origin);

            fetch(url.toString(), {
                method: 'POST',
                body: formData
            })
            .then(function(response) { return response.json(); })
            .then(function(data) {
                if (data) {
                    var attachment = data[1] || data;
                    var insertText;
                    if (attachment.isImage) {
                        insertText = '![' + attachment.title + '](' + attachment.url + ')';
                    } else {
                        insertText = '[' + attachment.title + '](' + attachment.url + ')';
                    }
                    miraiUserVditor.insertValue(insertText);
                }
            })
            .catch(function(err) { console.error('Upload failed:', err); });
        }

        var form = document.querySelector('.write-form');
        if (form) {
            form.addEventListener('submit', function () {
                if (miraiUserVditor && typeof miraiUserVditor.getValue === 'function') {
                    textarea.value = miraiUserVditor.getValue();
                }
            });
        }
    }

    function bootVditor() {
        ensureVditor(initMiraiUserVditor);
        window.initCoverUpload();
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', bootVditor);
    } else {
        bootVditor();
    }
})();
</script>
<?php endif; ?>
