// 百科模块：完整动态功能 + 三重兜底（错误边界 + 静态初始化 + API失败回退）
// 绝对不白屏：任何环节报错都有保底内容展示

var wikiReact;
try { wikiReact = React; } catch (e) { wikiReact = { createElement: function () { return null; }, useState: function () { return [null, function () {}]; }, useEffect: function () {}, Component: function () {} }; }

var useState = wikiReact.useState;
var useEffect = wikiReact.useEffect;
var Component = wikiReact.Component;

// API 全局兜底
if (typeof API === 'undefined') {
  window.API = {
    get: function () { return Promise.resolve({ success: false, data: [], message: '服务未就绪' }); },
    post: function () { return Promise.resolve({ success: false, data: null, message: '服务未就绪' }); },
  };
}

// ========== 静态兜底数据 ==========
var STATIC_ENTRIES = [
  { id: 1, title: '清明节习俗', category: '文化', view_count: 1280, summary: '清明节是中国传统节日之一，主要习俗包括扫墓祭祖、踏青郊游等。', content: '清明节，又称踏青节、行清节、三月节、祭祖节等，节期在仲春与暮春之交。清明节源自上古时代的祖先信仰与春祭礼俗，兼具自然与人文两大内涵。' },
  { id: 2, title: '云计算入门', category: '科技', view_count: 856, summary: '云计算是通过网络提供计算服务的模式，包括IaaS、PaaS、SaaS等服务形式。', content: '云计算是分布式计算的一种，指的是通过网络"云"将巨大的数据计算处理程序分解成无数个小程序，然后通过多部服务器组成的系统进行处理和分析。' },
  { id: 3, title: '劳动合同法要点', category: '法律', view_count: 2341, summary: '劳动合同法是规范劳动关系的重要法律，涵盖合同订立、履行、解除等方面。', content: '《中华人民共和国劳动合同法》是为了完善劳动合同制度，明确劳动合同双方当事人的权利和义务，保护劳动者的合法权益而制定的法律。' },
];

var WIKI_CATEGORIES = ['全部', '历史', '文化', '科技', '生活', '法律', '其他'];

// ========== 错误边界 ==========
function WikiErrorBoundary(props) {
  Component.call(this, props);
  this.state = { hasError: false, errorMsg: '' };
}
WikiErrorBoundary.prototype = Object.create(Component.prototype);
WikiErrorBoundary.prototype.constructor = WikiErrorBoundary;
WikiErrorBoundary.prototype.componentDidCatch = function (error) {
  try {
    this.setState({ hasError: true, errorMsg: String(error || '').slice(0, 80) });
  } catch (e) {}
};
WikiErrorBoundary.prototype.render = function () {
  if (this.state.hasError) {
    return wikiReact.createElement('div', { style: {
      padding: '40px 16px', textAlign: 'center',
      color: 'var(--text-tertiary, #999)', fontSize: 13,
      background: 'var(--bg-page, #f5f5f5)', minHeight: '100vh',
    }},
      wikiReact.createElement('div', { style: { fontSize: 32, marginBottom: 8 } }, '⚠️'),
      wikiReact.createElement('div', { style: { marginBottom: 4, fontWeight: 500, color: 'var(--text-primary, #333)', fontSize: 14 } }, '页面加载异常'),
      wikiReact.createElement('div', { style: { fontSize: 11, marginBottom: 12 } }, this.state.errorMsg),
      wikiReact.createElement('button', {
        onClick: function () { try { location.reload(); } catch (e) {} },
        style: {
          fontSize: 12, padding: '6px 16px',
          background: 'var(--primary, #1f8a5b)', color: '#fff',
          border: 'none', borderRadius: 14, cursor: 'pointer',
        },
      }, '刷新重试')
    );
  }
  try {
    return this.props.children;
  } catch (e) {
    return null;
  }
};

// ========== 安全获取 useApp ==========
function safeUseApp() {
  try {
    if (typeof useApp === 'function') {
      var app = useApp();
      if (app && typeof app === 'object') return app;
    }
  } catch (e) {}
  return {
    navigate: function () {},
    showToast: function (msg) { try { console.log('[toast]', msg); } catch (_) {} },
    currentUser: null,
    requireLogin: function () { return false; },
    pageParams: {},
    goBack: function () {},
  };
}

// ========== 安全 API 调用 ==========
function safeApiGet(path, onSuccess, onFail) {
  try {
    API.get(path).then(function (res) {
      try {
        if (res && (res.success !== false) && onSuccess) onSuccess(res.data, res);
        else if (onFail) onFail(res);
      } catch (e) { if (onFail) onFail(e); }
    }).catch(function (err) {
      try { if (onFail) onFail(err); } catch (e) {}
    });
  } catch (e) {
    try { if (onFail) onFail(e); } catch (_) {}
  }
}

function safeApiPost(path, body, onSuccess, onFail) {
  try {
    API.post(path, body).then(function (res) {
      try {
        if (res && res.success !== false) { if (onSuccess) onSuccess(res.data, res); }
        else { if (onFail) onFail(res); }
      } catch (e) { if (onFail) onFail(e); }
    }).catch(function (err) {
      try { if (onFail) onFail(err); } catch (e) {}
    });
  } catch (e) {
    try { if (onFail) onFail(e); } catch (_) {}
  }
}

