/**
 * 芋头CMS UEditor 兼容编辑器（稳定版）
 * 目标：
 * 1. 兼容现有 UE.getEditor / UE.ensureSync 调用
 * 2. 确保内容一定通过 textarea[name=content] 提交到数据库
 * 3. 支持图片上传、链接、基础格式化
 */
(function () {
    function escapeHtml(str) {
        return String(str || '')
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#39;');
    }

    function wrapSelection(textarea, before, after) {
        var start = textarea.selectionStart || 0;
        var end = textarea.selectionEnd || 0;
        var value = textarea.value || '';
        var selected = value.substring(start, end);
        var replacement = before + selected + after;
        textarea.value = value.substring(0, start) + replacement + value.substring(end);
        textarea.focus();
        textarea.selectionStart = start + before.length;
        textarea.selectionEnd = start + before.length + selected.length;
        triggerInput(textarea);
    }

    function insertAtCursor(textarea, text) {
        var start = textarea.selectionStart || 0;
        var end = textarea.selectionEnd || 0;
        var value = textarea.value || '';
        textarea.value = value.substring(0, start) + text + value.substring(end);
        textarea.focus();
        textarea.selectionStart = textarea.selectionEnd = start + text.length;
        triggerInput(textarea);
    }

    function triggerInput(el) {
        try {
            var evt = new Event('input', { bubbles: true });
            el.dispatchEvent(evt);
        } catch (e) {}
    }

    function buildPreview(html) {
        return html || '<p style="color:#94a3b8;">暂无内容预览</p>';
    }

    function uploadImage(file, container, callback) {
        if (!file) return;
        if (file.size > 5 * 1024 * 1024) {
            alert('图片不能超过5MB');
            return;
        }
        var formData = new FormData();
        formData.append('file', file);

        var form = container.closest ? container.closest('form') : null;
        if (form) {
            var csrf = form.querySelector('input[name="csrf_token"]');
            if (csrf && csrf.value) formData.append('csrf_token', csrf.value);
        }

        var xhr = new XMLHttpRequest();
        xhr.open('POST', '/admin/main.php?act=upload', true);
        xhr.onreadystatechange = function () {
            if (xhr.readyState !== 4) return;
            if (xhr.status !== 200) {
                alert('上传失败：HTTP ' + xhr.status);
                return;
            }
            try {
                var res = JSON.parse(xhr.responseText);
                if (res.code === 200 && res.data && res.data.url) {
                    callback(res.data.url);
                } else {
                    alert(res.msg || '上传失败');
                }
            } catch (err) {
                alert('上传响应解析失败');
            }
        };
        xhr.send(formData);
    }

    window.UE = {
        editors: {},
        getEditor: function (id) {
            if (window.UE.editors[id]) return window.UE.editors[id];

            var container = document.getElementById(id);
            if (!container) return null;

            var fieldName = container.getAttribute('data-name') || id;
            var initialHtml = container.getAttribute('data-content') || '';

            container.innerHTML = '';
            container.style.cssText = 'border:1px solid #e2e8f0;border-radius:8px;overflow:hidden;background:#fff;';

            var hidden = document.createElement('textarea');
            hidden.name = fieldName;
            hidden.style.display = 'none';
            hidden.value = initialHtml;

            var toolbar = document.createElement('div');
            toolbar.style.cssText = 'display:flex;flex-wrap:wrap;gap:6px;padding:10px;background:#f8fafc;border-bottom:1px solid #e2e8f0;';
            toolbar.innerHTML = '' +
                '<button type="button" data-cmd="bold">加粗</button>' +
                '<button type="button" data-cmd="italic">斜体</button>' +
                '<button type="button" data-cmd="underline">下划线</button>' +
                '<button type="button" data-cmd="h2">H2</button>' +
                '<button type="button" data-cmd="h3">H3</button>' +
                '<button type="button" data-cmd="p">段落</button>' +
                '<button type="button" data-cmd="ul">无序列表</button>' +
                '<button type="button" data-cmd="ol">有序列表</button>' +
                '<button type="button" data-cmd="link">链接</button>' +
                '<button type="button" data-cmd="image">图片</button>' +
                '<button type="button" data-cmd="hr">分割线</button>' +
                '<button type="button" data-cmd="clear">清空格式</button>' +
                '<input type="file" accept="image/*" style="display:none;" />';

            var toolbarButtons = toolbar.querySelectorAll('button');
            for (var i = 0; i < toolbarButtons.length; i++) {
                toolbarButtons[i].style.cssText = 'padding:6px 10px;border:1px solid #dbe2ea;border-radius:6px;background:#fff;cursor:pointer;font-size:12px;';
            }

            var uploader = toolbar.querySelector('input[type="file"]');

            var editor = document.createElement('textarea');
            editor.style.cssText = 'width:100%;min-height:360px;border:0;padding:16px;font-size:14px;line-height:1.8;color:#1e293b;resize:vertical;';
            editor.value = initialHtml;

            var previewTitle = document.createElement('div');
            previewTitle.style.cssText = 'padding:8px 16px;border-top:1px solid #e2e8f0;background:#f8fafc;color:#64748b;font-size:12px;';
            previewTitle.innerHTML = '内容预览';

            var preview = document.createElement('div');
            preview.style.cssText = 'padding:16px;min-height:120px;border-top:1px solid #e2e8f0;line-height:1.8;color:#334155;';
            preview.innerHTML = buildPreview(initialHtml);

            container.appendChild(hidden);
            container.appendChild(toolbar);
            container.appendChild(editor);
            container.appendChild(previewTitle);
            container.appendChild(preview);

            function sync() {
                hidden.value = editor.value;
                preview.innerHTML = buildPreview(editor.value);
            }

            editor.addEventListener('input', sync);
            editor.addEventListener('change', sync);
            sync();

            toolbar.addEventListener('click', function (e) {
                var btn = e.target.closest('button');
                if (!btn) return;
                var cmd = btn.getAttribute('data-cmd');
                if (!cmd) return;

                if (cmd === 'bold') return wrapSelection(editor, '<strong>', '</strong>');
                if (cmd === 'italic') return wrapSelection(editor, '<em>', '</em>');
                if (cmd === 'underline') return wrapSelection(editor, '<u>', '</u>');
                if (cmd === 'h2') return wrapSelection(editor, '<h2>', '</h2>');
                if (cmd === 'h3') return wrapSelection(editor, '<h3>', '</h3>');
                if (cmd === 'p') return wrapSelection(editor, '<p>', '</p>');
                if (cmd === 'ul') return wrapSelection(editor, '<ul>\n<li>', '</li>\n</ul>');
                if (cmd === 'ol') return wrapSelection(editor, '<ol>\n<li>', '</li>\n</ol>');
                if (cmd === 'hr') return insertAtCursor(editor, '\n<hr>\n');
                if (cmd === 'clear') {
                    var start = editor.selectionStart || 0;
                    var end = editor.selectionEnd || 0;
                    var selected = editor.value.substring(start, end);
                    selected = selected.replace(/<[^>]+>/g, '');
                    var value = editor.value;
                    editor.value = value.substring(0, start) + selected + value.substring(end);
                    triggerInput(editor);
                    return;
                }
                if (cmd === 'link') {
                    var url = prompt('请输入链接地址');
                    if (!url) return;
                    var txt = editor.value.substring(editor.selectionStart || 0, editor.selectionEnd || 0) || url;
                    return wrapSelection(editor, '<a href="' + escapeHtml(url) + '">', '</a>');
                }
                if (cmd === 'image') {
                    uploader.click();
                    return;
                }
            });

            uploader.addEventListener('change', function () {
                var file = this.files && this.files[0];
                if (!file) return;
                uploadImage(file, container, function (url) {
                    insertAtCursor(editor, '<p><img src="' + url + '" alt=""></p>');
                    uploader.value = '';
                });
            });

            editor.addEventListener('paste', function (e) {
                var items = e.clipboardData && e.clipboardData.items;
                if (!items) return;
                for (var i = 0; i < items.length; i++) {
                    if (items[i].type && items[i].type.indexOf('image') !== -1) {
                        e.preventDefault();
                        var file = items[i].getAsFile();
                        uploadImage(file, container, function (url) {
                            insertAtCursor(editor, '<p><img src="' + url + '" alt=""></p>');
                        });
                        break;
                    }
                }
            });

            var form = container.closest ? container.closest('form') : null;
            if (form) {
                form.addEventListener('submit', function () { sync(); });
            }

            var api = {
                setContent: function (html) { editor.value = html || ''; sync(); },
                getContent: function () { sync(); return hidden.value; },
                sync: sync,
                ready: function (fn) { if (typeof fn === 'function') fn(); }
            };

            window.UE.editors[id] = api;
            return api;
        },
        ensureSync: function () {
            if (!window.UE.editors) return true;
            for (var key in window.UE.editors) {
                if (window.UE.editors.hasOwnProperty(key) && window.UE.editors[key] && window.UE.editors[key].sync) {
                    window.UE.editors[key].sync();
                }
            }
            return true;
        }
    };

    window.addEventListener('load', function () {
        var nodes = document.querySelectorAll('[data-name]');
        for (var i = 0; i < nodes.length; i++) {
            var id = nodes[i].id || ('ue_' + i);
            if (!nodes[i].id) nodes[i].id = id;
            window.UE.getEditor(id);
        }
    });
})();
