/**
 * 小栈AI V5 — Gutenberg 智能写作面板 (7 Tab + 块工具栏✨Popover)
 *
 * Tab: 润色 | 标签 | SEO | 摘要 | 图片 | 内链 | 建议
 * 交互: Suggest → Review → Apply（三步确认模式）
 * 安全: 修改内容前自动备份，支持恢复原文
 *
 * 依赖: wp.plugins, wp.editor, wp.components, wp.data, wp.element,
 *        wp.i18n, wp.blocks, wp.blockEditor, wp.hooks
 */
(function (wp) {
    'use strict';

    var el = wp.element.createElement;
    var useState = wp.element.useState;
    var useEffect = wp.element.useEffect;
    var Fragment = wp.element.Fragment;
    var registerPlugin = wp.plugins.registerPlugin;
    var PluginDocumentSettingPanel = wp.editor.PluginDocumentSettingPanel;
    var useSelect = wp.data.useSelect;
    var useDispatch = wp.data.useDispatch;
    var subscribe = wp.data.subscribe;
    var Button = wp.components.Button;
    var Spinner = wp.components.Spinner;
    var Notice = wp.components.Notice;
    var Modal = wp.components.Modal;
    var TabPanel = wp.components.TabPanel;
    var TextControl = wp.components.TextControl;
    var TextareaControl = wp.components.TextareaControl;
    var CheckboxControl = wp.components.CheckboxControl;
    var RadioControl = wp.components.RadioControl;
    var ToolbarButton = wp.components.ToolbarButton;
    var ToolbarGroup = wp.components.ToolbarGroup;
    var Popover = wp.components.Popover;

    var config = window.xzdEditorAI || {};

    var TOOLS = config.tools || {
        'generate_summary': { label: 'AI摘要', icon: '📄' },
        'generate_tags': { label: 'AI标签', icon: '🏷️' },
        'generate_seo': { label: 'SEO优化', icon: '🔍' },
        'generate_cover': { label: '封面图', icon: '🎨' },
        'generate_alt': { label: 'ALT文字', icon: '🖼️' },
        'build_autolink': { label: '内链构建', icon: '🔗' },
        'polish_content': { label: '内容润色', icon: '✨' },
        'score_quality': { label: '质量评分', icon: '📊' },
    };

    var I18N = config.i18n || {};

    // ═══════════════════════════════
    // 工具函数
    // ═══════════════════════════════

    function callTool(toolId, params) {
        return fetch(config.restUrl + '/chat/execute', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json', 'X-WP-Nonce': config.nonce },
            body: JSON.stringify({ tool_id: toolId, params: Object.assign({ post_id: config.postId }, params || {}) }),
        }).then(function (r) { return r.json(); });
    }

    function extractBlockText(blockProps) {
        if (!blockProps || !blockProps.attributes) return '';
        var attrs = blockProps.attributes;
        var content = attrs.content || attrs.values || '';
        if (Array.isArray(content)) content = content.join('');
        return (content + '').replace(/<[^>]+>/g, '');
    }

    function getContentAttr(blockName) {
        if (blockName === 'core/list') return 'values';
        return 'content';
    }

    function getToolStatus(meta, toolId) {
        var key = '_xzd_ai_processed_' + toolId;
        var raw = meta && meta[key];
        if (!raw) return { processed: false };
        if (typeof raw === 'string') {
            try { var p = JSON.parse(raw); if (p && p.status === 'completed') return { processed: true }; } catch (e) {}
            return { processed: raw.length > 0 };
        }
        if (typeof raw === 'object' && raw.status === 'completed') return { processed: true };
        return { processed: false };
    }

    // ═══════════════════════════════
    // 对比Modal（润色/改写结果预览）
    // ═══════════════════════════════

    function ComparisonModal(props) {
        var _tab = useState('after'); var tab = _tab[0]; var setTab = _tab[1];
        var _loading = useState(false); var appLoading = _loading[0]; var setAppLoading = _loading[1];

        function handleAccept() {
            setAppLoading(true);
            var p = props.onAccept();
            if (p && p.then) { p.finally(function () { setAppLoading(false); }); }
            else { setAppLoading(false); }
        }

        return el(Modal, { title: props.title || '润色对比', onRequestClose: props.onClose, className: 'xzd-editor-compare-modal' },
            el('div', { style: { display: 'flex', gap: 12, marginBottom: 12, fontSize: 12 } },
                el('span', null, '原文 (' + (props.originalLen || 0) + '字)'),
                el('span', { style: { color: '#007cba' } }, '→'),
                el('span', null, '结果 (' + (props.polishedLen || 0) + '字)')
            ),
            el('div', { style: { display: 'flex', gap: 4, marginBottom: 12 } },
                el(Button, { variant: tab === 'before' ? 'primary' : 'secondary', size: 'compact', onClick: function () { setTab('before'); } }, '原文'),
                el(Button, { variant: tab === 'after' ? 'primary' : 'secondary', size: 'compact', onClick: function () { setTab('after'); } }, '结果'),
                el(Button, { variant: tab === 'diff' ? 'primary' : 'secondary', size: 'compact', onClick: function () { setTab('diff'); } }, '对比')
            ),
            el('div', { style: { maxHeight: '50vh', overflowY: 'auto', padding: 12, background: '#f8fafc', borderRadius: 6, fontSize: 12, lineHeight: 1.8 } },
                tab === 'before' ? el('div', null, props.original) :
                tab === 'after' ? el('div', null, props.polished) :
                el('div', null,
                    el('div', { style: { marginBottom: 12, paddingBottom: 12, borderBottom: '1px solid #e5e7eb' } },
                        el('p', { style: { fontSize: 11, color: '#6b7280', marginBottom: 4 } }, '原文:'), el('div', null, props.original)),
                    el('div', null, el('p', { style: { fontSize: 11, color: '#007cba', marginBottom: 4 } }, '结果:'), el('div', null, props.polished))
                )
            ),
            el('div', { style: { display: 'flex', justifyContent: 'flex-end', gap: 8, marginTop: 12 } },
                el(Button, { variant: 'tertiary', onClick: props.onClose }, '取消'),
                el(Button, { variant: 'primary', onClick: handleAccept, disabled: appLoading }, appLoading ? '保存中...' : (props.acceptLabel || '接受修改'))
            )
        );
    }

    // ═══════════════════════════════
    // 已应用横幅
    // ═══════════════════════════════

    function AppliedBanner(props) {
        return el('div', { style: { background: '#ecfdf5', border: '1px solid #86efac', borderRadius: 6, padding: 10, marginBottom: 8 } },
            el('div', { style: { fontSize: 13, fontWeight: 600, color: '#065f46', marginBottom: 4 } }, '✅ ' + (props.title || '') + '已设置'),
            el('p', { style: { margin: 0, fontSize: 11, color: '#6b7280' } }, '自动流水线将跳过此步骤'),
            props.onReset && el(Button, { variant: 'tertiary', size: 'small', onClick: props.onReset, style: { marginTop: 4 } }, '重新设置')
        );
    }

    // ═══════════════════════════════
    // Tab 1: 润色面板
    // ═══════════════════════════════

    function PolishPanel(props) {
        var postId = props.postId;
        var title = useSelect(function (s) { return s('core/editor').getEditedPostAttribute('title') || ''; }, []);
        var content = props.content;
        var editPost = useDispatch('core/editor').editPost;

        var _e = useState(''); var error = _e[0]; var setError = _e[1];
        var _s = useState(''); var status = _s[0]; var setStatus = _s[1];
        var _lv = useState('medium'); var level = _lv[0]; var setLevel = _lv[1];

        // 标题Modal
        var _tl = useState(false); var titleLoading = _tl[0]; var setTitleLoading = _tl[1];
        var _tm = useState(false); var titleModal = _tm[0]; var setTitleModal = _tm[1];
        var _ts = useState([]); var titleSuggestions = _ts[0]; var setTitleSuggestions = _ts[1];
        var _ti = useState(0); var titleIdx = _ti[0]; var setTitleIdx = _ti[1];
        var _cu = useState(''); var customTitle = _cu[0]; var setCustomTitle = _cu[1];

        // 润色Modal
        var _pl = useState(false); var polishLoading = _pl[0]; var setPolishLoading = _pl[1];
        var _pd = useState(null); var polishData = _pd[0]; var setPolishData = _pd[1];

        // 段落操作
        var _st = useState(''); var selText = _st[0]; var setSelText = _st[1];
        var _sa = useState('polish'); var selAction = _sa[0]; var setSelAction = _sa[1];
        var _rl = useState(false); var resizeLoading = _rl[0]; var setResizeLoading = _rl[1];
        var _rd = useState(null); var resizeData = _rd[0]; var setResizeData = _rd[1];

        // 监听选区
        useEffect(function () {
            var unsub = subscribe(function () {
                var sel = null;
                try { sel = window.getSelection(); } catch (e) {}
                var iframe = document.querySelector('iframe[name="editor-canvas"]');
                if ((!sel || !sel.toString().trim()) && iframe && iframe.contentWindow) {
                    try { sel = iframe.contentWindow.getSelection(); } catch (e) {}
                }
                var text = sel ? sel.toString().trim() : '';
                if (text && text.length >= 10 && text !== selText) { setSelText(text); }
                else if (!text && selText) { setSelText(''); }
            });
            return unsub;
        }, [selText]);

        // 标题生成
        function handleTitleGen() {
            setTitleLoading(true); setError('');
            var blocks = wp.data.select('core/block-editor').getBlocks();
            var plain = blocks ? blocks.map(function (b) { return extractBlockText({ attributes: b.attributes }); }).join(' ').trim() : '';

            callTool('expand_title', { post_id: postId, title: title, content: plain, count: 3 })
                .then(function (r) {
                    if (r.success && r.data && r.data.data && r.data.data.suggestions) {
                        setTitleSuggestions(r.data.data.suggestions);
                        setTitleModal(true);
                    } else { setError((r.data && r.data.message) || r.message || '生成失败'); }
                })
                .catch(function () { setError('网络错误'); })
                .finally(function () { setTitleLoading(false); });
        }

        function acceptTitle() {
            var t = customTitle || titleSuggestions[titleIdx] || '';
            if (t) { editPost({ title: t }); }
            setTitleModal(false); setCustomTitle('');
            setStatus('✅ 标题已更新');
        }

        // 全文润色
        function handlePolish() {
            if (!content || content.length < 100) { setError('内容太短（至少100字）'); return; }
            setPolishLoading(true); setError('');
            callTool('polish_content', { post_id: postId, depth: level, _processing_mode: 'overwrite' })
                .then(function (r) {
                    if (r.success && r.data && r.data.success && r.data.data) {
                        setPolishData({
                            original: content.substring(0, 3000),
                            polished: r.data.data.polished || r.data.data.content || '',
                            originalLen: content.length,
                            polishedLen: (r.data.data.polished_len || r.data.data.content ? (r.data.data.polished || r.data.data.content).length : 0),
                        });
                    } else if (r.success) {
                        // links_only 模式直接返回成功，刷新页面
                        setStatus('✅ ' + ((r.data || {}).message || '润色完成，请刷新页面查看'));
                        setTimeout(function () { window.location.reload(); }, 1500);
                    } else { setError((r.data && r.data.message) || r.message || '润色失败'); }
                })
                .catch(function () { setError('网络错误'); })
                .finally(function () { setPolishLoading(false); });
        }

        function acceptPolish() {
            if (!polishData) return Promise.resolve();
            return callTool('polish_content', { post_id: postId, depth: level, _processing_mode: 'overwrite' })
                .then(function () { window.location.reload(); })
                .catch(function () { setError('保存失败'); });
        }

        // 段落改写
        function handleResize() {
            if (!selText || selText.length < 10) { setError('请先在编辑器中划选文本（至少10字）'); return; }
            setResizeLoading(true); setError('');
            callTool('process_text', { content: selText, action: selAction })
                .then(function (r) {
                    if (r.success && r.data && r.data.success && r.data.data) {
                        var result = r.data.data.content.replace(/<[^>]+>/g, '');
                        setResizeData({ original: selText, polished: result, originalLen: selText.length, polishedLen: result.length });
                    } else { setError((r.data && r.data.message) || '改写失败'); }
                })
                .catch(function () { setError('网络错误'); })
                .finally(function () { setResizeLoading(false); });
        }

        function acceptResize() {
            if (!resizeData) return Promise.resolve();
            var block = wp.data.select('core/block-editor').getSelectedBlock();
            if (block) {
                var attrName = getContentAttr(block.name);
                var update = {}; update[attrName] = resizeData.polished;
                wp.data.dispatch('core/block-editor').updateBlockAttributes(block.clientId, update);
            }
            setResizeData(null); setSelText('');
            return Promise.resolve();
        }

        var levelNames = { light: '轻度 - 调整措辞', medium: '标准 - 优化结构', deep: '深度 - 全面重写', links_only: '仅优化内链 - 丝滑融入链接' };

        var modalData = polishData ? {
            title: '润色对比 (' + (levelNames[level] || level) + ')',
            original: polishData.original, polished: polishData.polished,
            originalLen: polishData.originalLen, polishedLen: polishData.polishedLen,
            acceptLabel: '接受并保存', onAccept: acceptPolish, onClose: function () { setPolishData(null); },
        } : (resizeData ? {
            title: '段落改写对比',
            original: resizeData.original, polished: resizeData.polished,
            originalLen: resizeData.originalLen, polishedLen: resizeData.polishedLen,
            acceptLabel: '接受并替换', onAccept: acceptResize, onClose: function () { setResizeData(null); },
        } : null);

        return el('div', { className: 'xzd-panel-section' },
            // 标题
            el('div', { style: { padding: 8, background: '#f9fafb', borderRadius: 6, marginBottom: 12 } },
                el('p', { style: { fontSize: 12, color: '#6b7280', margin: '0 0 6px 0' } }, '文章标题'),
                el(Button, { variant: 'secondary', onClick: handleTitleGen, disabled: titleLoading, style: { width: '100%', justifyContent: 'center' } },
                    titleLoading ? 'AI生成中...' : '🤖 AI 生成标题建议')
            ),

            // 全文润色
            el('p', { style: { fontSize: 12, fontWeight: 600, color: '#334155', margin: '0 0 6px 0' } }, '全文润色'),
            el('select', { value: level, onChange: function (e) { setLevel(e.target.value); },
                style: { width: '100%', marginBottom: 6, padding: '4px 8px', fontSize: 12, borderRadius: 4, border: '1px solid #d1d5db' } },
                el('option', { value: 'light' }, '轻度 - 调整措辞'),
                el('option', { value: 'medium' }, '标准 - 优化结构'),
                el('option', { value: 'deep' }, '深度 - 全面重写'),
                el('option', { value: 'links_only' }, '仅优化内链 - 丝滑融入链接')
            ),
            el(Button, { variant: 'secondary', onClick: handlePolish, disabled: polishLoading,
                style: { width: '100%', justifyContent: 'center', marginBottom: 12 } },
                polishLoading ? 'AI润色中...' : '✨ 执行润色'),

            polishLoading && el('div', { style: { display: 'flex', alignItems: 'center', gap: 6, marginBottom: 8 } },
                el(Spinner, null), el('span', { style: { fontSize: 11, color: '#94a3b8' } }, 'AI正在润色 (30-60秒)...')
            ),

            // 段落改写
            el('hr', { style: { margin: '12px 0', borderTop: '1px solid #e5e7eb' } }),
            el('p', { style: { fontSize: 12, fontWeight: 600, color: '#334155', margin: '0 0 6px 0' } }, '段落改写'),
            el('p', { style: { fontSize: 11, color: '#94a3b8', margin: '0 0 6px 0' } }, '在编辑器中划选文本后选择操作'),

            selText && el('div', { style: { background: '#f0fdf4', borderRadius: 4, padding: 8, marginBottom: 8 } },
                el('p', { style: { fontSize: 11, color: '#166534', margin: '0 0 4px 0' } }, '选中 (' + selText.length + '字)'),
                el('p', { style: { fontSize: 11, color: '#64748b', margin: 0, maxHeight: 50, overflow: 'hidden' } },
                    selText.substring(0, 120) + (selText.length > 120 ? '...' : ''))
            ),

            selText && el('div', { style: { display: 'flex', gap: 4, flexWrap: 'wrap', marginBottom: 8 } },
                ['polish','rewrite','expand','shorten','translate_en','fixGrammar'].map(function (a) {
                    var labels = { polish: '✨润色', rewrite: '🔄改写', expand: '📏扩写', shorten: '✂️缩短', translate_en: '🌐英译', fixGrammar: '✅语法' };
                    return el(Button, { key: a, variant: selAction === a ? 'primary' : 'secondary', size: 'compact',
                        onClick: function () { setSelAction(a); }, style: { fontSize: 11 } }, labels[a]);
                })
            ),

            selText && el(Button, { variant: 'secondary', onClick: handleResize, disabled: resizeLoading,
                style: { width: '100%', justifyContent: 'center' } },
                resizeLoading ? 'AI处理中...' : '执行段落改写'),

            !selText && el('p', { style: { fontSize: 11, color: '#cbd5e1', fontStyle: 'italic' } },
                '划选文中段落后此处自动识别'),

            error && el(Notice, { status: 'error', isDismissible: true, onRemove: function () { setError(''); },
                style: { marginTop: 8, fontSize: 11 } }, error),
            status && !error && el('p', { style: { fontSize: 11, color: '#10b981', marginTop: 8 } }, status),

            // 标题建议Modal
            titleModal && el(Modal, { title: 'AI 标题建议', onRequestClose: function () { setTitleModal(false); setCustomTitle(''); } },
                el('div', { style: { padding: '0 0 16px 0' } },
                    el('p', { style: { fontSize: 13, color: '#64748b', marginBottom: 12 } }, '选择或自定义一个标题：'),
                    titleSuggestions.map(function (s, i) {
                        var active = customTitle === '' && titleIdx === i;
                        return el('div', { key: i, onClick: function () { setTitleIdx(i); setCustomTitle(''); },
                            style: { padding: '10px 12px', marginBottom: 6, borderRadius: 6, cursor: 'pointer',
                                border: active ? '2px solid #2563eb' : '1px solid #e5e7eb',
                                background: active ? '#eff6ff' : '#fff' } },
                            el('p', { style: { fontSize: 13, color: active ? '#1d4ed8' : '#334155', margin: 0, fontWeight: active ? 600 : 400 } }, s)
                        );
                    }),
                    el('div', { style: { marginTop: 10, marginBottom: 12, borderTop: '1px solid #e5e7eb', paddingTop: 10 } },
                        el('p', { style: { fontSize: 12, color: '#6b7280', marginBottom: 4 } }, '或自定义标题：'),
                        el('input', { type: 'text', value: customTitle, placeholder: '输入自定义标题...',
                            onChange: function (e) { setCustomTitle(e.target.value); setTitleIdx(-1); },
                            style: { width: '100%', padding: '8px 10px', fontSize: 13, borderRadius: 4, border: '1px solid #d1d5db' } })
                    ),
                    el('div', { style: { display: 'flex', gap: 8, justifyContent: 'flex-end' } },
                        el(Button, { variant: 'tertiary', onClick: function () { setTitleModal(false); setCustomTitle(''); } }, '取消'),
                        el(Button, { variant: 'primary', onClick: acceptTitle,
                            disabled: !(customTitle || titleSuggestions[titleIdx]) }, '✅ 应用标题')
                    )
                )
            ),

            modalData && el(ComparisonModal, modalData)
        );
    }

    // ═══════════════════════════════
    // Tab 2: 标签面板
    // ═══════════════════════════════

    function TagPanel(props) {
        var postId = props.postId, content = props.content;
        var _s = useState(null); var suggestions = _s[0]; var setSuggestions = _s[1];
        var _l = useState(false); var loading = _l[0]; var setLoading = _l[1];
        var _e = useState(''); var error = _e[0]; var setError = _e[1];
        var _c = useState(null); var checked = _c[0]; var setChecked = _c[1];
        var _a = useState(false); var applied = _a[0]; var setApplied = _a[1];
        var _st = useState(''); var status = _st[0]; var setStatus = _st[1];

        useEffect(function () {
            if (suggestions && !checked) { var init = {}; suggestions.forEach(function (s, i) { init[i] = true; }); setChecked(init); }
        }, [suggestions]);

        function handleSuggest() {
            if (!content || content.length < 50) { setError('内容太短，至少50字'); return; }
            setLoading(true); setError(''); setSuggestions(null); setApplied(false);
            callTool('generate_tags', { post_id: postId, mode: 'hybrid', _preview: true })
                .then(function (r) {
                    if (r.success) { setSuggestions((r.data && r.data.data && r.data.data.tags) || []); }
                    else { setError((r.data && r.data.message) || '分析失败'); }
                })
                ['catch'](function () { setError('网络错误'); })
                ['finally'](function () { setLoading(false); });
        }

        function handleApply() {
            var sel = [];
            if (checked && suggestions) { suggestions.forEach(function (s, i) { if (checked[i]) sel.push(typeof s === 'string' ? s : s.name); }); }
            if (!sel.length) { setError('请至少选一个'); return; }
            setLoading(true); setError('');
            callTool('generate_tags', { post_id: postId, mode: 'hybrid', _tags: sel, _processing_mode: 'overwrite' })
                .then(function (r) {
                    if (r.success) { setApplied(true); setStatus('✅ 已应用 ' + sel.length + ' 个标签'); }
                    else { setError((r.data && r.data.message) || '应用失败'); }
                })
                ['catch'](function () { setError('网络错误'); })
                ['finally'](function () { setLoading(false); });
        }

        if (applied) return el('div', { className: 'xzd-panel-section' },
            el(AppliedBanner, { title: '标签', onReset: function () { setApplied(false); setSuggestions(null); setChecked(null); } }),
            status && el('p', { style: { fontSize: 11, color: '#10b981' } }, status)
        );

        return el('div', { className: 'xzd-panel-section' },
            !suggestions && !loading && el('div', null,
                el('p', { style: { fontSize: 11, color: '#6b7280', marginBottom: 8 } }, 'AI分析文章内容+词库匹配，推荐最合适的标签'),
                el(Button, { variant: 'secondary', onClick: handleSuggest, style: { width: '100%', justifyContent: 'center' } }, '🔍 分析建议标签')
            ),
            loading && el('div', { style: { display: 'flex', alignItems: 'center', gap: 8, padding: '8px 0' } },
                el(Spinner, null), el('span', { style: { fontSize: 12, color: '#757575' } }, ' AI分析中...')
            ),
            error && el(Notice, { status: 'error', isDismissible: true, onRemove: function () { setError(''); }, style: { marginBottom: 8 } }, error),
            suggestions && !loading && !applied && checked && el('div', null,
                el('div', { style: { marginBottom: 8 } },
                    suggestions.map(function (s, i) {
                        var name = typeof s === 'string' ? s : s.name;
                        var isNew = typeof s === 'object' && s.is_new;
                        var source = typeof s === 'object' ? s.source : null;
                        return el('div', { key: i, style: { display: 'flex', alignItems: 'center', gap: 8, padding: '4px 0', borderBottom: '1px solid #f1f5f9' } },
                            el(CheckboxControl, { label: name, checked: !!checked[i],
                                onChange: function () { var n = Object.assign({}, checked); n[i] = !n[i]; setChecked(n); } }),
                            isNew && el('span', { style: { fontSize: 10, background: '#dbeafe', color: '#2563eb', padding: '1px 5px', borderRadius: 3 } }, '新建'),
                            !isNew && el('span', { style: { fontSize: 10, background: '#f0fdf4', color: '#16a34a', padding: '1px 5px', borderRadius: 3 } }, '复用'),
                            source === 'ai' && el('span', { style: { fontSize: 10, background: '#fef3c7', color: '#d97706', padding: '1px 5px', borderRadius: 3 } }, 'AI')
                        );
                    })
                ),
                el(Button, { variant: 'primary', onClick: handleApply, disabled: loading, style: { width: '100%', justifyContent: 'center' } },
                    '✅ 应用选中标签')
            )
        );
    }

    // ═══════════════════════════════
    // Tab 3: SEO面板
    // ═══════════════════════════════

    function SEOPanel(props) {
        var postId = props.postId, content = props.content;
        var _s = useState(null); var seo = _s[0]; var setSeo = _s[1];
        var _l = useState(false); var loading = _l[0]; var setLoading = _l[1];
        var _e = useState(''); var error = _e[0]; var setError = _e[1];
        var _a = useState(false); var applied = _a[0]; var setApplied = _a[1];
        var _st = useState(''); var status = _st[0]; var setStatus = _st[1];
        var _t = useState(''); var et = _t[0]; var setEt = _t[1];
        var _k = useState(''); var ek = _k[0]; var setEk = _k[1];
        var _d = useState(''); var ed = _d[0]; var setEd = _d[1];

        useEffect(function () {
            if (seo) { setEt(seo.title || ''); setEk(seo.keywords || ''); setEd(seo.description || ''); }
        }, [seo]);

        function handleSuggest() {
            if (!content || content.length < 100) { setError('内容太短，至少100字'); return; }
            setLoading(true); setError(''); setSeo(null); setApplied(false);
            callTool('generate_seo', { post_id: postId, _preview: true })
                .then(function (r) {
                    if (r.success) { setSeo((r.data && r.data.data) || {}); }
                    else { setError((r.data && r.data.message) || '生成失败'); }
                })
                ['catch'](function () { setError('网络错误'); })
                ['finally'](function () { setLoading(false); });
        }

        function handleApply() {
            setLoading(true); setError('');
            callTool('generate_seo', { post_id: postId, seo_title: et, seo_keywords: ek, seo_description: ed, _processing_mode: 'overwrite' })
                .then(function (r) {
                    if (r.success) { setApplied(true); setStatus('✅ ' + ((r.data && r.data.message) || 'SEO已应用')); }
                    else { setError((r.data && r.data.message) || '应用失败'); }
                })
                ['catch'](function () { setError('网络错误'); })
                ['finally'](function () { setLoading(false); });
        }

        if (applied) return el('div', { className: 'xzd-panel-section' },
            el(AppliedBanner, { title: 'SEO', onReset: function () { setApplied(false); setSeo(null); } }),
            status && el('p', { style: { fontSize: 11, color: '#10b981' } }, status)
        );

        return el('div', { className: 'xzd-panel-section' },
            !seo && !loading && el('div', null,
                el('p', { style: { fontSize: 11, color: '#6b7280', marginBottom: 8 } }, 'AI生成SEO标题/关键词/描述'),
                el(Button, { variant: 'secondary', onClick: handleSuggest, style: { width: '100%', justifyContent: 'center' } }, '🔍 生成SEO建议')
            ),
            loading && el('div', { style: { display: 'flex', alignItems: 'center', gap: 8, padding: '8px 0' } },
                el(Spinner, null), el('span', { style: { fontSize: 12, color: '#757575' } }, ' 分析中...')
            ),
            error && el(Notice, { status: 'error', isDismissible: true, onRemove: function () { setError(''); }, style: { marginBottom: 8 } }, error),
            seo && !applied && el('div', null,
                el(TextControl, { label: 'SEO标题', value: et, onChange: setEt }),
                et && el('p', { style: { fontSize: 10, color: '#9ca3af', marginTop: -8 } }, '字数: ' + et.length + ' (建议15-25字)'),
                el(TextControl, { label: '关键词', value: ek, onChange: setEk, help: '英文逗号分隔' }),
                el(TextareaControl, { label: '描述', value: ed, onChange: setEd, rows: 3 }),
                ed && el('p', { style: { fontSize: 10, color: '#9ca3af', marginTop: -4 } }, '字数: ' + ed.length + ' (建议120-160字)'),
                el(Button, { variant: 'primary', onClick: handleApply, disabled: loading, style: { width: '100%', justifyContent: 'center' } }, '✅ 应用SEO数据')
            )
        );
    }

    // ═══════════════════════════════
    // Tab 4: 摘要面板
    // ═══════════════════════════════

    function SummaryPanel(props) {
        var postId = props.postId, content = props.content;
        var _s = useState(''); var summary = _s[0]; var setSummary = _s[1];
        var _l = useState(false); var loading = _l[0]; var setLoading = _l[1];
        var _e = useState(''); var error = _e[0]; var setError = _e[1];
        var _a = useState(false); var applied = _a[0]; var setApplied = _a[1];
        var _st = useState(''); var status = _st[0]; var setStatus = _st[1];

        function handleSuggest() {
            if (!content || content.length < 100) { setError('内容太短，至少100字'); return; }
            setLoading(true); setError(''); setApplied(false);
            callTool('generate_summary', { post_id: postId })
                .then(function (r) {
                    if (r.success && r.data && r.data.data) {
                        setSummary(r.data.data.summary || '');
                    } else { setError((r.data && r.data.message) || '生成失败'); }
                })
                ['catch'](function () { setError('网络错误'); })
                ['finally'](function () { setLoading(false); });
        }

        function handleApply() {
            if (!summary) return;
            setLoading(true); setError('');
            callTool('generate_summary', { post_id: postId, _processing_mode: 'overwrite' })
                .then(function (r) {
                    if (r.success) { setApplied(true); setStatus('✅ 摘要已应用'); }
                    else { setError((r.data && r.data.message) || '应用失败'); }
                })
                ['catch'](function () { setError('网络错误'); })
                ['finally'](function () { setLoading(false); });
        }

        if (applied) return el('div', { className: 'xzd-panel-section' },
            el(AppliedBanner, { title: '摘要', onReset: function () { setApplied(false); setSummary(''); } }),
            status && el('p', { style: { fontSize: 11, color: '#10b981' } }, status)
        );

        return el('div', { className: 'xzd-panel-section' },
            !summary && !loading && el('div', null,
                el('p', { style: { fontSize: 11, color: '#6b7280', marginBottom: 8 } }, 'AI生成文章一句话摘要'),
                el(Button, { variant: 'secondary', onClick: handleSuggest, style: { width: '100%', justifyContent: 'center' } }, '🔍 生成AI摘要')
            ),
            loading && el('div', { style: { display: 'flex', alignItems: 'center', gap: 8, padding: '8px 0' } },
                el(Spinner, null), el('span', { style: { fontSize: 12, color: '#757575' } }, ' 分析中...')
            ),
            error && el(Notice, { status: 'error', isDismissible: true, onRemove: function () { setError(''); } }, error),
            summary && !applied && el('div', null,
                el('p', { style: { fontSize: 11, color: '#334155', marginBottom: 4 } }, '摘要 (' + summary.length + '字)'),
                el(TextareaControl, { value: summary, onChange: setSummary, rows: 4 }),
                el(Button, { variant: 'primary', onClick: handleApply, disabled: loading, style: { width: '100%', justifyContent: 'center', marginTop: 8 } }, '✅ 应用摘要')
            )
        );
    }

    // ═══════════════════════════════
    // Tab 5: 图片面板
    // ═══════════════════════════════

    function ImagePanel(props) {
        var postId = props.postId, content = props.content;
        var meta = useSelect(function (s) { return s('core/editor').getEditedPostAttribute('meta') || {}; }, []);

        // 封面图
        var _cl = useState(false); var coverLoading = _cl[0]; var setCoverLoading = _cl[1];
        var _ce = useState(''); var coverError = _ce[0]; var setCoverError = _ce[1];
        var _cs = useState(''); var coverStatus = _cs[0]; var setCoverStatus = _cs[1];
        var _ca = useState(false); var coverApplied = _ca[0]; var setCoverApplied = _ca[1];

        // 配图
        var _ip = useState(''); var inlinePrompt = _ip[0]; var setInlinePrompt = _ip[1];
        var _il = useState(false); var inlineLoading = _il[0]; var setInlineLoading = _il[1];
        var _ie = useState(''); var inlineError = _ie[0]; var setInlineError = _ie[1];
        var _is = useState(''); var inlineStatus = _is[0]; var setInlineStatus = _is[1];

        // ALT
        var _al = useState(false); var altLoading = _al[0]; var setAltLoading = _al[1];
        var _ae = useState(''); var altError = _ae[0]; var setAltError = _ae[1];
        var _as = useState(''); var altStatus = _as[0]; var setAltStatus = _as[1];
        var _hb = useState(false); var hasImgBlock = _hb[0]; var setHasImgBlock = _hb[1];

        // 同步标题作为默认提示词
        useEffect(function () {
            var title = wp.data.select('core/editor').getEditedPostAttribute('title') || '';
            if (title && !inlinePrompt) setInlinePrompt(title);
        }, []);

        // 检测选中图片块
        useEffect(function () {
            var unsub = subscribe(function () {
                var block = wp.data.select('core/block-editor').getSelectedBlock();
                if (block && (block.name === 'core/image' || block.name === 'core/cover')) {
                    setHasImgBlock(true);
                } else { setHasImgBlock(false); }
            });
            return unsub;
        }, []);

        function handleCoverGen() {
            if (!content || content.length < 50) { setCoverError('内容太短'); return; }
            setCoverLoading(true); setCoverError(''); setCoverStatus(''); setCoverApplied(false);
            callTool('generate_cover', { post_id: postId, mode: 'full' })
                .then(function (r) {
                    if (r.success) { setCoverApplied(true); setCoverStatus('✅ ' + ((r.data && r.data.message) || '封面图已生成')); }
                    else { setCoverError((r.data && r.data.message) || r.message || '生成失败'); }
                })
                ['catch'](function () { setCoverError('网络错误'); })
                ['finally'](function () { setCoverLoading(false); });
        }

        function handleInlineGen() {
            if (!inlinePrompt) { setInlineError('请输入图片描述'); return; }
            setInlineLoading(true); setInlineError(''); setInlineStatus('');
            callTool('generate_inline_image', { post_id: postId, context_text: inlinePrompt, source: 'stock' })
                .then(function (r) {
                    if (r.success && r.data && r.data.data) {
                        var d = r.data.data;
                        if (d.url) {
                            // 插入到选中图片块或新建图片块
                            var block = wp.data.select('core/block-editor').getSelectedBlock();
                            if (block && (block.name === 'core/image' || block.name === 'core/cover')) {
                                wp.data.dispatch('core/block-editor').updateBlockAttributes(block.clientId, { url: d.url, alt: inlinePrompt });
                            } else {
                                try {
                                    var imgBlock = wp.blocks.createBlock('core/image', { url: d.url, alt: inlinePrompt });
                                    wp.data.dispatch('core/block-editor').insertBlocks(imgBlock);
                                } catch (e) {}
                            }
                            setInlineStatus('✅ 图片已插入');
                        }
                    } else { setInlineError((r.data && r.data.message) || r.message || '生成失败'); }
                })
                ['catch'](function () { setInlineError('网络错误'); })
                ['finally'](function () { setInlineLoading(false); });
        }

        function handleAltGen() {
            var block = wp.data.select('core/block-editor').getSelectedBlock();
            var attachmentId = block ? block.attributes.id : 0;
            var imgUrl = block ? block.attributes.url : '';
            if (!attachmentId && !imgUrl) { setAltError('请选中一个图片块'); return; }
            setAltLoading(true); setAltError(''); setAltStatus('');
            callTool('generate_alt', { post_id: postId, attachment_id: attachmentId, image_url: imgUrl })
                .then(function (r) {
                    if (r.success && r.data && r.data.data) {
                        var alt = r.data.data.alt_text || '';
                        if (block && alt) { wp.data.dispatch('core/block-editor').updateBlockAttributes(block.clientId, { alt: alt }); }
                        setAltStatus('✅ ALT: ' + alt);
                    } else { setAltError((r.data && r.data.message) || '生成失败'); }
                })
                ['catch'](function () { setAltError('网络错误'); })
                ['finally'](function () { setAltLoading(false); });
        }

        return el('div', { className: 'xzd-panel-section' },
            // 封面图
            el('p', { style: { fontSize: 12, fontWeight: 600, color: '#334155', margin: '0 0 6px 0' } }, '封面图'),
            coverApplied ? el('div', null,
                el(AppliedBanner, { title: '封面图', onReset: function () { setCoverApplied(false); setCoverStatus(''); } }),
                coverStatus && el('p', { style: { fontSize: 11, color: '#10b981' } }, coverStatus)
            ) : el('div', { style: { marginBottom: 12 } },
                el('p', { style: { fontSize: 11, color: '#6b7280', marginBottom: 6 } }, '根据文章内容AI生成封面图'),
                el(Button, { variant: 'secondary', onClick: handleCoverGen, disabled: coverLoading, style: { width: '100%', justifyContent: 'center' } },
                    coverLoading ? '生成中 (15-30秒)...' : '🎨 生成封面图')
            ),
            coverLoading && el('div', { style: { display: 'flex', alignItems: 'center', gap: 6, marginBottom: 8 } },
                el(Spinner, null), el('span', { style: { fontSize: 11, color: '#94a3b8' } }, '生成封面图中...')
            ),
            coverError && el(Notice, { status: 'error', isDismissible: true, onRemove: function () { setCoverError(''); }, style: { marginBottom: 8 } }, coverError),

            // 配图
            el('hr', { style: { margin: '12px 0', borderTop: '1px solid #e5e7eb' } }),
            el('p', { style: { fontSize: 12, fontWeight: 600, color: '#334155', margin: '0 0 6px 0' } }, '文章配图'),
            el(TextareaControl, { label: '图片描述', value: inlinePrompt, onChange: setInlinePrompt, rows: 2 }),
            el(Button, { variant: 'secondary', onClick: handleInlineGen, disabled: inlineLoading, style: { width: '100%', justifyContent: 'center', marginBottom: 12 } },
                inlineLoading ? '生成中...' : '🖼️ 生成配图并插入'),
            inlineLoading && el('div', { style: { display: 'flex', alignItems: 'center', gap: 6, marginBottom: 8 } },
                el(Spinner, null), el('span', { style: { fontSize: 11, color: '#94a3b8' } }, '生成中...')
            ),
            inlineError && el(Notice, { status: 'error', isDismissible: true, onRemove: function () { setInlineError(''); }, style: { marginBottom: 8 } }, inlineError),
            inlineStatus && el(Notice, { status: 'success', isDismissible: true, onRemove: function () { setInlineStatus(''); } }, inlineStatus),

            // ALT
            el('hr', { style: { margin: '12px 0', borderTop: '1px solid #e5e7eb' } }),
            el('p', { style: { fontSize: 12, fontWeight: 600, color: '#334155', margin: '0 0 6px 0' } }, '图片ALT文本'),
            hasImgBlock ? el(Button, { variant: 'secondary', onClick: handleAltGen, disabled: altLoading, style: { width: '100%', justifyContent: 'center' } },
                altLoading ? 'AI生成中...' : '🏷️ 生成ALT文本') :
            el('p', { style: { fontSize: 11, color: '#cbd5e1', fontStyle: 'italic' } }, '请先点击选中一个图片块'),
            altLoading && el('div', { style: { display: 'flex', alignItems: 'center', gap: 6, marginTop: 8 } },
                el(Spinner, null), el('span', { style: { fontSize: 11, color: '#94a3b8' } }, '分析图片中...')
            ),
            altError && el(Notice, { status: 'error', isDismissible: true, onRemove: function () { setAltError(''); }, style: { marginTop: 8 } }, altError),
            altStatus && el(Notice, { status: 'success', isDismissible: true, onRemove: function () { setAltStatus(''); }, style: { marginTop: 8 } }, altStatus)
        );
    }

    // ═══════════════════════════════
    // Tab 6: 内链面板（重构版）
    // ═══════════════════════════════

    function AutolinkPanel(props) {
        var postId = props.postId, content = props.content;
        var _l = useState(false); var loading = _l[0]; var setLoading = _l[1];
        var _e = useState(''); var error = _e[0]; var setError = _e[1];
        var _s = useState(''); var status = _s[0]; var setStatus = _s[1];
        var _sr = useState('mixed'); var source = _sr[0]; var setSource = _sr[1];
        var _tc = useState(3); var tagCount = _tc[0]; var setTagCount = _tc[1];
        var _sc = useState(3); var seoCount = _sc[0]; var setSeoCount = _sc[1];
        var _mt = useState(8); var maxTotal = _mt[0]; var setMaxTotal = _mt[1];
        var _mp = useState(1); var maxPer = _mp[0]; var setMaxPer = _mp[1];

        function handleInsert() {
            if (!content || content.length < 100) { setError('内容太短（至少100字）'); return; }
            setLoading(true); setError(''); setStatus('');
            callTool('build_autolink', {
                post_id: postId, source: source,
                tag_count: tagCount, seo_count: seoCount,
                max_total: maxTotal, max_per_word: maxPer,
                _processing_mode: 'overwrite',
                // V3.1.9：传递内链样式配置，确保编辑器路径也使用用户设置的颜色
                link_color: (window.xzdEditorAI && window.xzdEditorAI.autolink && window.xzdEditorAI.autolink.link_color) || '#2F6BFF',
                link_weight: (window.xzdEditorAI && window.xzdEditorAI.autolink && window.xzdEditorAI.autolink.link_weight) || '500',
                text_decoration: (window.xzdEditorAI && window.xzdEditorAI.autolink && window.xzdEditorAI.autolink.text_decoration) || 'underline',
            }).then(function (r) {
                if (r.success) {
                    var d = (r.data && r.data.data) || {};
                    var msg = '文中插入 ' + (d.inserted || 0) + ' 处内链';
                    if (d.appended > 0) msg += '，底部附加 ' + d.appended + ' 个链接';
                    msg += '。' + (d.appended > 0 ? '💡 切换到「润色」Tab选择「仅优化内链」将链接融入文章。' : '');
                    setStatus('✅ ' + msg);
                } else { setError((r.data && r.data.message) || r.message || '插入失败'); }
            })
            ['catch'](function () { setError('网络错误'); })
            ['finally'](function () { setLoading(false); });
        }

        return el('div', { className: 'xzd-panel-section' },
            el('p', { style: { fontSize: 12, fontWeight: 600, color: '#334155', margin: '0 0 8px 0' } }, '🔗 关键词内链'),

            el('p', { style: { fontSize: 11, color: '#6b7280', margin: '0 0 8px 0' } },
                '读取SEO关键词和文章标签，在正文中匹配关键词并插入内链。未匹配的关键词附文末。'),

            // 来源选择
            el('p', { style: { fontSize: 11, color: '#64748b', margin: '0 0 4px 0' } }, '关键词来源:'),
            el('div', { style: { display: 'flex', gap: 4, marginBottom: 10 } },
                el(Button, { variant: source === 'tags' ? 'primary' : 'secondary', size: 'compact',
                    onClick: function () { setSource('tags'); } }, '仅标签'),
                el(Button, { variant: source === 'keywords' ? 'primary' : 'secondary', size: 'compact',
                    onClick: function () { setSource('keywords'); } }, '仅SEO关键词'),
                el(Button, { variant: source === 'mixed' ? 'primary' : 'secondary', size: 'compact',
                    onClick: function () { setSource('mixed'); } }, '混合')
            ),

            // 数量设置
            el('div', { style: { display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 6, marginBottom: 10 } },
                el('div', null,
                    el('label', { style: { fontSize: 10, color: '#64748b' } }, '标签数'),
                    el('input', { type: 'number', value: tagCount, min: 0, max: 10, onChange: function (e) { setTagCount(parseInt(e.target.value) || 0); },
                        style: { width: '100%', padding: '2px 6px', fontSize: 12, borderRadius: 4, border: '1px solid #d1d5db' } })
                ),
                el('div', null,
                    el('label', { style: { fontSize: 10, color: '#64748b' } }, 'SEO词数'),
                    el('input', { type: 'number', value: seoCount, min: 0, max: 10, onChange: function (e) { setSeoCount(parseInt(e.target.value) || 0); },
                        style: { width: '100%', padding: '2px 6px', fontSize: 12, borderRadius: 4, border: '1px solid #d1d5db' } })
                ),
                el('div', null,
                    el('label', { style: { fontSize: 10, color: '#64748b' } }, '总链接上限'),
                    el('input', { type: 'number', value: maxTotal, min: 1, max: 30, onChange: function (e) { setMaxTotal(parseInt(e.target.value) || 8); },
                        style: { width: '100%', padding: '2px 6px', fontSize: 12, borderRadius: 4, border: '1px solid #d1d5db' } })
                ),
                el('div', null,
                    el('label', { style: { fontSize: 10, color: '#64748b' } }, '每词频率'),
                    el('input', { type: 'number', value: maxPer, min: 1, max: 5, onChange: function (e) { setMaxPer(parseInt(e.target.value) || 1); },
                        style: { width: '100%', padding: '2px 6px', fontSize: 12, borderRadius: 4, border: '1px solid #d1d5db' } })
                )
            ),

            el(Button, { variant: 'secondary', onClick: handleInsert, disabled: loading,
                style: { width: '100%', justifyContent: 'center' } },
                loading ? '处理中...' : '🔗 执行内链插入'),

            loading && el('div', { style: { display: 'flex', alignItems: 'center', gap: 6, marginTop: 8 } },
                el(Spinner, null), el('span', { style: { fontSize: 11, color: '#94a3b8' } }, ' 匹配关键词并插入内链...')
            ),

            error && el(Notice, { status: 'error', isDismissible: true, onRemove: function () { setError(''); }, style: { marginTop: 8 } }, error),
            status && el(Notice, { status: 'success', isDismissible: true, onRemove: function () { setStatus(''); }, style: { marginTop: 8 } }, status),

            el('hr', { style: { margin: '12px 0', borderTop: '1px solid #e5e7eb' } }),
            el('p', { style: { fontSize: 10, color: '#9ca3af', lineHeight: 1.4 } },
                '💡 提示：内链插入后，切换到「润色」Tab → 选择「仅优化内链」级别，AI会将底部链接丝滑融入文章段落中。')
        );
    }

    // ═══════════════════════════════
    // Tab 7: 编辑建议面板
    // ═══════════════════════════════

    function EditorialPanel(props) {
        var postId = props.postId, content = props.content;
        var _l = useState(false); var loading = _l[0]; var setLoading = _l[1];
        var _e = useState(''); var error = _e[0]; var setError = _e[1];
        var _n = useState(null); var notes = _n[0]; var setNotes = _n[1];

        var typeLabels = { readability: '可读性', seo: 'SEO', grammar: '语法' };
        var typeColors = { readability: '#3b82f6', seo: '#10b981', grammar: '#f59e0b' };

        function handleAnalyze() {
            if (!content || content.length < 100) { setError('内容太短（至少100字）'); return; }
            setLoading(true); setError(''); setNotes(null);
            callTool('editorial_notes', { post_id: postId })
                .then(function (r) {
                    if (r.success && r.data && r.data.data) { setNotes(r.data.data); }
                    else { setError((r.data && r.data.message) || '分析失败'); }
                })
                ['catch'](function () { setError('网络错误'); })
                ['finally'](function () { setLoading(false); });
        }

        return el('div', { className: 'xzd-panel-section' },
            el('p', { style: { fontSize: 12, fontWeight: 600, color: '#334155', margin: '0 0 6px 0' } }, '📋 AI 编辑建议'),
            el('p', { style: { fontSize: 11, color: '#6b7280', margin: '0 0 8px 0' } },
                '从可读性、SEO、语法三个维度分析文章'),

            !notes && !loading && el(Button, { variant: 'secondary', onClick: handleAnalyze, style: { width: '100%', justifyContent: 'center' } }, '🔍 分析文章'),

            loading && el('div', { style: { display: 'flex', alignItems: 'center', gap: 8, padding: '8px 0' } },
                el(Spinner, null), el('span', { style: { fontSize: 12, color: '#757575' } }, ' AI正在逐段分析...')
            ),
            error && el(Notice, { status: 'error', isDismissible: true, onRemove: function () { setError(''); } }, error),

            notes && el('div', null,
                notes.summary && el('div', { style: { display: 'flex', gap: 6, marginBottom: 10 } },
                    el('span', { style: { fontSize: 10, padding: '2px 8px', borderRadius: 3, background: '#eff6ff', color: typeColors.readability } }, '可读性 ' + (notes.summary.readability || 0)),
                    el('span', { style: { fontSize: 10, padding: '2px 8px', borderRadius: 3, background: '#ecfdf5', color: typeColors.seo } }, 'SEO ' + (notes.summary.seo || 0)),
                    el('span', { style: { fontSize: 10, padding: '2px 8px', borderRadius: 3, background: '#fffbeb', color: typeColors.grammar } }, '语法 ' + (notes.summary.grammar || 0))
                ),
                notes.suggestions && notes.suggestions.map(function (s, i) {
                    return el('div', { key: i, style: { padding: '8px 10px', marginBottom: 6,
                        borderLeft: '3px solid ' + (typeColors[s.type] || '#6b7280'),
                        background: '#f9fafb', borderRadius: '0 4px 4px 0' } },
                        el('div', { style: { display: 'flex', justifyContent: 'space-between', marginBottom: 4 } },
                            el('span', { style: { fontSize: 9, padding: '1px 5px', borderRadius: 2, background: typeColors[s.type] || '#6b7280', color: '#fff' } }, typeLabels[s.type] || s.type),
                            el('span', { style: { fontSize: 9, color: '#9ca3af' } }, '#' + (i + 1))
                        ),
                        s.text && el('p', { style: { fontSize: 10, color: '#6b7280', fontStyle: 'italic', margin: '0 0 2px 0' } }, '"' + s.text.substring(0, 60) + (s.text.length > 60 ? '...' : '') + '"'),
                        el('p', { style: { fontSize: 11, lineHeight: 1.5, margin: 0 } }, s.note)
                    );
                }),
                notes.count && el('p', { style: { fontSize: 10, color: '#9ca3af', marginTop: 6 } }, '共 ' + notes.count + ' 条建议')
            )
        );
    }

    // ═══════════════════════════════
    // 主面板
    // ═══════════════════════════════

    function EditorPanel() {
        var postId = useSelect(function (s) { return s('core/editor').getCurrentPostId(); }, []);
        var postType = useSelect(function (s) { return s('core/editor').getCurrentPostType(); }, []);
        var meta = useSelect(function (s) { return s('core/editor').getEditedPostAttribute('meta') || {}; }, []);

        var _c = useState(''); var content = _c[0]; var setContent = _c[1];
        var _rb = useState(false); var restoreLoading = _rb[0]; var setRestoreLoading = _rb[1];
        var _rm = useState(''); var restoreMsg = _rm[0]; var setRestoreMsg = _rm[1];

        useEffect(function () {
            if (postType !== 'post') return;
            var blocks = wp.data.select('core/block-editor').getBlocks();
            if (blocks) setContent(getText(blocks));
            var unsub = subscribe(function () {
                var b = wp.data.select('core/block-editor').getBlocks();
                if (b) setContent(getText(b));
            });
            return unsub;
        }, [postType]);

        function getText(blocks) {
            var t = '';
            if (!blocks) return '';
            blocks.forEach(function (b) {
                if (b.attributes) {
                    ['content', 'text', 'alt', 'caption'].forEach(function (k) {
                        if (b.attributes[k]) t += ' ' + b.attributes[k];
                    });
                }
                if (b.innerBlocks) t += ' ' + getText(b.innerBlocks);
            });
            return t.replace(/<[^>]*>/g, ' ').replace(/\s+/g, ' ').trim();
        }

        function handleRestore() {
            if (!confirm('确定恢复AI修改前的原文吗？当前内容将被替换。')) return;
            setRestoreLoading(true); setRestoreMsg('');
            callTool('restore_backup', { post_id: postId })
                .then(function (r) {
                    if (r.success) {
                        setRestoreMsg('✅ 原文已恢复，请刷新页面');
                        setTimeout(function () { window.location.reload(); }, 1500);
                    } else {
                        setRestoreMsg('❌ ' + ((r.data && r.data.message) || r.message || '恢复失败'));
                    }
                })
                ['catch'](function () { setRestoreMsg('❌ 网络错误'); })
                ['finally'](function () { setRestoreLoading(false); });
        }

        if (postType !== 'post') return null;

        var tabs = [
            { name: 'polish', title: '润色', className: 'xzd-editor-tab' },
            { name: 'tags', title: '标签', className: 'xzd-editor-tab' },
            { name: 'seo', title: 'SEO', className: 'xzd-editor-tab' },
            { name: 'summary', title: '摘要', className: 'xzd-editor-tab' },
            { name: 'image', title: '图片', className: 'xzd-editor-tab' },
            { name: 'autolink', title: '内链', className: 'xzd-editor-tab' },
            { name: 'editorial', title: '建议', className: 'xzd-editor-tab' },
        ];

        return el(PluginDocumentSettingPanel, {
            name: 'xzd-ai-writing-panel',
            title: '🤖 小栈AI · 智能写作',
            className: 'xzd-ai-gutenberg-panel',
            initialOpen: true,
        },
            el(TabPanel, {
                className: 'xzd-editor-tabs',
                tabs: tabs,
                children: function (tab) {
                    switch (tab.name) {
                        case 'polish': return el(PolishPanel, { postId: postId, content: content });
                        case 'tags': return el(TagPanel, { postId: postId, content: content });
                        case 'seo': return el(SEOPanel, { postId: postId, content: content });
                        case 'summary': return el(SummaryPanel, { postId: postId, content: content });
                        case 'image': return el(ImagePanel, { postId: postId, content: content });
                        case 'autolink': return el(AutolinkPanel, { postId: postId, content: content });
                        case 'editorial': return el(EditorialPanel, { postId: postId, content: content });
                        default: return null;
                    }
                },
            }),

            // ── 状态栏 ──
            el('hr', { style: { margin: '12px 0 8px 0', borderTop: '1px solid #e5e7eb' } }),
            el('div', { style: { display: 'flex', flexWrap: 'wrap', gap: 8, marginBottom: 8 } },
                Object.keys(TOOLS).map(function (toolId) {
                    var isDone = getToolStatus(meta, toolId).processed;
                    return el('span', { key: toolId, title: TOOLS[toolId].label,
                        style: { fontSize: 12, cursor: 'default' } },
                        (isDone ? '🟢' : '⚪') + ' ' + TOOLS[toolId].label);
                })
            ),

            // ── 恢复备份 ──
            el('div', { style: { display: 'flex', alignItems: 'center', gap: 8 } },
                el(Button, { variant: 'link', size: 'compact', onClick: handleRestore, disabled: restoreLoading,
                    style: { fontSize: 11, color: '#ef4444', textDecoration: 'none' } },
                    restoreLoading ? '恢复中...' : '↩ 恢复AI修改前原文'),
                restoreMsg && el('span', { style: { fontSize: 11, color: restoreMsg.indexOf('❌') >= 0 ? '#ef4444' : '#10b981' } }, restoreMsg)
            )
        );
    }

    registerPlugin('xzd-ai-editor-panel', { render: EditorPanel, icon: 'admin-generic' });

    // ═══════════════════════════════
    // 块工具栏 ✨Popover
    // ═══════════════════════════════

    var AI_ACTIONS = [
        { id: 'polish', icon: '✨', label: '润色', desc: '优化表达' },
        { id: 'rewrite', icon: '🔄', label: '改写', desc: '换风格表达' },
        { id: 'expand', icon: '📏', label: '扩写', desc: '增加细节' },
        { id: 'shorten', icon: '✂️', label: '缩短', desc: '精简文字' },
        { id: 'translate_en', icon: '🌐', label: '英译', desc: '翻为英文' },
        { id: 'fixGrammar', icon: '✅', label: '语法', desc: '修正错别字' },
    ];

    function AIPopoverButton(props) {
        var blockProps = props.blockProps;
        var _open = useState(false); var isOpen = _open[0]; var setOpen = _open[1];
        var _loading = useState(false); var isLoading = _loading[0]; var setLoading = _loading[1];

        function handleAction(actionId) {
            var text = extractBlockText(blockProps);
            if (!text.trim()) return;
            setLoading(true);
            callTool('process_text', { content: text, action: actionId })
                .then(function (res) {
                    setLoading(false); setOpen(false);
                    if (res.success && res.data && res.data.success && res.data.data) {
                        var result = res.data.data.content.replace(/<[^>]+>/g, '');
                        var attrName = getContentAttr(blockProps.name);
                        var update = {}; update[attrName] = result;
                        blockProps.setAttributes(update);
                        try {
                            wp.data.dispatch('core/notices').createNotice('success',
                                '✅ ' + (AI_ACTIONS.find(function (a) { return a.id === actionId; }) || {}).label + '完成',
                                { type: 'snackbar', isDismissible: true });
                        } catch (e) {}
                    }
                })
                ['catch'](function () { setLoading(false); });
        }

        return el(Fragment, null,
            el(ToolbarButton, {
                icon: 'superhero', label: 'AI 助手',
                onClick: function () { setOpen(!isOpen); },
                isActive: isOpen, disabled: isLoading,
            }),
            isOpen && el(Popover, { position: 'bottom center', onClose: function () { setOpen(false); }, className: 'xzd-ai-popover' },
                el('div', { style: { padding: 8, minWidth: 200 } },
                    el('div', { style: { fontSize: 11, fontWeight: 600, color: '#64748b', marginBottom: 6, paddingBottom: 4, borderBottom: '1px solid #e2e8f0' } }, '✨ AI 助手'),
                    AI_ACTIONS.map(function (act) {
                        return el(Button, { key: act.id, onClick: function () { handleAction(act.id); }, disabled: isLoading,
                            style: { justifyContent: 'flex-start', width: '100%', padding: '6px 8px', fontSize: 12, height: 'auto' } },
                            el('span', null,
                                el('span', { style: { marginRight: 6 } }, act.icon),
                                el('span', { style: { fontWeight: 500 } }, act.label),
                                el('span', { style: { marginLeft: 4, fontSize: 10, color: '#94a3b8' } }, act.desc)
                            )
                        );
                    }),
                    isLoading && el('div', { style: { display: 'flex', alignItems: 'center', gap: 4, marginTop: 6, paddingTop: 6, borderTop: '1px solid #e2e8f0' } },
                        el(Spinner, null), el('span', { style: { fontSize: 10, color: '#94a3b8' } }, 'AI处理中...')
                    )
                )
            )
        );
    }

    if (wp.hooks && wp.hooks.addFilter) {
        wp.hooks.addFilter('editor.BlockEdit', 'xzd/ai-toolbar-button', function (BlockEdit) {
            return function (props) {
                var textBlocks = ['core/paragraph', 'core/heading', 'core/list', 'core/quote',
                    'zibllblock/biaoti', 'zibllblock/quote', 'zibllblock/alert'];
                if (textBlocks.indexOf(props.name) === -1) return el(BlockEdit, props);
                return el(Fragment, null,
                    el(BlockEdit, Object.assign({}, props, { key: 'edit' })),
                    props.isSelected ? el(wp.blockEditor.BlockControls, { key: 'ai-controls' },
                        el(ToolbarGroup, null, el(AIPopoverButton, { blockProps: props }))
                    ) : null
                );
            };
        });
    }

})(window.wp);