// ========== 通用 Header ==========
function WikiHeader(props) {
  var app = safeUseApp();
  var navigate = app.navigate || function () {};
  var backTo = props.backTo || 'apps';
  return wikiReact.createElement('div', {
    style: {
      flexShrink: 0, display: 'flex', alignItems: 'center',
      height: 48, padding: '0 16px',
      background: 'var(--bg-card, #fff)',
      borderBottom: '1px solid var(--border, #eee)',
      position: 'sticky', top: 0, zIndex: 10,
    },
  },
    wikiReact.createElement('button', {
      onClick: function () {
        try {
          if (props.onBack) { props.onBack(); return; }
          navigate(backTo);
        } catch (e) { try { app.goBack && app.goBack(); } catch (_) {} }
      },
      style: {
        width: 32, height: 32, marginLeft: -8,
        background: 'transparent', border: 'none',
        fontSize: 18, cursor: 'pointer', color: 'var(--text-primary, #333)',
      },
    }, '←'),
    wikiReact.createElement('div', {
      style: { flex: 1, textAlign: 'center', fontSize: 16, fontWeight: 600, color: 'var(--text-primary, #333)' },
    }, props.title),
    props.rightBtn
      ? wikiReact.createElement('button', {
          onClick: function () { try { props.rightBtn.onClick(); } catch (e) {} },
          style: {
            fontSize: 12, padding: '5px 12px',
            background: 'var(--primary, #1f8a5b)', color: '#fff',
            border: 'none', borderRadius: 14, cursor: 'pointer', fontWeight: 500,
          },
        }, props.rightBtn.text)
      : wikiReact.createElement('div', { style: { width: 56 } })
  );
}

// ========== 百科列表页 ==========
function WikiPage() {
  var app = safeUseApp();
  var navigate = app.navigate || function () {};
  var showToast = app.showToast || function (msg) { try { console.log('[toast]', msg); } catch (_) {} };
  var requireLogin = app.requireLogin || function () { showToast('请先登录'); return false; };

  var s0 = useState(STATIC_ENTRIES); var entries = s0[0]; var setEntries = s0[1];
  var s1 = useState('全部'); var category = s1[0]; var setCategory = s1[1];
  var s2 = useState(''); var keyword = s2[0]; var setKeyword = s2[1];
  var s3 = useState(false); var showCreate = s3[0]; var setShowCreate = s3[1];
  var s4 = useState(false); var showAdmin = s4[0]; var setShowAdmin = s4[1];

  function loadEntries() {
    try {
      var url = '/wiki/entries?category=' + (category === '全部' ? 'all' : encodeURIComponent(category));
      if (keyword) url += '&keyword=' + encodeURIComponent(keyword);
      safeApiGet(url,
        function (data) {
          try {
            if (Array.isArray(data) && data.length > 0) {
              setEntries(data);
            }
            // 为空保留静态数据
          } catch (e) {}
        },
        function () {}
      );
    } catch (e) {}
  }

  useEffect(function () {
    loadEntries();
  }, [category]);

  function handleSearch() {
    try { loadEntries(); } catch (e) {}
  }

  function handleCreateClick() {
    try {
      requireLogin(function () { try { setShowCreate(true); } catch (e) {} });
    } catch (e) { try { showToast('请先登录'); } catch (_) {} }
  }

  function handleEntryClick(entry) {
    try { navigate('wiki-entry', { id: entry.id }); }
    catch (e) { try { showToast('功能加载中'); } catch (_) {} }
  }

  function handleAdminClick() {
    try { setShowAdmin(true); } catch (e) {}
  }

  return wikiReact.createElement('div', { style: {
    display: 'flex', flexDirection: 'column',
    height: '100dvh', overflow: 'hidden',
    background: 'var(--bg-page, #f5f5f5)',
  } },
    wikiReact.createElement(WikiHeader, {
      title: '百科',
      backTo: 'apps',
      rightBtn: { text: '创建词条', onClick: handleCreateClick },
    }),

    // 搜索栏
    wikiReact.createElement('div', { style: { padding: '10px 16px', background: 'var(--bg-card, #fff)', borderBottom: '1px solid var(--border, #eee)' } },
      wikiReact.createElement('div', { style: {
        height: 34, borderRadius: 17,
        background: 'var(--bg-page, #f5f5f5)',
        display: 'flex', alignItems: 'center', padding: '0 14px',
        gap: 8,
      }},
        wikiReact.createElement('span', { style: { fontSize: 12, color: 'var(--text-tertiary, #999)' } }, '🔍'),
        wikiReact.createElement('input', {
          type: 'text',
          value: keyword,
          placeholder: '搜索词条...',
          onChange: function (e) { try { setKeyword(e.target.value); } catch (_) {} },
          onKeyDown: function (e) { if (e.key === 'Enter') handleSearch(); },
          style: {
            flex: 1, border: 'none', background: 'transparent',
            fontSize: 12, outline: 'none', color: 'var(--text-primary, #333)',
          },
        })
      )
    ),

    // 分类 Tab
    wikiReact.createElement('div', {
      style: {
        flexShrink: 0,
        display: 'flex', gap: 0, overflowX: 'auto',
        padding: '0 12px',
        background: 'var(--bg-card, #fff)',
        borderBottom: '1px solid var(--border, #eee)',
        WebkitOverflowScrolling: 'touch',
      },
    },
      WIKI_CATEGORIES.map(function (name) {
        var active = category === name;
        return wikiReact.createElement('button', {
          key: name,
          onClick: function () { try { setCategory(name); } catch (e) {} },
          style: {
            flexShrink: 0,
            padding: '10px 12px',
            fontSize: 13,
            color: active ? 'var(--primary, #1f8a5b)' : 'var(--text-secondary, #666)',
            fontWeight: active ? 600 : 400,
            background: 'transparent',
            border: 'none',
            borderBottom: active ? '2px solid var(--primary, #1f8a5b)' : '2px solid transparent',
            cursor: 'pointer',
          },
        }, name);
      })
    ),

    // 词条列表
    wikiReact.createElement('div', {
      style: { flex: 1, minHeight: 0, overflowY: 'auto', padding: '12px 16px' },
    },
      wikiReact.createElement('div', { style: { display: 'flex', flexDirection: 'column', gap: 10 } },
        entries.map(function (entry) {
          return wikiReact.createElement('div', {
            key: entry.id,
            onClick: function () { handleEntryClick(entry); },
            style: {
              padding: 14,
              background: 'var(--bg-card, #fff)',
              borderRadius: 10,
              cursor: 'pointer',
              boxShadow: '0 1px 3px rgba(0,0,0,0.04)',
            },
          },
            wikiReact.createElement('div', { style: { fontSize: 14, fontWeight: 600, marginBottom: 6, color: 'var(--text-primary, #333)' } }, entry.title),
            wikiReact.createElement('div', { style: { fontSize: 12, color: 'var(--text-secondary, #666)', lineHeight: 1.5, marginBottom: 8 } }, entry.summary || (entry.content || '').slice(0, 80)),
            wikiReact.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 8, fontSize: 11, color: 'var(--text-tertiary, #999)' } },
              wikiReact.createElement('span', { style: { padding: '1px 6px', borderRadius: 4, background: 'var(--bg-page, #f5f5f5)' } }, entry.category || '其他'),
              wikiReact.createElement('span', null, '·'),
              wikiReact.createElement('span', null, (entry.view_count || 0) + ' 浏览')
            )
          );
        })
      )
    ),

    // 底部全民编辑提示
    wikiReact.createElement('div', {
      style: {
        flexShrink: 0,
        padding: '10px 16px',
        background: 'var(--primary-light, #e8f7ef)',
        borderTop: '1px solid var(--border, #eee)',
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        fontSize: 12,
      },
    },
      wikiReact.createElement('span', { style: { color: 'var(--primary, #1f8a5b)' } }, '全民编辑，共建知识百科'),
      wikiReact.createElement('button', {
        onClick: handleCreateClick,
        style: {
          fontSize: 12, padding: '4px 10px',
          background: 'var(--primary, #1f8a5b)', color: '#fff',
          border: 'none', borderRadius: 12, cursor: 'pointer',
        },
      }, '我来编辑 →')
    ),

    // 创建词条弹窗
    showCreate && wikiReact.createElement(CreateEntryModal, {
      onClose: function () { try { setShowCreate(false); } catch (e) {} },
      onSuccess: function () {
        try {
          setShowCreate(false);
          showToast('词条已提交，等待审核');
        } catch (e) {}
      },
    }),

    // 管理员审核入口（长按或调试用）
    showAdmin && wikiReact.createElement(AdminWikiModal, {
      onClose: function () { try { setShowAdmin(false); } catch (e) {} },
      onSuccess: function () {
        try {
          setShowAdmin(false);
          loadEntries();
        } catch (e) {}
      },
    })
  );
}

// ========== 创建词条弹窗 ==========
function CreateEntryModal(props) {
  var app = safeUseApp();
  var showToast = app.showToast || function (msg) { try { console.log('[toast]', msg); } catch (_) {} };

  var s0 = useState(''); var title = s0[0]; var setTitle = s0[1];
  var s1 = useState(''); var content = s1[0]; var setContent = s1[1];
  var s2 = useState(''); var summary = s2[0]; var setSummary = s2[1];
  var s3 = useState('科技'); var category = s3[0]; var setCategory = s3[1];
  var s4 = useState(false); var submitting = s4[0]; var setSubmitting = s4[1];

  function handleSubmit() {
    try {
      if (!title.trim()) { showToast('请输入词条标题'); return; }
      if (!content.trim()) { showToast('请输入词条正文'); return; }
      setSubmitting(true);
      safeApiPost('/wiki/entries', {
        title: title,
        content: content,
        summary: summary,
        category: category,
      }, function () {
        try {
          setSubmitting(false);
          if (props.onSuccess) props.onSuccess();
        } catch (e) { setSubmitting(false); }
      }, function (err) {
        try {
          setSubmitting(false);
          showToast(err && err.message ? err.message : '提交失败');
        } catch (e) { setSubmitting(false); }
      });
    } catch (e) {
      try { setSubmitting(false); showToast('提交失败'); } catch (_) {}
    }
  }

  return wikiReact.createElement('div', {
    onClick: function () { try { props.onClose && props.onClose(); } catch (e) {} },
    style: {
      position: 'fixed', inset: 0, zIndex: 1000,
      background: 'rgba(0,0,0,0.5)',
      display: 'flex', alignItems: 'flex-end', justifyContent: 'center',
    },
  },
    wikiReact.createElement('div', {
      onClick: function (e) { try { e.stopPropagation(); } catch (_) {} },
      style: {
        width: '100%', maxWidth: 480, maxHeight: '85vh',
        background: 'var(--bg-card, #fff)',
        borderRadius: '16px 16px 0 0',
        display: 'flex', flexDirection: 'column', overflow: 'hidden',
      },
    },
      wikiReact.createElement('div', {
        style: {
          flexShrink: 0, padding: '14px 16px',
          borderBottom: '1px solid var(--border, #eee)',
          display: 'flex', justifyContent: 'space-between', alignItems: 'center',
        },
      },
        wikiReact.createElement('div', { style: { fontSize: 16, fontWeight: 600 } }, '创建词条'),
        wikiReact.createElement('button', {
          onClick: function () { try { props.onClose && props.onClose(); } catch (e) {} },
          style: { fontSize: 20, color: 'var(--text-tertiary, #999)', background: 'transparent', border: 'none', cursor: 'pointer', padding: 0, lineHeight: 1 },
        }, '×')
      ),
      wikiReact.createElement('div', { style: { flex: 1, overflowY: 'auto', padding: 16 } },
        wikiReact.createElement('div', { style: { marginBottom: 12 } },
          wikiReact.createElement('div', { style: { fontSize: 12, color: 'var(--text-secondary, #666)', marginBottom: 6 } }, '词条标题'),
          wikiReact.createElement('input', {
            type: 'text', value: title,
            onChange: function (e) { try { setTitle(e.target.value); } catch (_) {} },
            placeholder: '请输入词条标题',
            style: {
              width: '100%', padding: '10px 12px',
              border: '1px solid var(--border, #ddd)',
              borderRadius: 8, fontSize: 13, boxSizing: 'border-box', outline: 'none',
            },
          })
        ),
        wikiReact.createElement('div', { style: { marginBottom: 12 } },
          wikiReact.createElement('div', { style: { fontSize: 12, color: 'var(--text-secondary, #666)', marginBottom: 6 } }, '分类'),
          wikiReact.createElement('div', { style: { display: 'flex', flexWrap: 'wrap', gap: 6 } },
            WIKI_CATEGORIES.filter(function (c) { return c !== '全部'; }).map(function (c) {
              var active = category === c;
              return wikiReact.createElement('button', {
                key: c,
                onClick: function () { try { setCategory(c); } catch (e) {} },
                style: {
                  padding: '5px 12px', fontSize: 12,
                  borderRadius: 14, border: 'none', cursor: 'pointer',
                  background: active ? 'var(--primary, #1f8a5b)' : 'var(--bg-page, #f5f5f5)',
                  color: active ? '#fff' : 'var(--text-secondary, #666)',
                },
              }, c);
            })
          )
        ),
        wikiReact.createElement('div', { style: { marginBottom: 12 } },
          wikiReact.createElement('div', { style: { fontSize: 12, color: 'var(--text-secondary, #666)', marginBottom: 6 } }, '摘要（选填）'),
          wikiReact.createElement('input', {
            type: 'text', value: summary,
            onChange: function (e) { try { setSummary(e.target.value); } catch (_) {} },
            placeholder: '一句话概括词条内容',
            style: {
              width: '100%', padding: '10px 12px',
              border: '1px solid var(--border, #ddd)',
              borderRadius: 8, fontSize: 13, boxSizing: 'border-box', outline: 'none',
            },
          })
        ),
        wikiReact.createElement('div', { style: { marginBottom: 12 } },
          wikiReact.createElement('div', { style: { fontSize: 12, color: 'var(--text-secondary, #666)', marginBottom: 6 } }, '正文内容'),
          wikiReact.createElement('textarea', {
            value: content, rows: 10,
            onChange: function (e) { try { setContent(e.target.value); } catch (_) {} },
            placeholder: '详细编写词条内容...',
            style: {
              width: '100%', padding: '10px 12px',
              border: '1px solid var(--border, #ddd)',
              borderRadius: 8, fontSize: 13,
              boxSizing: 'border-box', resize: 'vertical', outline: 'none',
            },
          })
        )
      ),
      wikiReact.createElement('div', {
        style: {
          flexShrink: 0, padding: '12px 16px',
          borderTop: '1px solid var(--border, #eee)',
        },
      },
        wikiReact.createElement('button', {
          onClick: handleSubmit,
          disabled: submitting,
          style: {
            width: '100%', padding: '11px 0',
            background: 'var(--primary, #1f8a5b)', color: '#fff',
            border: 'none', borderRadius: 8, fontSize: 14, fontWeight: 500,
            cursor: submitting ? 'not-allowed' : 'pointer',
            opacity: submitting ? 0.6 : 1,
          },
        }, submitting ? '提交中...' : '提交审核')
      )
    )
  );
}

// ========== 词条详情页 ==========
function WikiEntryPage() {
  var app = safeUseApp();
  var navigate = app.navigate || function () {};
  var showToast = app.showToast || function (msg) { try { console.log('[toast]', msg); } catch (_) {} };
  var requireLogin = app.requireLogin || function () { showToast('请先登录'); return false; };
  var params = app.pageParams || {};
  var eid = params.id;

  var s0 = useState(null); var entry = s0[0]; var setEntry = s0[1];
  var s1 = useState([]); var versions = s1[0]; var setVersions = s1[1];
  var s2 = useState(false); var showEdit = s2[0]; var setShowEdit = s2[1];
  var s3 = useState(false); var showVersions = s3[0]; var setShowVersions = s3[1];

  var fallbackEntry = STATIC_ENTRIES[0] || { title: '词条加载中', content: '', category: '其他', view_count: 0 };

  function loadEntry() {
    if (!eid) return;
    try {
      safeApiGet('/wiki/entries/' + eid,
        function (data) { try { setEntry(data); } catch (e) {} },
        function () { try { setEntry(fallbackEntry); } catch (e) {} }
      );
      safeApiGet('/wiki/entries/' + eid + '/versions',
        function (data) { try { if (Array.isArray(data)) setVersions(data); } catch (e) {} },
        function () {}
      );
    } catch (e) {}
  }

  useEffect(function () {
    loadEntry();
    return function () {};
  }, [eid]);

  function handleEditClick() {
    try {
      requireLogin(function () { try { setShowEdit(true); } catch (e) {} });
    } catch (e) { try { showToast('请先登录'); } catch (_) {} }
  }

  var currentEntry = entry || fallbackEntry;

  return wikiReact.createElement('div', { style: {
    display: 'flex', flexDirection: 'column',
    height: '100dvh', overflow: 'hidden',
    background: 'var(--bg-page, #f5f5f5)',
  } },
    wikiReact.createElement(WikiHeader, {
      title: '词条详情',
      backTo: 'wiki',
      rightBtn: { text: '编辑', onClick: handleEditClick },
    }),

    wikiReact.createElement('div', { style: { flex: 1, padding: 16, overflowY: 'auto' } },
      wikiReact.createElement('div', { style: { padding: 16, background: 'var(--bg-card, #fff)', borderRadius: 10 } },
        wikiReact.createElement('div', { style: { fontSize: 20, fontWeight: 700, marginBottom: 8, color: 'var(--text-primary, #333)' } }, currentEntry.title),
        wikiReact.createElement('div', { style: { fontSize: 11, color: 'var(--text-tertiary, #999)', marginBottom: 16, display: 'flex', gap: 10, flexWrap: 'wrap' } },
          wikiReact.createElement('span', null, currentEntry.category || '其他'),
          wikiReact.createElement('span', null, '·'),
          wikiReact.createElement('span', null, (currentEntry.view_count || 0) + ' 次浏览'),
          currentEntry.updated_at && wikiReact.createElement('span', null, '· 更新于 ' + new Date(currentEntry.updated_at).toLocaleDateString())
        ),
        wikiReact.createElement('div', { style: {
          fontSize: 13, color: 'var(--text-primary, #333)', lineHeight: 1.8,
        }},
          currentEntry.content ? currentEntry.content.split('\n').map(function (line, i) {
            return wikiReact.createElement('div', { key: i, style: { marginBottom: 8 } }, line);
          }) : '暂无内容'
        )
      ),

      // 版本历史入口
      versions.length > 0 && wikiReact.createElement('div', {
        style: {
          marginTop: 12, padding: 14, background: 'var(--bg-card, #fff)', borderRadius: 10,
          cursor: 'pointer',
        },
        onClick: function () { try { setShowVersions(true); } catch (e) {} },
      },
        wikiReact.createElement('div', { style: { display: 'flex', justifyContent: 'space-between', alignItems: 'center' } },
          wikiReact.createElement('div', { style: { fontSize: 13, fontWeight: 500 } }, '版本历史'),
          wikiReact.createElement('div', { style: { fontSize: 12, color: 'var(--text-tertiary, #999)' } }, versions.length + ' 个版本 →')
        )
      )
    ),

    // 编辑弹窗
    showEdit && wikiReact.createElement(EditEntryModal, {
      entryId: eid,
      currentContent: currentEntry.content,
      onClose: function () { try { setShowEdit(false); } catch (e) {} },
      onSuccess: function () {
        try {
          setShowEdit(false);
          showToast('编辑已提交，等待审核');
        } catch (e) {}
      },
    }),

    // 版本历史弹窗
    showVersions && wikiReact.createElement('div', {
      onClick: function () { try { setShowVersions(false); } catch (e) {} },
      style: {
        position: 'fixed', inset: 0, zIndex: 1000,
        background: 'rgba(0,0,0,0.5)',
        display: 'flex', alignItems: 'flex-end', justifyContent: 'center',
      },
    },
      wikiReact.createElement('div', {
        onClick: function (e) { try { e.stopPropagation(); } catch (_) {} },
        style: {
          width: '100%', maxWidth: 480, maxHeight: '70vh',
          background: 'var(--bg-card, #fff)',
          borderRadius: '16px 16px 0 0',
          display: 'flex', flexDirection: 'column', overflow: 'hidden',
        },
      },
        wikiReact.createElement('div', {
          style: {
            flexShrink: 0, padding: '14px 16px',
            borderBottom: '1px solid var(--border, #eee)',
            display: 'flex', justifyContent: 'space-between', alignItems: 'center',
          },
        },
          wikiReact.createElement('div', { style: { fontSize: 16, fontWeight: 600 } }, '版本历史'),
          wikiReact.createElement('button', {
            onClick: function () { try { setShowVersions(false); } catch (e) {} },
            style: { fontSize: 20, color: 'var(--text-tertiary, #999)', background: 'transparent', border: 'none', cursor: 'pointer', padding: 0, lineHeight: 1 },
          }, '×')
        ),
        wikiReact.createElement('div', { style: { flex: 1, overflowY: 'auto', padding: 12 } },
          versions.length === 0
            ? wikiReact.createElement('div', { style: { textAlign: 'center', padding: 40, color: 'var(--text-tertiary, #999)', fontSize: 13 } }, '暂无版本记录')
            : wikiReact.createElement('div', { style: { display: 'flex', flexDirection: 'column', gap: 8 } },
                versions.map(function (v) {
                  var statusText = v.status === 'approved' ? '已通过' : v.status === 'pending' ? '待审核' : '已驳回';
                  var statusColor = v.status === 'approved' ? '#15803d' : v.status === 'pending' ? '#92400e' : '#991b1b';
                  return wikiReact.createElement('div', {
                    key: v.id,
                    style: {
                      padding: 12, background: 'var(--bg-page, #f5f5f5)',
                      borderRadius: 8, fontSize: 12,
                    },
                  },
                    wikiReact.createElement('div', { style: { display: 'flex', justifyContent: 'space-between', marginBottom: 4 } },
                      wikiReact.createElement('span', { style: { fontWeight: 500 } }, 'v' + v.version),
                      wikiReact.createElement('span', { style: { color: statusColor } }, statusText)
                    ),
                    wikiReact.createElement('div', { style: { color: 'var(--text-secondary, #666)', marginBottom: 4 } },
                      v.user_name + ' · ' + (v.change_note || '更新内容')
                    ),
                    wikiReact.createElement('div', { style: { color: 'var(--text-tertiary, #999)', fontSize: 11 } },
                      v.created_at ? new Date(v.created_at).toLocaleString() : ''
                    )
                  );
                })
              )
        )
      )
    )
  );
}

// ========== 编辑词条弹窗 ==========
function EditEntryModal(props) {
  var app = safeUseApp();
  var showToast = app.showToast || function (msg) { try { console.log('[toast]', msg); } catch (_) {} };

  var s0 = useState(props.currentContent || ''); var content = s0[0]; var setContent = s0[1];
  var s1 = useState(''); var changeNote = s1[0]; var setChangeNote = s1[1];
  var s2 = useState(false); var submitting = s2[0]; var setSubmitting = s2[1];

  function handleSubmit() {
    try {
      if (!content.trim()) { showToast('请输入词条正文'); return; }
      setSubmitting(true);
      safeApiPost('/wiki/entries/' + props.entryId + '/edit', {
        content: content,
        change_note: changeNote,
      }, function () {
        try {
          setSubmitting(false);
          if (props.onSuccess) props.onSuccess();
        } catch (e) { setSubmitting(false); }
      }, function (err) {
        try {
          setSubmitting(false);
          showToast(err && err.message ? err.message : '提交失败');
        } catch (e) { setSubmitting(false); }
      });
    } catch (e) {
      try { setSubmitting(false); showToast('提交失败'); } catch (_) {}
    }
  }

  return wikiReact.createElement('div', {
    onClick: function () { try { props.onClose && props.onClose(); } catch (e) {} },
    style: {
      position: 'fixed', inset: 0, zIndex: 1000,
      background: 'rgba(0,0,0,0.5)',
      display: 'flex', alignItems: 'flex-end', justifyContent: 'center',
    },
  },
    wikiReact.createElement('div', {
      onClick: function (e) { try { e.stopPropagation(); } catch (_) {} },
      style: {
        width: '100%', maxWidth: 480, maxHeight: '85vh',
        background: 'var(--bg-card, #fff)',
        borderRadius: '16px 16px 0 0',
        display: 'flex', flexDirection: 'column', overflow: 'hidden',
      },
    },
      wikiReact.createElement('div', {
        style: {
          flexShrink: 0, padding: '14px 16px',
          borderBottom: '1px solid var(--border, #eee)',
          display: 'flex', justifyContent: 'space-between', alignItems: 'center',
        },
      },
        wikiReact.createElement('div', { style: { fontSize: 16, fontWeight: 600 } }, '编辑词条'),
        wikiReact.createElement('button', {
          onClick: function () { try { props.onClose && props.onClose(); } catch (e) {} },
          style: { fontSize: 20, color: 'var(--text-tertiary, #999)', background: 'transparent', border: 'none', cursor: 'pointer', padding: 0, lineHeight: 1 },
        }, '×')
      ),
      wikiReact.createElement('div', { style: { flex: 1, overflowY: 'auto', padding: 16 } },
        wikiReact.createElement('div', { style: { marginBottom: 12 } },
          wikiReact.createElement('div', { style: { fontSize: 12, color: 'var(--text-secondary, #666)', marginBottom: 6 } }, '修改说明'),
          wikiReact.createElement('input', {
            type: 'text', value: changeNote,
            onChange: function (e) { try { setChangeNote(e.target.value); } catch (_) {} },
            placeholder: '简要说明修改内容',
            style: {
              width: '100%', padding: '10px 12px',
              border: '1px solid var(--border, #ddd)',
              borderRadius: 8, fontSize: 13, boxSizing: 'border-box', outline: 'none',
            },
          })
        ),
        wikiReact.createElement('div', { style: { marginBottom: 12 } },
          wikiReact.createElement('div', { style: { fontSize: 12, color: 'var(--text-secondary, #666)', marginBottom: 6 } }, '正文内容'),
          wikiReact.createElement('textarea', {
            value: content, rows: 15,
            onChange: function (e) { try { setContent(e.target.value); } catch (_) {} },
            style: {
              width: '100%', padding: '10px 12px',
              border: '1px solid var(--border, #ddd)',
              borderRadius: 8, fontSize: 13,
              boxSizing: 'border-box', resize: 'vertical', outline: 'none',
            },
          })
        )
      ),
      wikiReact.createElement('div', {
        style: {
          flexShrink: 0, padding: '12px 16px',
          borderTop: '1px solid var(--border, #eee)',
        },
      },
        wikiReact.createElement('button', {
          onClick: handleSubmit,
          disabled: submitting,
          style: {
            width: '100%', padding: '11px 0',
            background: 'var(--primary, #1f8a5b)', color: '#fff',
            border: 'none', borderRadius: 8, fontSize: 14, fontWeight: 500,
            cursor: submitting ? 'not-allowed' : 'pointer',
            opacity: submitting ? 0.6 : 1,
          },
        }, submitting ? '提交中...' : '提交审核')
      )
    )
  );
}

// ========== 管理员审核弹窗 ==========
function AdminWikiModal(props) {
  var app = safeUseApp();
  var showToast = app.showToast || function (msg) { try { console.log('[toast]', msg); } catch (_) {} };

  var s0 = useState([]); var pending = s0[0]; var setPending = s0[1];
  var s1 = useState(false); var loading = s1[0]; var setLoading = s1[1];

  function loadPending() {
    try {
      setLoading(true);
      safeApiGet('/wiki/pending',
        function (data) {
          try {
            if (Array.isArray(data)) setPending(data);
            setLoading(false);
          } catch (e) { setLoading(false); }
        },
        function () { setLoading(false); }
      );
    } catch (e) { setLoading(false); }
  }

  useEffect(function () {
    loadPending();
  }, []);

  function handleApprove(versionId) {
    try {
      safeApiPost('/wiki/versions/' + versionId + '/approve', {},
        function () {
          try {
            showToast('已通过');
            loadPending();
          } catch (e) {}
        },
        function (err) { try { showToast(err && err.message ? err.message : '操作失败'); } catch (_) {} }
      );
    } catch (e) {}
  }

  function handleReject(versionId) {
    try {
      safeApiPost('/wiki/versions/' + versionId + '/reject', { reason: '内容不符合规范' },
        function () {
          try {
            showToast('已驳回');
            loadPending();
          } catch (e) {}
        },
        function (err) { try { showToast(err && err.message ? err.message : '操作失败'); } catch (_) {} }
      );
    } catch (e) {}
  }

  return wikiReact.createElement('div', {
    onClick: function () { try { props.onClose && props.onClose(); } catch (e) {} },
    style: {
      position: 'fixed', inset: 0, zIndex: 1000,
      background: 'rgba(0,0,0,0.5)',
      display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20,
    },
  },
    wikiReact.createElement('div', {
      onClick: function (e) { try { e.stopPropagation(); } catch (_) {} },
      style: {
        width: '100%', maxWidth: 400, maxHeight: '80vh',
        background: 'var(--bg-card, #fff)',
        borderRadius: 16,
        display: 'flex', flexDirection: 'column', overflow: 'hidden',
      },
    },
      wikiReact.createElement('div', {
        style: {
          flexShrink: 0, padding: '14px 16px',
          borderBottom: '1px solid var(--border, #eee)',
          display: 'flex', justifyContent: 'space-between', alignItems: 'center',
        },
      },
        wikiReact.createElement('div', { style: { fontSize: 16, fontWeight: 600 } }, '待审核词条'),
        wikiReact.createElement('button', {
          onClick: function () { try { props.onClose && props.onClose(); } catch (e) {} },
          style: { fontSize: 20, color: 'var(--text-tertiary, #999)', background: 'transparent', border: 'none', cursor: 'pointer', padding: 0, lineHeight: 1 },
        }, '×')
      ),
      wikiReact.createElement('div', { style: { flex: 1, overflowY: 'auto', padding: 12 } },
        loading
          ? wikiReact.createElement('div', { style: { textAlign: 'center', padding: 40, color: 'var(--text-tertiary, #999)', fontSize: 13 } }, '加载中...')
          : pending.length === 0
            ? wikiReact.createElement('div', { style: { textAlign: 'center', padding: 40, color: 'var(--text-tertiary, #999)', fontSize: 13 } }, '暂无待审核词条')
            : wikiReact.createElement('div', { style: { display: 'flex', flexDirection: 'column', gap: 8 } },
                pending.map(function (v) {
                  return wikiReact.createElement('div', {
                    key: v.id,
                    style: {
                      padding: 12, background: 'var(--bg-page, #f5f5f5)',
                      borderRadius: 8,
                    },
                  },
                    wikiReact.createElement('div', { style: { fontSize: 13, fontWeight: 500, marginBottom: 4 } }, v.entry_title),
                    wikiReact.createElement('div', { style: { fontSize: 11, color: 'var(--text-secondary, #666)', marginBottom: 8 } },
                      v.user_name + ' · v' + v.version + ' · ' + (v.change_note || '编辑')
                    ),
                    wikiReact.createElement('div', { style: { display: 'flex', gap: 8 } },
                      wikiReact.createElement('button', {
                        onClick: function () { handleReject(v.id); },
                        style: {
                          flex: 1, padding: '6px 0', fontSize: 12,
                          background: '#fee2e2', color: '#991b1b',
                          border: 'none', borderRadius: 6, cursor: 'pointer',
                        },
                      }, '驳回'),
                      wikiReact.createElement('button', {
                        onClick: function () { handleApprove(v.id); },
                        style: {
                          flex: 1, padding: '6px 0', fontSize: 12,
                          background: '#dcfce7', color: '#15803d',
                          border: 'none', borderRadius: 6, cursor: 'pointer',
                        },
                      }, '通过')
                    )
                  );
                })
              )
      )
    )
  );
}

// ========== 百科编辑页（独立页面入口，直接复用逻辑） ==========
function WikiEditPage() {
  var app = safeUseApp();
  var navigate = app.navigate || function () {};
  var params = app.pageParams || {};
  var entryId = params.id;

  var s0 = useState(true); var showEdit = s0[0];

  return wikiReact.createElement('div', { style: {
    display: 'flex', flexDirection: 'column',
    height: '100dvh', overflow: 'hidden',
    background: 'var(--bg-page, #f5f5f5)',
  } },
    wikiReact.createElement(WikiHeader, { title: '编辑词条', backTo: 'wiki-entry' }),
    wikiReact.createElement('div', { style: { flex: 1, padding: 16 } },
      wikiReact.createElement('div', { style: { padding: 16, background: 'var(--bg-card, #fff)', borderRadius: 10 } },
        wikiReact.createElement('div', { style: { fontSize: 13, color: 'var(--text-secondary, #666)' } }, '请在词条详情页点击"编辑"按钮进入编辑。')
      )
    ),
    showEdit && wikiReact.createElement(EditEntryModal, {
      entryId: entryId,
      currentContent: '',
      onClose: function () { try { navigate('wiki-entry', { id: entryId }); } catch (e) {} },
      onSuccess: function () { try { navigate('wiki-entry', { id: entryId }); } catch (e) {} },
    })
  );
}

// 管理员审核页
function AdminWikiPage() {
  var s0 = useState(true); var show = s0[0];
  return wikiReact.createElement('div', { style: {
    display: 'flex', flexDirection: 'column',
    height: '100dvh', overflow: 'hidden',
    background: 'var(--bg-page, #f5f5f5)',
  } },
    wikiReact.createElement(WikiHeader, { title: '词条审核', backTo: 'wiki' }),
    wikiReact.createElement('div', { style: { flex: 1, padding: 16 } },
      wikiReact.createElement('div', { style: { padding: 16, background: 'var(--bg-card, #fff)', borderRadius: 10 } },
        wikiReact.createElement('div', { style: { fontSize: 13, color: 'var(--text-secondary, #666)' } }, '请在百科列表页进入管理员审核。')
      )
    ),
    show && wikiReact.createElement(AdminWikiModal, {
      onClose: function () {},
      onSuccess: function () {},
    })
  );
}

// ========== 导出 ==========
function withWikiBoundary(Component) {
  return function (props) {
    return wikiReact.createElement(WikiErrorBoundary, {},
      wikiReact.createElement(Component, props)
    );
  };
}

window.WikiPage = withWikiBoundary(WikiPage);
window.WikiEntryPage = withWikiBoundary(WikiEntryPage);
window.WikiEditPage = withWikiBoundary(WikiEditPage);
window.AdminWikiPage = withWikiBoundary(AdminWikiPage);
