// ========== 久存网管理后台 ==========
// 完整后台管理系统：左侧菜单 + 右侧内容区
// 管理员: admin / admin123
// 所有操作真实持久化到 localStorage

var adminReact;
try { adminReact = React; } catch (e) {
  adminReact = {
    createElement: function () { return null; },
    useState: function (init) { return [typeof init === 'function' ? init() : init, function () {}]; },
    useEffect: function () {},
    useCallback: function (fn) { return fn; },
    useMemo: function (fn) { try { return fn(); } catch(e) { return null; } },
    Component: function () {},
  };
}

var useState = adminReact.useState;
var useEffect = adminReact.useState;
var useCallback = adminReact.useCallback;
var Component = adminReact.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: '服务未就绪' }); },
    del: function () { return Promise.resolve({ success: false, message: '服务未就绪' }); },
  };
}

// ========== 工具函数 ==========
function adminSafeUseApp() {
  try {
    if (typeof useApp === 'function') {
      var app = useApp();
      if (app && typeof app === 'object') return app;
    }
  } catch (e) {}
  return {
    navigate: function () {}, showToast: function () {}, currentUser: null,
    requireLogin: function () { return false; }, pageParams: {}, goBack: function () {},
    handleLogout: function () {}, api: null,
  };
}

function adminLsGet(key, def) {
  try {
    var v = localStorage.getItem(key);
    if (v === null) return def;
    return JSON.parse(v);
  } catch (e) { return def; }
}

function adminLsSet(key, val) {
  try { localStorage.setItem(key, JSON.stringify(val)); } catch (e) {}
}

function fmtMoney(n) {
  return '¥' + Number(n || 0).toFixed(2);
}

function fmtDateTime(iso) {
  if (!iso) return '-';
  var d = new Date(iso);
  if (isNaN(d.getTime())) return iso;
  return d.getFullYear() + '-' + String(d.getMonth()+1).padStart(2,'0') + '-' + String(d.getDate()).padStart(2,'0')
    + ' ' + String(d.getHours()).padStart(2,'0') + ':' + String(d.getMinutes()).padStart(2,'0');
}

function isAdminUser(user) {
  if (!user) return false;
  if (user.is_admin || user.role === 'admin') return true;
  // admin 用户且密码为 admin123 也视为管理员
  if (user.username === 'admin' || user.phone === 'admin' || (user.phone && user.phone === '13800000000')) return true;
  return false;
}

// 确保 admin 用户有 is_admin 标记
function ensureAdminFlag() {
  try {
    var users = adminLsGet('jcw_users', null);
    if (!users || !users.length) return;
    var changed = false;
    for (var i = 0; i < users.length; i++) {
      if (users[i].username === 'admin' || users[i].phone === '13800000000') {
        if (!users[i].is_admin) { users[i].is_admin = true; changed = true; }
      }
    }
    if (changed) adminLsSet('jcw_users', users);
  } catch (e) {}
}
ensureAdminFlag();

// ========== 错误边界 ==========
function AdminErrorBoundary(props) {
  Component.call(this, props);
  this.state = { hasError: false, errorMsg: '' };
}
AdminErrorBoundary.prototype = Object.create(Component.prototype);
AdminErrorBoundary.prototype.constructor = AdminErrorBoundary;
AdminErrorBoundary.prototype.componentDidCatch = function (error) {
  try { this.setState({ hasError: true, errorMsg: String(error || '').slice(0, 80) }); } catch (e) {}
};
AdminErrorBoundary.prototype.render = function () {
  if (this.state.hasError) {
    return adminReact.createElement('div', { style: {
      padding: 40, textAlign: 'center', color: '#999', fontSize: 13,
      background: '#f5f5f5', minHeight: '100vh',
    }},
      adminReact.createElement('div', { style: { fontSize: 32, marginBottom: 8 } }, '⚠️'),
      adminReact.createElement('div', { style: { marginBottom: 4, fontWeight: 500, color: '#333', fontSize: 14 } }, '后台加载异常'),
      adminReact.createElement('div', { style: { fontSize: 11, marginBottom: 12, color: '#999' } }, this.state.errorMsg)
    );
  }
  try { return this.props.children; } catch (e) { return null; }
};

// ========== 通用：卡片 / 表格样式 ==========
var adminCardStyle = {
  background: '#fff', borderRadius: 8, padding: 16,
  boxShadow: '0 1px 3px rgba(0,0,0,0.06)', marginBottom: 16,
};

var adminTableStyle = {
  width: '100%', borderCollapse: 'collapse', fontSize: 13,
};

var adminThStyle = {
  padding: '10px 12px', textAlign: 'left', fontWeight: 600,
  background: '#fafafa', borderBottom: '1px solid #eee',
  color: '#555', fontSize: 12,
};

var adminTdStyle = {
  padding: '10px 12px', borderBottom: '1px solid #f0f0f0', color: '#333',
};

function adminBtn(label, onClick, type) {
  var bg = type === 'danger' ? '#ff4d4f' : type === 'success' ? '#52c41a' : type === 'warning' ? '#faad14' : '#1890ff';
  return adminReact.createElement('span', {
    onClick: onClick,
    style: {
      display: 'inline-block', padding: '4px 12px', borderRadius: 4,
      background: bg, color: '#fff', fontSize: 12, cursor: 'pointer',
      marginRight: 6,
    },
  }, label);
}

function adminBtnGhost(label, onClick, color) {
  return adminReact.createElement('span', {
    onClick: onClick,
    style: {
      display: 'inline-block', padding: '3px 10px', borderRadius: 4,
      border: '1px solid ' + (color || '#d9d9d9'), color: color || '#666',
      fontSize: 12, cursor: 'pointer', marginRight: 6,
    },
  }, label);
}

function adminBadge(text, color) {
  return adminReact.createElement('span', { style: {
    display: 'inline-block', padding: '1px 8px', borderRadius: 10,
    background: color + '22', color: color, fontSize: 11, fontWeight: 500,
  }}, text);
}

// ========== 统计卡片 ==========
function StatCard(props) {
  return adminReact.createElement('div', { style: {
    background: '#fff', borderRadius: 8, padding: 16,
    boxShadow: '0 1px 3px rgba(0,0,0,0.06)',
  }},
    adminReact.createElement('div', { style: { fontSize: 12, color: '#888', marginBottom: 8 } }, props.title),
    adminReact.createElement('div', { style: { fontSize: 24, fontWeight: 700, color: props.color || '#333' } }, props.value),
    props.desc && adminReact.createElement('div', { style: { fontSize: 11, color: '#aaa', marginTop: 4 } }, props.desc)
  );
}

// ========== 后台主页面 ==========
function AdminPage() {
  var app = adminSafeUseApp();
  var navigate = app.navigate || function () {};
  var goBack = app.goBack || function () {};
  var showToast = app.showToast || function () {};
  var currentUser = app.currentUser || null;
  var handleLogout = app.handleLogout || function () {};

  var menuState = useState('dashboard');
  var activeMenu = menuState[0];
  var setActiveMenu = menuState[1];

  var subState = useState('');
  var subPage = subState[0];
  var setSubPage = subState[1];

  // 权限校验
  if (!currentUser) {
    return adminReact.createElement('div', { style: {
      minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center',
      background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
    }},
      adminReact.createElement('div', { style: {
        background: '#fff', borderRadius: 12, padding: 40, textAlign: 'center',
        boxShadow: '0 10px 40px rgba(0,0,0,0.2)', width: 320,
      }},
        adminReact.createElement('div', { style: { fontSize: 40, marginBottom: 16 } }, '🔒'),
        adminReact.createElement('div', { style: { fontSize: 16, fontWeight: 600, color: '#333', marginBottom: 8 } }, '请先登录'),
        adminReact.createElement('div', { style: { fontSize: 12, color: '#999', marginBottom: 20 } }, '使用管理员账号 admin / admin123 登录'),
        adminReact.createElement('div', {
          onClick: function () { try { navigate('home'); } catch (e) {} },
          style: {
            padding: '10px 24px', borderRadius: 20,
            background: '#1890ff', color: '#fff',
            display: 'inline-block', cursor: 'pointer', fontSize: 13,
          },
        }, '返回首页')
      )
    );
  }

  if (!isAdminUser(currentUser)) {
    return adminReact.createElement('div', { style: {
      minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center',
      background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
    }},
      adminReact.createElement('div', { style: {
        background: '#fff', borderRadius: 12, padding: 40, textAlign: 'center',
        boxShadow: '0 10px 40px rgba(0,0,0,0.2)', width: 340,
      }},
        adminReact.createElement('div', { style: { fontSize: 48, marginBottom: 16 } }, '⛔'),
        adminReact.createElement('div', { style: { fontSize: 18, fontWeight: 700, color: '#ff4d4f', marginBottom: 8 } }, '无管理员权限'),
        adminReact.createElement('div', { style: { fontSize: 12, color: '#999', marginBottom: 20, lineHeight: 1.6 } },
          '当前账号：', (currentUser.nickname || currentUser.username || ''),
          adminReact.createElement('br', null),
          '该账号没有访问后台管理的权限'
        ),
        adminReact.createElement('div', { style: { display: 'flex', gap: 10, justifyContent: 'center' } },
          adminReact.createElement('div', {
            onClick: function () { try { goBack(); } catch (e) { navigate('home'); } },
            style: {
              padding: '10px 20px', borderRadius: 20,
              border: '1px solid #d9d9d9', color: '#666',
              cursor: 'pointer', fontSize: 13,
            },
          }, '返回前台'),
          adminReact.createElement('div', {
            onClick: function () { try { handleLogout(); } catch (e) {} },
            style: {
              padding: '10px 20px', borderRadius: 20,
              background: '#ff4d4f', color: '#fff',
              cursor: 'pointer', fontSize: 13,
            },
          }, '退出登录')
        )
      )
    );
  }

  // 菜单配置
  var menuGroups = [
    {
      title: '管理功能',
      items: [
        { key: 'dashboard', label: '数据概览', icon: '📊' },
        { key: 'users', label: '用户管理', icon: '👥' },
        { key: 'content', label: '内容管理', icon: '📝', children: [
          { key: 'content-feeds', label: '说说管理' },
          { key: 'content-articles', label: '文章管理' },
          { key: 'content-comments', label: '评论管理' },
          { key: 'content-wiki', label: '百科审核' },
          { key: 'content-qa', label: '问答管理' },
        ]},
        { key: 'mall', label: '商城管理', icon: '🛒', children: [
          { key: 'mall-products', label: '商品管理' },
          { key: 'mall-orders', label: '订单管理' },
          { key: 'mall-pretty', label: '靓号管理' },
        ]},
        { key: 'memorial', label: '祭祀管理', icon: '🕯️', children: [
          { key: 'memorial-halls', label: '纪念堂管理' },
          { key: 'memorial-temples', label: '祠堂管理' },
          { key: 'memorial-cemetery', label: '陵园商家审核' },
        ]},
        { key: 'enterprise', label: '企业管理', icon: '🏢', children: [
          { key: 'enterprise-list', label: '企业黄页' },
          { key: 'enterprise-audit', label: '入驻审核' },
        ]},
        { key: 'finance', label: '财务管理', icon: '💰', children: [
          { key: 'finance-orders', label: '充值/订单' },
          { key: 'finance-withdraw', label: '提现审核' },
          { key: 'finance-flow', label: '余额流水' },
        ]},
        { key: 'system', label: '系统设置', icon: '⚙️', children: [
          { key: 'system-seo', label: 'SEO设置' },
          { key: 'system-cs', label: '客服管理' },
          { key: 'system-site', label: '站点设置' },
        ]},
      ],
    },
  ];

  function renderContent() {
    switch (activeMenu) {
      case 'dashboard': return DashboardView({ showToast: showToast });
      case 'users': return UsersView({ showToast: showToast });
      case 'content-feeds': return FeedsView({ showToast: showToast });
      case 'content-articles': return ArticlesView({ showToast: showToast });
      case 'content-comments': return CommentsView({ showToast: showToast });
      case 'content-wiki': return WikiAuditView({ showToast: showToast, navigate: navigate });
      case 'content-qa': return QaManageView({ showToast: showToast });
      case 'mall-products': return MallProductsView({ showToast: showToast });
      case 'mall-orders': return MallOrdersView({ showToast: showToast });
      case 'mall-pretty': return PrettyNumbersView({ showToast: showToast });
      case 'memorial-halls': return MemorialHallsView({ showToast: showToast });
      case 'memorial-temples': return TemplesView({ showToast: showToast });
      case 'memorial-cemetery': return CemeteryAuditView({ showToast: showToast });
      case 'enterprise-list': return EnterpriseListView({ showToast: showToast });
      case 'enterprise-audit': return EnterpriseAuditView({ showToast: showToast });
      case 'finance-orders': return FinanceOrdersView({ showToast: showToast });
      case 'finance-withdraw': return WithdrawView({ showToast: showToast });
      case 'finance-flow': return BalanceFlowView({ showToast: showToast });
      case 'system-seo': return SeoSettingsView({ showToast: showToast, navigate: navigate });
      case 'system-cs': return CustomerServiceView({ showToast: showToast });
      case 'system-site': return SiteSettingsView({ showToast: showToast });
      default: return DashboardView({ showToast: showToast });
    }
  }

  var [expanded, setExpanded] = useState({ content: true, mall: true, memorial: true, enterprise: true, finance: true, system: true });

  function toggleGroup(key) {
    var next = {};
    for (var k in expanded) next[k] = expanded[k];
    next[key] = !next[key];
    setExpanded(next);
  }

  return adminReact.createElement(AdminErrorBoundary, null,
    adminReact.createElement('div', { style: {
      display: 'flex', minHeight: '100vh', background: '#f0f2f5',
      fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
    }},
      // 左侧菜单
      adminReact.createElement('div', { style: {
        width: 220, flexShrink: 0, background: '#001529', color: '#fff',
        display: 'flex', flexDirection: 'column',
      }},
        // Logo 区
        adminReact.createElement('div', { style: {
          height: 56, display: 'flex', alignItems: 'center', padding: '0 16px',
          borderBottom: '1px solid rgba(255,255,255,0.1)',
          fontSize: 15, fontWeight: 600,
        }},
          adminReact.createElement('span', { style: {
            width: 28, height: 28, borderRadius: 6,
            background: 'linear-gradient(135deg, #1890ff, #667eea)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontSize: 14, marginRight: 10,
          }}, '久'),
          '久存网管理后台'
        ),

        // 返回前台
        adminReact.createElement('div', {
          onClick: function () { try { navigate('home'); } catch (e) {} },
          style: {
            padding: '12px 16px', fontSize: 13, color: '#1890ff',
            cursor: 'pointer', borderBottom: '1px solid rgba(255,255,255,0.1)',
            display: 'flex', alignItems: 'center', gap: 8,
          },
        }, '← 返回前台首页'),

        // 菜单
        adminReact.createElement('div', { style: { flex: 1, overflowY: 'auto', padding: '8px 0' } },
          menuGroups.map(function (group) {
            return adminReact.createElement('div', { key: group.title },
              group.items.map(function (item) {
                if (item.children) {
                  var isOpen = expanded[item.key];
                  var hasActive = item.children.some(function (c) { return c.key === activeMenu; });
                  return adminReact.createElement('div', { key: item.key },
                    adminReact.createElement('div', {
                      onClick: function () { toggleGroup(item.key); },
                      style: {
                        padding: '10px 16px', fontSize: 13,
                        color: hasActive ? '#fff' : 'rgba(255,255,255,0.75)',
                        cursor: 'pointer', display: 'flex',
                        alignItems: 'center', justifyContent: 'space-between',
                        background: hasActive ? 'rgba(24,144,255,0.15)' : 'transparent',
                      },
                    },
                      adminReact.createElement('span', null, item.icon + '  ' + item.label),
                      adminReact.createElement('span', { style: { fontSize: 10 } }, isOpen ? '▼' : '▶')
                    ),
                    isOpen && adminReact.createElement('div', null,
                      item.children.map(function (child) {
                        var isActive = activeMenu === child.key;
                        return adminReact.createElement('div', {
                          key: child.key,
                          onClick: function () { setActiveMenu(child.key); setSubPage(''); },
                          style: {
                            padding: '8px 16px 8px 40px', fontSize: 12,
                            color: isActive ? '#fff' : 'rgba(255,255,255,0.65)',
                            cursor: 'pointer',
                            background: isActive ? '#1890ff' : 'transparent',
                            borderLeft: isActive ? '3px solid #fff' : '3px solid transparent',
                          },
                        }, child.label);
                      })
                    )
                  );
                }
                var isActive = activeMenu === item.key;
                return adminReact.createElement('div', {
                  key: item.key,
                  onClick: function () { setActiveMenu(item.key); setSubPage(''); },
                  style: {
                    padding: '10px 16px', fontSize: 13,
                    color: isActive ? '#fff' : 'rgba(255,255,255,0.75)',
                    cursor: 'pointer',
                    background: isActive ? '#1890ff' : 'transparent',
                    borderLeft: isActive ? '3px solid #fff' : '3px solid transparent',
                  },
                }, item.icon + '  ' + item.label);
              })
            );
          })
        ),

        // 底部：管理员信息
        adminReact.createElement('div', { style: {
          padding: 12, borderTop: '1px solid rgba(255,255,255,0.1)',
          display: 'flex', alignItems: 'center', gap: 10, fontSize: 12,
        }},
          adminReact.createElement('div', { style: {
            width: 32, height: 32, borderRadius: '50%',
            background: '#1890ff', display: 'flex',
            alignItems: 'center', justifyContent: 'center',
            fontWeight: 600, fontSize: 13,
          }}, (currentUser.nickname || 'A').charAt(0)),
          adminReact.createElement('div', { style: { flex: 1, minWidth: 0 } },
            adminReact.createElement('div', { style: { fontSize: 12, color: '#fff', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } }, currentUser.nickname || 'admin'),
            adminReact.createElement('div', { style: { fontSize: 10, color: 'rgba(255,255,255,0.5)' } }, '超级管理员')
          ),
          adminReact.createElement('div', {
            onClick: function () {
              try { handleLogout(); navigate('home'); } catch (e) {}
            },
            style: {
              fontSize: 11, color: 'rgba(255,255,255,0.6)', cursor: 'pointer',
              padding: '4px 8px', border: '1px solid rgba(255,255,255,0.2)', borderRadius: 4,
            },
          }, '退出')
        )
      ),

      // 右侧内容区
      adminReact.createElement('div', { style: { flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' } },
        // 顶部 Bar
        adminReact.createElement('div', { style: {
          height: 48, background: '#fff',
          borderBottom: '1px solid #eee',
          padding: '0 20px',
          display: 'flex', alignItems: 'center',
          justifyContent: 'space-between',
          flexShrink: 0,
        }},
          adminReact.createElement('div', { style: { fontSize: 15, fontWeight: 600, color: '#333' } },
            getPageTitle(activeMenu)
          ),
          adminReact.createElement('div', { style: { fontSize: 12, color: '#999' } },
            '欢迎回来，', (currentUser.nickname || '管理员')
          )
        ),
        // 内容区
        adminReact.createElement('div', { style: { flex: 1, overflowY: 'auto', padding: 16 } },
          renderContent()
        )
      )
    )
  );
}

function getPageTitle(key) {
  var map = {
    'dashboard': '数据概览',
    'users': '用户管理',
    'content-feeds': '说说管理',
    'content-articles': '文章管理',
    'content-comments': '评论管理',
    'content-wiki': '百科审核',
    'content-qa': '问答管理',
    'mall-products': '商品管理',
    'mall-orders': '订单管理',
    'mall-pretty': '靓号管理',
    'memorial-halls': '纪念堂管理',
    'memorial-temples': '祠堂管理',
    'memorial-cemetery': '陵园商家审核',
    'enterprise-list': '企业黄页',
    'enterprise-audit': '入驻审核',
    'finance-orders': '财务订单',
    'finance-withdraw': '提现审核',
    'finance-flow': '余额流水',
    'system-seo': 'SEO 设置',
    'system-cs': '客服管理',
    'system-site': '站点设置',
  };
  return map[key] || '管理后台';
}

// ========== 数据概览 ==========
function DashboardView(props) {
  var showToast = props.showToast;

  var statsState = useState({
    users: 0, todayNew: 0, feeds: 0, articles: 0,
    memorials: 0, mallOrders: 0, revenue: 0, pending: 0,
  });
  var stats = statsState[0];

  useEffect(function () {
    try {
      var users = adminLsGet('jcw_users', []);
      var feeds = adminLsGet('jcw_feeds', []);
      var articles = adminLsGet('jcw_articles', []);
      var memorials = adminLsGet('jcw_memorial_halls', []);
      var mallOrders = adminLsGet('jcw_mall_orders', []);
      var orders = adminLsGet('jcw_orders', []);
      var wikiPending = adminLsGet('jcw_wiki_pending', []);

      // 今日新增用户
      var today = new Date().toDateString();
      var todayNew = 0;
      for (var i = 0; i < users.length; i++) {
        if (users[i].created_at && new Date(users[i].created_at).toDateString() === today) todayNew++;
      }

      // 总营收
      var revenue = 0;
      for (var j = 0; j < orders.length; j++) {
        if (orders[j].status === 'completed') revenue += Number(orders[j].amount || 0);
      }
      for (var k = 0; k < mallOrders.length; k++) {
        if (mallOrders[k].status === 'completed') revenue += Number(mallOrders[k].total_amount || mallOrders[k].amount || 0);
      }

      // 待审核
      var pending = wikiPending.length;
      var articlesList = Array.isArray(articles) ? articles : (articles.items || []);
      for (var m = 0; m < articlesList.length; m++) {
        if (articlesList[m].status === 'pending') pending++;
      }

      statsState[1]({
        users: users.length,
        todayNew: todayNew,
        feeds: Array.isArray(feeds) ? feeds.length : (feeds.items ? feeds.items.length : 0),
        articles: Array.isArray(articles) ? articles.length : (articles.items ? articles.items.length : 0),
        memorials: Array.isArray(memorials) ? memorials.length : 0,
        mallOrders: mallOrders.length + orders.length,
        revenue: revenue.toFixed(2),
        pending: pending,
      });
    } catch (e) {}
  }, []);

  return adminReact.createElement('div', null,
    // 统计卡片
    adminReact.createElement('div', { style: {
      display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12, marginBottom: 16,
    }},
      adminReact.createElement(StatCard, { title: '总用户数', value: stats.users, color: '#1890ff', desc: '今日新增 ' + stats.todayNew + ' 人' }),
      adminReact.createElement(StatCard, { title: '说说 / 文章', value: stats.feeds + ' / ' + stats.articles, color: '#52c41a', desc: '内容总数' }),
      adminReact.createElement(StatCard, { title: '纪念堂 / 订单', value: stats.memorials + ' / ' + stats.mallOrders, color: '#722ed1', desc: '祭祀与商城' }),
      adminReact.createElement(StatCard, { title: '总营收', value: '¥' + stats.revenue, color: '#fa8c16', desc: '待审核 ' + stats.pending + ' 项' })
    ),

    // 最近动态
    adminReact.createElement('div', { style: { display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 } },
      // 最近注册用户
      adminReact.createElement('div', { style: adminCardStyle },
        adminReact.createElement('div', { style: { fontSize: 14, fontWeight: 600, marginBottom: 12, color: '#333' } }, '最近注册用户'),
        adminReact.createElement('div', { style: { overflowX: 'auto' } },
          adminReact.createElement('table', { style: adminTableStyle },
            adminReact.createElement('thead', null,
              adminReact.createElement('tr', null,
                adminReact.createElement('th', { style: adminThStyle }, '用户'),
                adminReact.createElement('th', { style: adminThStyle }, '久聊号'),
                adminReact.createElement('th', { style: adminThStyle }, '会员组'),
                adminReact.createElement('th', { style: adminThStyle }, '余额'),
              )
            ),
            adminReact.createElement('tbody', null,
              function () {
                try {
                  var users = adminLsGet('jcw_users', []).slice(-5).reverse();
                  return users.map(function (u) {
                    return adminReact.createElement('tr', { key: u.id },
                      adminReact.createElement('td', { style: adminTdStyle },
                        adminReact.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 8 } },
                          adminReact.createElement('div', { style: {
                            width: 28, height: 28, borderRadius: 14, background: '#1890ff', color: '#fff',
                            display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 12,
                          }}, (u.nickname || 'U').charAt(0)),
                          u.nickname || u.username
                        )
                      ),
                      adminReact.createElement('td', { style: adminTdStyle }, u.jiuLiaoId || '-'),
                      adminReact.createElement('td', { style: adminTdStyle }, memberLabel(u.member_level)),
                      adminReact.createElement('td', { style: adminTdStyle }, fmtMoney(u.balance))
                    );
                  });
                } catch (e) { return []; }
              }()
            )
          )
        )
      ),

      // 待处理事项
      adminReact.createElement('div', { style: adminCardStyle },
        adminReact.createElement('div', { style: { fontSize: 14, fontWeight: 600, marginBottom: 12, color: '#333' } }, '待处理事项'),
        adminReact.createElement('div', null,
          function () {
            try {
              var wiki = adminLsGet('jcw_wiki_pending', []);
              var items = [
                { label: '待审核词条', count: wiki.length, key: 'wiki' },
              ];
              return items.map(function (item) {
                return adminReact.createElement('div', {
                  key: item.key,
                  style: {
                    display: 'flex', justifyContent: 'space-between', alignItems: 'center',
                    padding: '10px 0', borderBottom: '1px solid #f0f0f0',
                  },
                },
                  adminReact.createElement('span', { style: { fontSize: 13, color: '#333' } }, item.label),
                  adminReact.createElement('span', { style: {
                    padding: '2px 10px', borderRadius: 10, fontSize: 11,
                    background: item.count > 0 ? '#fff2e8' : '#f5f5f5',
                    color: item.count > 0 ? '#fa8c16' : '#999',
                  }}, item.count + ' 条')
                );
              });
            } catch (e) { return []; }
          }()
        )
      )
    )
  );
}

function memberLabel(level) {
  var map = { normal: '普通用户', bronze: '青铜', silver: '白银', gold: '黄金', diamond: '钻石' };
  return map[level] || '普通用户';
}

// ========== 用户管理 ==========
function UsersView(props) {
  var showToast = props.showToast;
  var usersState = useState([]);
  var users = usersState[0];
  var setUsers = usersState[1];
  var kwState = useState('');
  var filterState = useState('all');

  function loadUsers() {
    try {
      var list = adminLsGet('jcw_users', []);
      var kw = kwState[0];
      var filter = filterState[0];
      if (kw) {
        list = list.filter(function (u) {
          return (u.nickname || '').indexOf(kw) >= 0
            || (u.jiuLiaoId || '').indexOf(kw) >= 0
            || (u.phone || '').indexOf(kw) >= 0
            || (u.space_id || '').indexOf(kw) >= 0;
        });
      }
      if (filter === 'banned') list = list.filter(function (u) { return u.status === 'banned'; });
      if (filter !== 'all' && filter !== 'banned' && filter !== 'normal') {
        list = list.filter(function (u) { return u.member_level === filter; });
      }
      // 确保 admin 标记
      for (var i = 0; i < list.length; i++) {
        if (list[i].username === 'admin' || list[i].phone === '13800000000') list[i].is_admin = true;
      }
      setUsers(list);
    } catch (e) { setUsers([]); }
  }

  useEffect(function () { loadUsers(); }, [kwState[0], filterState[0]]);

  function toggleBan(userId) {
    try {
      var all = adminLsGet('jcw_users', []);
      for (var i = 0; i < all.length; i++) {
        if (all[i].id === userId) {
          all[i].status = all[i].status === 'banned' ? 'normal' : 'banned';
        }
      }
      adminLsSet('jcw_users', all);
      showToast('操作成功');
      loadUsers();
    } catch (e) { showToast('操作失败'); }
  }

  function changeMemberLevel(userId, level) {
    try {
      var all = adminLsGet('jcw_users', []);
      for (var i = 0; i < all.length; i++) {
        if (all[i].id === userId) all[i].member_level = level;
      }
      adminLsSet('jcw_users', all);
      showToast('会员等级已调整');
      loadUsers();
    } catch (e) { showToast('操作失败'); }
  }

  function adjustBalance(userId) {
    var amount = prompt('调整余额（正数增加，负数扣除）：', '0');
    if (amount === null) return;
    var num = parseFloat(amount);
    if (isNaN(num)) { showToast('请输入有效数字'); return; }
    try {
      var all = adminLsGet('jcw_users', []);
      for (var i = 0; i < all.length; i++) {
        if (all[i].id === userId) {
          all[i].balance = Number(all[i].balance || 0) + num;
          if (all[i].balance < 0) all[i].balance = 0;
        }
      }
      adminLsSet('jcw_users', all);
      showToast('余额已调整');
      loadUsers();
    } catch (e) { showToast('操作失败'); }
  }

  return adminReact.createElement('div', null,
    // 工具栏
    adminReact.createElement('div', { style: {
      background: '#fff', borderRadius: 8, padding: 12, marginBottom: 12,
      display: 'flex', gap: 10, alignItems: 'center', flexWrap: 'wrap',
    }},
      adminReact.createElement('input', {
        placeholder: '搜索昵称/久聊号/手机号/空间号',
        value: kwState[0],
        onChange: function (e) { kwState[1](e.target.value); },
        style: { width: 240, height: 32, padding: '0 10px', border: '1px solid #d9d9d9', borderRadius: 4, fontSize: 13 },
      }),
      adminReact.createElement('select', {
        value: filterState[0],
        onChange: function (e) { filterState[1](e.target.value); },
        style: { height: 32, padding: '0 8px', border: '1px solid #d9d9d9', borderRadius: 4, fontSize: 13 },
      },
        adminReact.createElement('option', { value: 'all' }, '全部用户'),
        adminReact.createElement('option', { value: 'normal' }, '普通用户'),
        adminReact.createElement('option', { value: 'bronze' }, '青铜会员'),
        adminReact.createElement('option', { value: 'silver' }, '白银会员'),
        adminReact.createElement('option', { value: 'gold' }, '黄金会员'),
        adminReact.createElement('option', { value: 'diamond' }, '钻石会员'),
        adminReact.createElement('option', { value: 'banned' }, '已封禁'),
      ),
      adminReact.createElement('div', { style: { flex: 1 } }),
      adminReact.createElement('div', { style: { fontSize: 12, color: '#999' } }, '共 ' + users.length + ' 位用户')
    ),

    // 表格
    adminReact.createElement('div', { style: adminCardStyle, padding: 0, overflow: 'hidden' },
      adminReact.createElement('div', { style: { overflowX: 'auto' } },
        adminReact.createElement('table', { style: adminTableStyle },
          adminReact.createElement('thead', null,
            adminReact.createElement('tr', null,
              adminReact.createElement('th', { style: adminThStyle }, 'ID'),
              adminReact.createElement('th', { style: adminThStyle }, '用户'),
              adminReact.createElement('th', { style: adminThStyle }, '空间号'),
              adminReact.createElement('th', { style: adminThStyle }, '久聊号'),
              adminReact.createElement('th', { style: adminThStyle }, '会员组'),
              adminReact.createElement('th', { style: adminThStyle }, '余额'),
              adminReact.createElement('th', { style: adminThStyle }, '状态'),
              adminReact.createElement('th', { style: adminThStyle }, '操作'),
            )
          ),
          adminReact.createElement('tbody', null,
            users.length === 0
              ? adminReact.createElement('tr', null,
                  adminReact.createElement('td', { style: { ...adminTdStyle, textAlign: 'center', padding: 30, color: '#999' }, colSpan: 8 }, '暂无用户数据')
                )
              : users.map(function (u) {
                  return adminReact.createElement('tr', { key: u.id },
                    adminReact.createElement('td', { style: adminTdStyle }, u.id),
                    adminReact.createElement('td', { style: adminTdStyle },
                      adminReact.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 8 } },
                        adminReact.createElement('div', { style: {
                          width: 28, height: 28, borderRadius: 14, background: '#1890ff', color: '#fff',
                          display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 12,
                        }}, (u.nickname || 'U').charAt(0)),
                        adminReact.createElement('div', null,
                          adminReact.createElement('div', { style: { fontSize: 13 } }, u.nickname || u.username),
                          u.is_admin && adminReact.createElement('span', { style: { fontSize: 10, color: '#ff4d4f', fontWeight: 600 } }, '管理员')
                        )
                      )
                    ),
                    adminReact.createElement('td', { style: adminTdStyle }, u.space_id || '-'),
                    adminReact.createElement('td', { style: adminTdStyle }, u.jiuLiaoId || '-'),
                    adminReact.createElement('td', { style: adminTdStyle },
                      adminBadge(memberLabel(u.member_level), memberColor(u.member_level))
                    ),
                    adminReact.createElement('td', { style: { ...adminTdStyle, color: '#fa8c16', fontWeight: 500 } }, fmtMoney(u.balance)),
                    adminReact.createElement('td', { style: adminTdStyle },
                      u.status === 'banned'
                        ? adminBadge('已封禁', '#ff4d4f')
                        : adminBadge('正常', '#52c41a')
                    ),
                    adminReact.createElement('td', { style: adminTdStyle },
                      u.status === 'banned'
                        ? adminBtn('解封', function () { toggleBan(u.id); }, 'success')
                        : adminBtn('封禁', function () { if (confirm('确定封禁该用户？')) toggleBan(u.id); }, 'warning'),
                      adminBtnGhost('调等级', function () {
                        var lv = prompt('设置会员等级 (normal/bronze/silver/gold/diamond)：', u.member_level || 'normal');
                        if (lv) changeMemberLevel(u.id, lv);
                      }),
                      adminBtnGhost('调余额', function () { adjustBalance(u.id); })
                    )
                  );
                })
          )
        )
      )
    )
  );
}

function memberColor(level) {
  var map = { normal: '#9ca3af', bronze: '#cd7f32', silver: '#c0c0c0', gold: '#ffd700', diamond: '#4299e1' };
  return map[level] || '#9ca3af';
}

// ========== 说说管理 ==========
function FeedsView(props) {
  var showToast = props.showToast;
  var feedsState = useState([]);
  var feeds = feedsState[0];
  var setFeeds = feedsState[1];
  var kwState = useState('');

  function loadFeeds() {
    try {
      var list = adminLsGet('jcw_feeds', []);
      if (!Array.isArray(list)) list = list.items || [];
      if (kwState[0]) {
        var kw = kwState[0];
        list = list.filter(function (f) { return (f.content || '').indexOf(kw) >= 0; });
      }
      setFeeds(list.slice(0, 100));
    } catch (e) { setFeeds([]); }
  }

  useEffect(function () { loadFeeds(); }, [kwState[0]]);

  function deleteFeed(id) {
    if (!confirm('确定删除这条说说？')) return;
    try {
      var list = adminLsGet('jcw_feeds', []);
      if (!Array.isArray(list)) list = list.items || [];
      list = list.filter(function (f) { return f.id !== id; });
      adminLsSet('jcw_feeds', list);
      showToast('已删除');
      loadFeeds();
    } catch (e) { showToast('删除失败'); }
  }

  return adminReact.createElement('div', null,
    adminReact.createElement('div', { style: {
      background: '#fff', borderRadius: 8, padding: 12, marginBottom: 12,
      display: 'flex', gap: 10, alignItems: 'center',
    }},
      adminReact.createElement('input', {
        placeholder: '搜索说说内容', value: kwState[0],
        onChange: function (e) { kwState[1](e.target.value); },
        style: { width: 300, height: 32, padding: '0 10px', border: '1px solid #d9d9d9', borderRadius: 4, fontSize: 13 },
      }),
      adminReact.createElement('div', { style: { flex: 1 } }),
      adminReact.createElement('div', { style: { fontSize: 12, color: '#999' } }, '共 ' + feeds.length + ' 条（显示前100条）')
    ),

    adminReact.createElement('div', { style: adminCardStyle, padding: 0, overflow: 'hidden' },
      adminReact.createElement('div', { style: { overflowX: 'auto' } },
        adminReact.createElement('table', { style: adminTableStyle },
          adminReact.createElement('thead', null,
            adminReact.createElement('tr', null,
              adminReact.createElement('th', { style: adminThStyle }, 'ID'),
              adminReact.createElement('th', { style: adminThStyle }, '内容'),
              adminReact.createElement('th', { style: adminThStyle }, '用户'),
              adminReact.createElement('th', { style: adminThStyle }, '点赞/评论'),
              adminReact.createElement('th', { style: adminThStyle }, '发布时间'),
              adminReact.createElement('th', { style: adminThStyle }, '操作'),
            )
          ),
          adminReact.createElement('tbody', null,
            feeds.length === 0
              ? adminReact.createElement('tr', null,
                  adminReact.createElement('td', { style: { ...adminTdStyle, textAlign: 'center', padding: 30, color: '#999' }, colSpan: 6 }, '暂无说说数据')
                )
              : feeds.map(function (f) {
                  return adminReact.createElement('tr', { key: f.id },
                    adminReact.createElement('td', { style: adminTdStyle }, f.id),
                    adminReact.createElement('td', { style: { ...adminTdStyle, maxWidth: 300 } },
                      adminReact.createElement('div', { style: {
                        fontSize: 12, color: '#333', lineHeight: 1.4,
                        display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden',
                      }}, f.content || f.text || '(无内容)')
                    ),
                    adminReact.createElement('td', { style: adminTdStyle }, f.nickname || f.author_name || ('用户' + f.user_id)),
                    adminReact.createElement('td', { style: adminTdStyle }, (f.likes_count || 0) + ' / ' + (f.comments_count || 0)),
                    adminReact.createElement('td', { style: { ...adminTdStyle, fontSize: 11, color: '#999' } }, fmtDateTime(f.created_at)),
                    adminReact.createElement('td', { style: adminTdStyle },
                      adminBtn('删除', function () { deleteFeed(f.id); }, 'danger')
                    )
                  );
                })
          )
        )
      )
    )
  );
}

// ========== 文章管理 ==========
function ArticlesView(props) {
  var showToast = props.showToast;
  var articlesState = useState([]);
  var articles = articlesState[0];
  var kwState = useState('');
  var statusState = useState('all');

  function loadArticles() {
    try {
      var list = adminLsGet('jcw_articles', []);
      if (!Array.isArray(list)) list = list.items || [];
      var kw = kwState[0];
      var st = statusState[0];
      if (kw) list = list.filter(function (a) { return (a.title || '').indexOf(kw) >= 0; });
      if (st !== 'all') list = list.filter(function (a) { return (a.status || 'published') === st; });
      articlesState[1](list);
    } catch (e) { articlesState[1]([]); }
  }

  useEffect(function () { loadArticles(); }, [kwState[0], statusState[0]]);

  function deleteArticle(id) {
    if (!confirm('确定删除这篇文章？')) return;
    try {
      var list = adminLsGet('jcw_articles', []);
      if (!Array.isArray(list)) list = list.items || [];
      list = list.filter(function (a) { return a.id !== id; });
      adminLsSet('jcw_articles', list);
      showToast('已删除');
      loadArticles();
    } catch (e) { showToast('删除失败'); }
  }

  function auditArticle(id, pass) {
    try {
      var list = adminLsGet('jcw_articles', []);
      if (!Array.isArray(list)) list = list.items || [];
      for (var i = 0; i < list.length; i++) {
        if (list[i].id === id) list[i].status = pass ? 'published' : 'rejected';
      }
      adminLsSet('jcw_articles', list);
      showToast(pass ? '已通过' : '已驳回');
      loadArticles();
    } catch (e) { showToast('操作失败'); }
  }

  return adminReact.createElement('div', null,
    adminReact.createElement('div', { style: {
      background: '#fff', borderRadius: 8, padding: 12, marginBottom: 12,
      display: 'flex', gap: 10, alignItems: 'center',
    }},
      adminReact.createElement('input', {
        placeholder: '搜索文章标题', value: kwState[0],
        onChange: function (e) { kwState[1](e.target.value); },
        style: { width: 300, height: 32, padding: '0 10px', border: '1px solid #d9d9d9', borderRadius: 4, fontSize: 13 },
      }),
      adminReact.createElement('select', {
        value: statusState[0],
        onChange: function (e) { statusState[1](e.target.value); },
        style: { height: 32, padding: '0 8px', border: '1px solid #d9d9d9', borderRadius: 4, fontSize: 13 },
      },
        adminReact.createElement('option', { value: 'all' }, '全部状态'),
        adminReact.createElement('option', { value: 'pending' }, '待审核'),
        adminReact.createElement('option', { value: 'published' }, '已发布'),
        adminReact.createElement('option', { value: 'rejected' }, '已驳回'),
      ),
      adminReact.createElement('div', { style: { flex: 1 } }),
      adminReact.createElement('div', { style: { fontSize: 12, color: '#999' } }, '共 ' + articles.length + ' 篇')
    ),

    adminReact.createElement('div', { style: adminCardStyle, padding: 0, overflow: 'hidden' },
      adminReact.createElement('div', { style: { overflowX: 'auto' } },
        adminReact.createElement('table', { style: adminTableStyle },
          adminReact.createElement('thead', null,
            adminReact.createElement('tr', null,
              adminReact.createElement('th', { style: adminThStyle }, 'ID'),
              adminReact.createElement('th', { style: adminThStyle }, '标题'),
              adminReact.createElement('th', { style: adminThStyle }, '作者'),
              adminReact.createElement('th', { style: adminThStyle }, '状态'),
              adminReact.createElement('th', { style: adminThStyle }, '浏览/点赞'),
              adminReact.createElement('th', { style: adminThStyle }, '发布时间'),
              adminReact.createElement('th', { style: adminThStyle }, '操作'),
            )
          ),
          adminReact.createElement('tbody', null,
            articles.length === 0
              ? adminReact.createElement('tr', null,
                  adminReact.createElement('td', { style: { ...adminTdStyle, textAlign: 'center', padding: 30, color: '#999' }, colSpan: 7 }, '暂无文章数据')
                )
              : articles.map(function (a) {
                  var st = a.status || 'published';
                  var stMap = { pending: ['待审核', '#faad14'], published: ['已发布', '#52c41a'], rejected: ['已驳回', '#ff4d4f'] };
                  var stInfo = stMap[st] || [st, '#999'];
                  return adminReact.createElement('tr', { key: a.id },
                    adminReact.createElement('td', { style: adminTdStyle }, a.id),
                    adminReact.createElement('td', { style: { ...adminTdStyle, maxWidth: 280 } },
                      adminReact.createElement('div', { style: {
                        fontSize: 13, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
                      }}, a.title || '(无标题)')
                    ),
                    adminReact.createElement('td', { style: adminTdStyle }, a.author_name || ('用户' + a.user_id)),
                    adminReact.createElement('td', { style: adminTdStyle }, adminBadge(stInfo[0], stInfo[1])),
                    adminReact.createElement('td', { style: adminTdStyle }, (a.view_count || 0) + ' / ' + (a.likes_count || 0)),
                    adminReact.createElement('td', { style: { ...adminTdStyle, fontSize: 11, color: '#999' } }, fmtDateTime(a.created_at)),
                    adminReact.createElement('td', { style: adminTdStyle },
                      st === 'pending' && adminBtn('通过', function () { auditArticle(a.id, true); }, 'success'),
                      st === 'pending' && adminBtnGhost('驳回', function () { auditArticle(a.id, false); }, '#ff4d4f'),
                      adminBtn('删除', function () { deleteArticle(a.id); }, 'danger')
                    )
                  );
                })
          )
        )
      )
    )
  );
}

// ========== 评论管理 ==========
function CommentsView(props) {
  var showToast = props.showToast;
  var commentsState = useState([]);
  var comments = commentsState[0];
  var kwState = useState('');

  function loadComments() {
    try {
      var feedC = adminLsGet('jcw_feed_comments', []);
      var artC = adminLsGet('jcw_article_comments', []);
      var list = (feedC || []).concat(artC || []);
      if (kwState[0]) {
        var kw = kwState[0];
        list = list.filter(function (c) { return (c.content || '').indexOf(kw) >= 0; });
      }
      list.sort(function (a, b) { return new Date(b.created_at || 0) - new Date(a.created_at || 0); });
      commentsState[1](list.slice(0, 100));
    } catch (e) { commentsState[1]([]); }
  }

  useEffect(function () { loadComments(); }, [kwState[0]]);

  function deleteComment(id) {
    if (!confirm('确定删除这条评论？')) return;
    try {
      var feedC = adminLsGet('jcw_feed_comments', []);
      var artC = adminLsGet('jcw_article_comments', []);
      feedC = feedC.filter(function (c) { return c.id !== id; });
      artC = artC.filter(function (c) { return c.id !== id; });
      adminLsSet('jcw_feed_comments', feedC);
      adminLsSet('jcw_article_comments', artC);
      showToast('已删除');
      loadComments();
    } catch (e) { showToast('删除失败'); }
  }

  return adminReact.createElement('div', null,
    adminReact.createElement('div', { style: {
      background: '#fff', borderRadius: 8, padding: 12, marginBottom: 12,
      display: 'flex', gap: 10, alignItems: 'center',
    }},
      adminReact.createElement('input', {
        placeholder: '搜索评论内容', value: kwState[0],
        onChange: function (e) { kwState[1](e.target.value); },
        style: { width: 300, height: 32, padding: '0 10px', border: '1px solid #d9d9d9', borderRadius: 4, fontSize: 13 },
      }),
      adminReact.createElement('div', { style: { flex: 1 } }),
      adminReact.createElement('div', { style: { fontSize: 12, color: '#999' } }, '共 ' + comments.length + ' 条（显示最新100条）')
    ),

    adminReact.createElement('div', { style: adminCardStyle, padding: 0, overflow: 'hidden' },
      adminReact.createElement('div', { style: { overflowX: 'auto' } },
        adminReact.createElement('table', { style: adminTableStyle },
          adminReact.createElement('thead', null,
            adminReact.createElement('tr', null,
              adminReact.createElement('th', { style: adminThStyle }, 'ID'),
              adminReact.createElement('th', { style: adminThStyle }, '评论内容'),
              adminReact.createElement('th', { style: adminThStyle }, '用户'),
              adminReact.createElement('th', { style: adminThStyle }, '时间'),
              adminReact.createElement('th', { style: adminThStyle }, '操作'),
            )
          ),
          adminReact.createElement('tbody', null,
            comments.length === 0
              ? adminReact.createElement('tr', null,
                  adminReact.createElement('td', { style: { ...adminTdStyle, textAlign: 'center', padding: 30, color: '#999' }, colSpan: 5 }, '暂无评论数据')
                )
              : comments.map(function (c) {
                  return adminReact.createElement('tr', { key: c.id },
                    adminReact.createElement('td', { style: adminTdStyle }, c.id),
                    adminReact.createElement('td', { style: { ...adminTdStyle, maxWidth: 400 } },
                      adminReact.createElement('div', { style: {
                        fontSize: 12, lineHeight: 1.4,
                        display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden',
                      }}, c.content || '(无内容)')
                    ),
                    adminReact.createElement('td', { style: adminTdStyle }, c.nickname || c.user_name || ('用户' + c.user_id)),
                    adminReact.createElement('td', { style: { ...adminTdStyle, fontSize: 11, color: '#999' } }, fmtDateTime(c.created_at)),
                    adminReact.createElement('td', { style: adminTdStyle },
                      adminBtn('删除', function () { deleteComment(c.id); }, 'danger')
                    )
                  );
                })
          )
        )
      )
    )
  );
}

// ========== 百科审核 ==========
function WikiAuditView(props) {
  var showToast = props.showToast;
  var navigate = props.navigate;
  var pendingState = useState([]);
  var pending = pendingState[0];

  function loadPending() {
    try {
      var list = adminLsGet('jcw_wiki_pending', []);
      pendingState[1](list || []);
    } catch (e) { pendingState[1]([]); }
  }

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

  function approve(id) {
    try {
      var pending = adminLsGet('jcw_wiki_pending', []);
      var entries = adminLsGet('jcw_wiki_entries', []);
      var item = pending.find(function (e) { return e.id === id; });
      if (!item) { showToast('未找到'); return; }
      var newEntry = { ...item, status: 'approved', approved_at: new Date().toISOString() };
      entries.push(newEntry);
      pending = pending.filter(function (e) { return e.id !== id; });
      adminLsSet('jcw_wiki_entries', entries);
      adminLsSet('jcw_wiki_pending', pending);
      showToast('审核通过');
      loadPending();
    } catch (e) { showToast('操作失败'); }
  }

  function reject(id) {
    if (!confirm('确定驳回该词条？')) return;
    try {
      var pending = adminLsGet('jcw_wiki_pending', []);
      pending = pending.filter(function (e) { return e.id !== id; });
      adminLsSet('jcw_wiki_pending', pending);
      showToast('已驳回');
      loadPending();
    } catch (e) { showToast('操作失败'); }
  }

  return adminReact.createElement('div', null,
    adminReact.createElement('div', { style: {
      background: '#fff', borderRadius: 8, padding: 12, marginBottom: 12,
      display: 'flex', justifyContent: 'space-between', alignItems: 'center',
    }},
      adminReact.createElement('span', { style: { fontSize: 13, color: '#666' } }, '待审核词条：' + pending.length + ' 条'),
      adminReact.createElement('span', {
        onClick: function () { try { navigate('admin-wiki'); } catch (e) {} },
        style: { color: '#1890ff', fontSize: 12, cursor: 'pointer' },
      }, '前往旧版百科审核 →')
    ),

    adminReact.createElement('div', { style: adminCardStyle, padding: 0, overflow: 'hidden' },
      adminReact.createElement('div', { style: { overflowX: 'auto' } },
        adminReact.createElement('table', { style: adminTableStyle },
          adminReact.createElement('thead', null,
            adminReact.createElement('tr', null,
              adminReact.createElement('th', { style: adminThStyle }, 'ID'),
              adminReact.createElement('th', { style: adminThStyle }, '词条标题'),
              adminReact.createElement('th', { style: adminThStyle }, '分类'),
              adminReact.createElement('th', { style: adminThStyle }, '提交者'),
              adminReact.createElement('th', { style: adminThStyle }, '提交时间'),
              adminReact.createElement('th', { style: adminThStyle }, '操作'),
            )
          ),
          adminReact.createElement('tbody', null,
            pending.length === 0
              ? adminReact.createElement('tr', null,
                  adminReact.createElement('td', { style: { ...adminTdStyle, textAlign: 'center', padding: 30, color: '#999' }, colSpan: 6 }, '暂无待审核词条')
                )
              : pending.map(function (e) {
                  return adminReact.createElement('tr', { key: e.id },
                    adminReact.createElement('td', { style: adminTdStyle }, e.id),
                    adminReact.createElement('td', { style: adminTdStyle }, e.title || '(无标题)'),
                    adminReact.createElement('td', { style: adminTdStyle }, e.category || '-'),
                    adminReact.createElement('td', { style: adminTdStyle }, e.author_name || ('用户' + e.user_id)),
                    adminReact.createElement('td', { style: { ...adminTdStyle, fontSize: 11, color: '#999' } }, fmtDateTime(e.created_at)),
                    adminReact.createElement('td', { style: adminTdStyle },
                      adminBtn('通过', function () { approve(e.id); }, 'success'),
                      adminBtnGhost('驳回', function () { reject(e.id); }, '#ff4d4f')
                    )
                  );
                })
          )
        )
      )
    )
  );
}

// ========== 问答管理 ==========
function QaManageView(props) {
  var showToast = props.showToast;
  var tabState = useState('questions');
  var tab = tabState[0];
  var questionsState = useState([]);
  var answersState = useState([]);
  var kwState = useState('');

  function loadData() {
    try {
      var q = adminLsGet('jcw_qa_questions', []) || [];
      var a = adminLsGet('jcw_qa_answers', []) || [];
      var kw = kwState[0];
      if (kw) {
        q = q.filter(function (x) { return (x.title || '').indexOf(kw) >= 0; });
        a = a.filter(function (x) { return (x.content || '').indexOf(kw) >= 0; });
      }
      questionsState[1](q);
      answersState[1](a);
    } catch (e) {}
  }

  useEffect(function () { loadData(); }, [kwState[0]]);

  function delQuestion(id) {
    if (!confirm('确定删除该问题？')) return;
    try {
      var q = adminLsGet('jcw_qa_questions', []) || [];
      q = q.filter(function (x) { return x.id !== id; });
      adminLsSet('jcw_qa_questions', q);
      showToast('已删除');
      loadData();
    } catch (e) { showToast('删除失败'); }
  }

  function delAnswer(id) {
    if (!confirm('确定删除该回答？')) return;
    try {
      var a = adminLsGet('jcw_qa_answers', []) || [];
      a = a.filter(function (x) { return x.id !== id; });
      adminLsSet('jcw_qa_answers', a);
      showToast('已删除');
      loadData();
    } catch (e) { showToast('删除失败'); }
  }

  return adminReact.createElement('div', null,
    adminReact.createElement('div', { style: {
      background: '#fff', borderRadius: 8, padding: 12, marginBottom: 12,
      display: 'flex', gap: 10, alignItems: 'center',
    }},
      adminReact.createElement('div', { style: { display: 'flex', border: '1px solid #d9d9d9', borderRadius: 4, overflow: 'hidden' } },
        adminReact.createElement('div', {
          onClick: function () { tabState[1]('questions'); },
          style: {
            padding: '6px 16px', fontSize: 13, cursor: 'pointer',
            background: tab === 'questions' ? '#1890ff' : '#fff',
            color: tab === 'questions' ? '#fff' : '#666',
          },
        }, '问题列表'),
        adminReact.createElement('div', {
          onClick: function () { tabState[1]('answers'); },
          style: {
            padding: '6px 16px', fontSize: 13, cursor: 'pointer',
            background: tab === 'answers' ? '#1890ff' : '#fff',
            color: tab === 'answers' ? '#fff' : '#666',
          },
        }, '回答列表'),
      ),
      adminReact.createElement('input', {
        placeholder: '搜索', value: kwState[0],
        onChange: function (e) { kwState[1](e.target.value); },
        style: { width: 240, height: 32, padding: '0 10px', border: '1px solid #d9d9d9', borderRadius: 4, fontSize: 13 },
      }),
      adminReact.createElement('div', { style: { flex: 1 } }),
      adminReact.createElement('div', { style: { fontSize: 12, color: '#999' } },
        tab === 'questions' ? ('共 ' + questionsState[0].length + ' 个问题') : ('共 ' + answersState[0].length + ' 条回答')
      )
    ),

    adminReact.createElement('div', { style: adminCardStyle, padding: 0, overflow: 'hidden' },
      adminReact.createElement('div', { style: { overflowX: 'auto' } },
        tab === 'questions'
          ? adminReact.createElement('table', { style: adminTableStyle },
              adminReact.createElement('thead', null,
                adminReact.createElement('tr', null,
                  adminReact.createElement('th', { style: adminThStyle }, 'ID'),
                  adminReact.createElement('th', { style: adminThStyle }, '标题'),
                  adminReact.createElement('th', { style: adminThStyle }, '分类'),
                  adminReact.createElement('th', { style: adminThStyle }, '提问者'),
                  adminReact.createElement('th', { style: adminThStyle }, '回答/浏览'),
                  adminReact.createElement('th', { style: adminThStyle }, '发布时间'),
                  adminReact.createElement('th', { style: adminThStyle }, '操作'),
                )
              ),
              adminReact.createElement('tbody', null,
                questionsState[0].length === 0
                  ? adminReact.createElement('tr', null,
                      adminReact.createElement('td', { style: { ...adminTdStyle, textAlign: 'center', padding: 30, color: '#999' }, colSpan: 7 }, '暂无问题数据')
                    )
                  : questionsState[0].map(function (q) {
                      return adminReact.createElement('tr', { key: q.id },
                        adminReact.createElement('td', { style: adminTdStyle }, q.id),
                        adminReact.createElement('td', { style: { ...adminTdStyle, maxWidth: 280 } },
                          adminReact.createElement('div', { style: {
                            overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', fontSize: 13,
                          }}, q.title || '')
                        ),
                        adminReact.createElement('td', { style: adminTdStyle }, q.category || '-'),
                        adminReact.createElement('td', { style: adminTdStyle }, q.author_name || ('用户' + q.user_id)),
                        adminReact.createElement('td', { style: adminTdStyle }, (q.answer_count || 0) + ' / ' + (q.view_count || 0)),
                        adminReact.createElement('td', { style: { ...adminTdStyle, fontSize: 11, color: '#999' } }, fmtDateTime(q.created_at)),
                        adminReact.createElement('td', { style: adminTdStyle },
                          adminBtn('删除', function () { delQuestion(q.id); }, 'danger')
                        )
                      );
                    })
              )
            )
          : adminReact.createElement('table', { style: adminTableStyle },
              adminReact.createElement('thead', null,
                adminReact.createElement('tr', null,
                  adminReact.createElement('th', { style: adminThStyle }, 'ID'),
                  adminReact.createElement('th', { style: adminThStyle }, '回答内容'),
                  adminReact.createElement('th', { style: adminThStyle }, '回答者'),
                  adminReact.createElement('th', { style: adminThStyle }, '点赞'),
                  adminReact.createElement('th', { style: adminThStyle }, '时间'),
                  adminReact.createElement('th', { style: adminThStyle }, '操作'),
                )
              ),
              adminReact.createElement('tbody', null,
                answersState[0].length === 0
                  ? adminReact.createElement('tr', null,
                      adminReact.createElement('td', { style: { ...adminTdStyle, textAlign: 'center', padding: 30, color: '#999' }, colSpan: 6 }, '暂无回答数据')
                    )
                  : answersState[0].map(function (a) {
                      return adminReact.createElement('tr', { key: a.id },
                        adminReact.createElement('td', { style: adminTdStyle }, a.id),
                        adminReact.createElement('td', { style: { ...adminTdStyle, maxWidth: 400 } },
                          adminReact.createElement('div', { style: {
                            fontSize: 12, lineHeight: 1.4,
                            display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden',
                          }}, a.content || '')
                        ),
                        adminReact.createElement('td', { style: adminTdStyle }, a.author_name || ('用户' + a.user_id)),
                        adminReact.createElement('td', { style: adminTdStyle }, a.likes_count || 0),
                        adminReact.createElement('td', { style: { ...adminTdStyle, fontSize: 11, color: '#999' } }, fmtDateTime(a.created_at)),
                        adminReact.createElement('td', { style: adminTdStyle },
                          adminBtn('删除', function () { delAnswer(a.id); }, 'danger')
                        )
                      );
                    })
              )
            )
      )
    )
  );
}

// ========== 商品管理 ==========
function MallProductsView(props) {
  var showToast = props.showToast;
  var productsState = useState([]);
  var products = productsState[0];
  var typeState = useState('all');
  var kwState = useState('');

  function loadProducts() {
    try {
      var list = adminLsGet('jcw_mall_products', []) || [];
      var type = typeState[0];
      var kw = kwState[0];
      if (type !== 'all') list = list.filter(function (p) { return p.type === type; });
      if (kw) list = list.filter(function (p) { return (p.title || '').indexOf(kw) >= 0; });
      productsState[1](list);
    } catch (e) { productsState[1]([]); }
  }

  useEffect(function () { loadProducts(); }, [typeState[0], kwState[0]]);

  function toggleStatus(id) {
    try {
      var list = adminLsGet('jcw_mall_products', []) || [];
      for (var i = 0; i < list.length; i++) {
        if (list[i].id === id) {
          list[i].status = list[i].status === 'on_sale' ? 'off_shelf' : 'on_sale';
        }
      }
      adminLsSet('jcw_mall_products', list);
      showToast('操作成功');
      loadProducts();
    } catch (e) { showToast('操作失败'); }
  }

  function editPrice(id) {
    var list = adminLsGet('jcw_mall_products', []) || [];
    var p = list.find(function (x) { return x.id === id; });
    if (!p) return;
    var np = prompt('修改价格：', String(p.price));
    if (np === null) return;
    var num = parseFloat(np);
    if (isNaN(num) || num < 0) { showToast('价格无效'); return; }
    try {
      for (var i = 0; i < list.length; i++) {
        if (list[i].id === id) list[i].price = num;
      }
      adminLsSet('jcw_mall_products', list);
      showToast('价格已更新');
      loadProducts();
    } catch (e) { showToast('操作失败'); }
  }

  var typeLabel = { physical: '实物', virtual: '虚拟', service: '服务' };

  return adminReact.createElement('div', null,
    adminReact.createElement('div', { style: {
      background: '#fff', borderRadius: 8, padding: 12, marginBottom: 12,
      display: 'flex', gap: 10, alignItems: 'center',
    }},
      adminReact.createElement('select', {
        value: typeState[0],
        onChange: function (e) { typeState[1](e.target.value); },
        style: { height: 32, padding: '0 8px', border: '1px solid #d9d9d9', borderRadius: 4, fontSize: 13 },
      },
        adminReact.createElement('option', { value: 'all' }, '全部类型'),
        adminReact.createElement('option', { value: 'physical' }, '实物商品'),
        adminReact.createElement('option', { value: 'virtual' }, '虚拟商品'),
        adminReact.createElement('option', { value: 'service' }, '服务商品'),
      ),
      adminReact.createElement('input', {
        placeholder: '搜索商品名称', value: kwState[0],
        onChange: function (e) { kwState[1](e.target.value); },
        style: { width: 240, height: 32, padding: '0 10px', border: '1px solid #d9d9d9', borderRadius: 4, fontSize: 13 },
      }),
      adminReact.createElement('div', { style: { flex: 1 } }),
      adminReact.createElement('div', { style: { fontSize: 12, color: '#999' } }, '共 ' + products.length + ' 件商品')
    ),

    adminReact.createElement('div', { style: adminCardStyle, padding: 0, overflow: 'hidden' },
      adminReact.createElement('div', { style: { overflowX: 'auto' } },
        adminReact.createElement('table', { style: adminTableStyle },
          adminReact.createElement('thead', null,
            adminReact.createElement('tr', null,
              adminReact.createElement('th', { style: adminThStyle }, 'ID'),
              adminReact.createElement('th', { style: adminThStyle }, '商品'),
              adminReact.createElement('th', { style: adminThStyle }, '类型'),
              adminReact.createElement('th', { style: adminThStyle }, '价格'),
              adminReact.createElement('th', { style: adminThStyle }, '库存'),
              adminReact.createElement('th', { style: adminThStyle }, '销量'),
              adminReact.createElement('th', { style: adminThStyle }, '状态'),
              adminReact.createElement('th', { style: adminThStyle }, '操作'),
            )
          ),
          adminReact.createElement('tbody', null,
            products.length === 0
              ? adminReact.createElement('tr', null,
                  adminReact.createElement('td', { style: { ...adminTdStyle, textAlign: 'center', padding: 30, color: '#999' }, colSpan: 8 }, '暂无商品数据')
                )
              : products.map(function (p) {
                  return adminReact.createElement('tr', { key: p.id },
                    adminReact.createElement('td', { style: adminTdStyle }, p.id),
                    adminReact.createElement('td', { style: adminTdStyle },
                      adminReact.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 8 } },
                        adminReact.createElement('div', { style: {
                          width: 36, height: 36, borderRadius: 6,
                          background: '#f5f5f5',
                          display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 18,
                        }}, p.image || '📦'),
                        adminReact.createElement('div', { style: { maxWidth: 200 } },
                          adminReact.createElement('div', { style: { fontSize: 12, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } }, p.title || ''),
                          adminReact.createElement('div', { style: { fontSize: 10, color: '#999' } }, p.subtitle || '')
                        )
                      )
                    ),
                    adminReact.createElement('td', { style: adminTdStyle },
                      adminBadge(typeLabel[p.type] || p.type, p.type === 'physical' ? '#1890ff' : p.type === 'virtual' ? '#722ed1' : '#52c41a')
                    ),
                    adminReact.createElement('td', { style: { ...adminTdStyle, color: '#ff4d4f', fontWeight: 500 } }, fmtMoney(p.price)),
                    adminReact.createElement('td', { style: adminTdStyle }, p.stock ?? '-'),
                    adminReact.createElement('td', { style: adminTdStyle }, p.sales || 0),
                    adminReact.createElement('td', { style: adminTdStyle },
                      p.status === 'on_sale'
                        ? adminBadge('在售', '#52c41a')
                        : adminBadge('下架', '#999')
                    ),
                    adminReact.createElement('td', { style: adminTdStyle },
                      adminBtnGhost('改价', function () { editPrice(p.id); }),
                      p.status === 'on_sale'
                        ? adminBtn('下架', function () { toggleStatus(p.id); }, 'warning')
                        : adminBtn('上架', function () { toggleStatus(p.id); }, 'success')
                    )
                  );
                })
          )
        )
      )
    )
  );
}

// ========== 订单管理 ==========
function MallOrdersView(props) {
  var showToast = props.showToast;
  var ordersState = useState([]);
  var orders = ordersState[0];
  var statusState = useState('all');

  function loadOrders() {
    try {
      var mallOrders = adminLsGet('jcw_mall_orders', []) || [];
      var otherOrders = adminLsGet('jcw_orders', []) || [];
      var all = mallOrders.concat(otherOrders);
      if (statusState[0] !== 'all') all = all.filter(function (o) { return o.status === statusState[0]; });
      all.sort(function (a, b) { return new Date(b.created_at || 0) - new Date(a.created_at || 0); });
      ordersState[1](all);
    } catch (e) { ordersState[1]([]); }
  }

  useEffect(function () { loadOrders(); }, [statusState[0]]);

  function updateOrderStatus(id, status) {
    if (!confirm('确定将订单状态更新为：' + status + '？')) return;
    try {
      var mallOrders = adminLsGet('jcw_mall_orders', []) || [];
      var otherOrders = adminLsGet('jcw_orders', []) || [];
      var found = false;
      for (var i = 0; i < mallOrders.length; i++) {
        if (mallOrders[i].id === id) { mallOrders[i].status = status; found = true; }
      }
      if (!found) {
        for (var j = 0; j < otherOrders.length; j++) {
          if (otherOrders[j].id === id) { otherOrders[j].status = status; found = true; }
        }
      }
      adminLsSet('jcw_mall_orders', mallOrders);
      adminLsSet('jcw_orders', otherOrders);
      showToast('状态已更新');
      loadOrders();
    } catch (e) { showToast('操作失败'); }
  }

  var typeLabel = { physical: '实物', virtual: '虚拟', service: '服务', member: '会员', premium: '靓号' };
  var statusLabel = { pending: '待付款', paid: '待发货', shipped: '待收货', completed: '已完成', cancelled: '已取消' };
  var statusColor = { pending: '#ff9500', paid: '#1890ff', shipped: '#722ed1', completed: '#52c41a', cancelled: '#999' };

  return adminReact.createElement('div', null,
    adminReact.createElement('div', { style: {
      background: '#fff', borderRadius: 8, padding: 12, marginBottom: 12,
      display: 'flex', gap: 10, alignItems: 'center',
    }},
      adminReact.createElement('select', {
        value: statusState[0],
        onChange: function (e) { statusState[1](e.target.value); },
        style: { height: 32, padding: '0 8px', border: '1px solid #d9d9d9', borderRadius: 4, fontSize: 13 },
      },
        adminReact.createElement('option', { value: 'all' }, '全部状态'),
        adminReact.createElement('option', { value: 'pending' }, '待付款'),
        adminReact.createElement('option', { value: 'paid' }, '待发货/服务'),
        adminReact.createElement('option', { value: 'shipped' }, '待收货'),
        adminReact.createElement('option', { value: 'completed' }, '已完成'),
        adminReact.createElement('option', { value: 'cancelled' }, '已取消'),
      ),
      adminReact.createElement('div', { style: { flex: 1 } }),
      adminReact.createElement('div', { style: { fontSize: 12, color: '#999' } }, '共 ' + orders.length + ' 条订单')
    ),

    adminReact.createElement('div', { style: adminCardStyle, padding: 0, overflow: 'hidden' },
      adminReact.createElement('div', { style: { overflowX: 'auto' } },
        adminReact.createElement('table', { style: adminTableStyle },
          adminReact.createElement('thead', null,
            adminReact.createElement('tr', null,
              adminReact.createElement('th', { style: adminThStyle }, '订单号'),
              adminReact.createElement('th', { style: adminThStyle }, '商品'),
              adminReact.createElement('th', { style: adminThStyle }, '类型'),
              adminReact.createElement('th', { style: adminThStyle }, '金额'),
              adminReact.createElement('th', { style: adminThStyle }, '用户ID'),
              adminReact.createElement('th', { style: adminThStyle }, '状态'),
              adminReact.createElement('th', { style: adminThStyle }, '时间'),
              adminReact.createElement('th', { style: adminThStyle }, '操作'),
            )
          ),
          adminReact.createElement('tbody', null,
            orders.length === 0
              ? adminReact.createElement('tr', null,
                  adminReact.createElement('td', { style: { ...adminTdStyle, textAlign: 'center', padding: 30, color: '#999' }, colSpan: 8 }, '暂无订单数据')
                )
              : orders.map(function (o) {
                  var st = o.status || 'pending';
                  return adminReact.createElement('tr', { key: o.id },
                    adminReact.createElement('td', { style: { ...adminTdStyle, fontSize: 11, fontFamily: 'monospace' } }, o.order_no || ('ORD' + o.id)),
                    adminReact.createElement('td', { style: { ...adminTdStyle, maxWidth: 200 } },
                      adminReact.createElement('div', { style: {
                        fontSize: 12, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
                      }}, o.product_name || (o.items && o.items[0] && o.items[0].product_title) || '商城商品')
                    ),
                    adminReact.createElement('td', { style: adminTdStyle }, adminBadge(typeLabel[o.type] || o.type || '商城', '#1890ff')),
                    adminReact.createElement('td', { style: { ...adminTdStyle, color: '#ff4d4f', fontWeight: 500 } }, fmtMoney(o.total_amount || o.amount || 0)),
                    adminReact.createElement('td', { style: adminTdStyle }, o.user_id || '-'),
                    adminReact.createElement('td', { style: adminTdStyle }, adminBadge(statusLabel[st] || st, statusColor[st] || '#999')),
                    adminReact.createElement('td', { style: { ...adminTdStyle, fontSize: 11, color: '#999' } }, fmtDateTime(o.created_at)),
                    adminReact.createElement('td', { style: adminTdStyle },
                      st === 'pending' && adminBtn('标记已付', function () { updateOrderStatus(o.id, 'paid'); }, 'success'),
                      st === 'paid' && adminBtn('发货', function () { updateOrderStatus(o.id, 'shipped'); }, 'success'),
                      st === 'shipped' && adminBtn('完成', function () { updateOrderStatus(o.id, 'completed'); }, 'success'),
                      st !== 'cancelled' && st !== 'completed' && adminBtnGhost('取消', function () { updateOrderStatus(o.id, 'cancelled'); }, '#ff4d4f')
                    )
                  );
                })
          )
        )
      )
    )
  );
}

// ========== 靓号管理 ==========
function PrettyNumbersView(props) {
  var showToast = props.showToast;
  var numsState = useState([]);
  var nums = numsState[0];
  var levelState = useState('all');

  function loadNums() {
    try {
      var list = adminLsGet('jcw_mall_pretty_numbers', []) || [];
      if (!list.length) {
        // 旧的 premium_nums 也读入
        var old = adminLsGet('jcw_premium_numbers', []) || [];
        list = old.map(function (n, i) {
          return {
            id: n.id || 100 + i,
            number: n.number,
            price: n.price,
            level: numberToLevel(n.number),
            status: n.status === 'available' ? 'on_sale' : 'sold',
            description: n.description,
          };
        });
      }
      if (levelState[0] !== 'all') list = list.filter(function (n) { return n.level === levelState[0]; });
      numsState[1](list);
    } catch (e) { numsState[1]([]); }
  }

  function numberToLevel(numStr) {
    var s = String(numStr || '').replace(/[^0-9]/g, '');
    // 简单判断
    var counts = {};
    for (var i = 0; i < s.length; i++) counts[s[i]] = (counts[s[i]] || 0) + 1;
    var maxCount = 0;
    for (var k in counts) if (counts[k] > maxCount) maxCount = counts[k];
    if (maxCount >= 4) return 'AAAA';
    if (maxCount >= 3) return 'AAA';
    if (maxCount >= 2) return 'AA';
    return 'A';
  }

  useEffect(function () { loadNums(); }, [levelState[0]]);

  function addNumber() {
    var num = prompt('输入靓号：', '');
    if (!num) return;
    var priceStr = prompt('输入价格：', '99');
    var price = parseFloat(priceStr);
    if (isNaN(price)) { showToast('价格无效'); return; }
    var level = prompt('等级 (A/AA/AAA/AAAA)：', numberToLevel(num));
    try {
      var list = adminLsGet('jcw_mall_pretty_numbers', []) || [];
      var newId = Math.max.apply(null, list.map(function (n) { return n.id; }).concat([0])) + 1;
      list.push({
        id: newId,
        number: num,
        price: price,
        level: level || 'A',
        status: 'on_sale',
        description: prompt('描述（可选）：', '') || '',
      });
      adminLsSet('jcw_mall_pretty_numbers', list);
      showToast('添加成功');
      loadNums();
    } catch (e) { showToast('添加失败'); }
  }

  function toggleStatus(id) {
    try {
      var list = adminLsGet('jcw_mall_pretty_numbers', []) || [];
      for (var i = 0; i < list.length; i++) {
        if (list[i].id === id) list[i].status = list[i].status === 'on_sale' ? 'sold' : 'on_sale';
      }
      adminLsSet('jcw_mall_pretty_numbers', list);
      showToast('操作成功');
      loadNums();
    } catch (e) { showToast('操作失败'); }
  }

  function editPrice(id) {
    var list = adminLsGet('jcw_mall_pretty_numbers', []) || [];
    var n = list.find(function (x) { return x.id === id; });
    if (!n) return;
    var np = prompt('修改价格：', String(n.price));
    if (np === null) return;
    var num = parseFloat(np);
    if (isNaN(num) || num < 0) { showToast('价格无效'); return; }
    try {
      for (var i = 0; i < list.length; i++) {
        if (list[i].id === id) list[i].price = num;
      }
      adminLsSet('jcw_mall_pretty_numbers', list);
      showToast('价格已更新');
      loadNums();
    } catch (e) { showToast('操作失败'); }
  }

  var levelColor = { A: '#9ca3af', AA: '#60a5fa', AAA: '#fbbf24', AAAA: '#f472b6' };

  return adminReact.createElement('div', null,
    adminReact.createElement('div', { style: {
      background: '#fff', borderRadius: 8, padding: 12, marginBottom: 12,
      display: 'flex', gap: 10, alignItems: 'center',
    }},
      adminReact.createElement('select', {
        value: levelState[0],
        onChange: function (e) { levelState[1](e.target.value); },
        style: { height: 32, padding: '0 8px', border: '1px solid #d9d9d9', borderRadius: 4, fontSize: 13 },
      },
        adminReact.createElement('option', { value: 'all' }, '全部等级'),
        adminReact.createElement('option', { value: 'A' }, 'A级'),
        adminReact.createElement('option', { value: 'AA' }, 'AA级'),
        adminReact.createElement('option', { value: 'AAA' }, 'AAA级'),
        adminReact.createElement('option', { value: 'AAAA' }, 'AAAA级'),
      ),
      adminReact.createElement('div', { style: { flex: 1 } }),
      adminReact.createElement('div', {
        onClick: addNumber,
        style: {
          padding: '6px 16px', borderRadius: 4,
          background: '#1890ff', color: '#fff',
          fontSize: 12, cursor: 'pointer',
        },
      }, '+ 新增靓号'),
      adminReact.createElement('div', { style: { fontSize: 12, color: '#999' } }, '共 ' + nums.length + ' 个')
    ),

    adminReact.createElement('div', { style: adminCardStyle, padding: 0, overflow: 'hidden' },
      adminReact.createElement('div', { style: { overflowX: 'auto' } },
        adminReact.createElement('table', { style: adminTableStyle },
          adminReact.createElement('thead', null,
            adminReact.createElement('tr', null,
              adminReact.createElement('th', { style: adminThStyle }, 'ID'),
              adminReact.createElement('th', { style: adminThStyle }, '靓号'),
              adminReact.createElement('th', { style: adminThStyle }, '等级'),
              adminReact.createElement('th', { style: adminThStyle }, '价格'),
              adminReact.createElement('th', { style: adminThStyle }, '描述'),
              adminReact.createElement('th', { style: adminThStyle }, '状态'),
              adminReact.createElement('th', { style: adminThStyle }, '操作'),
            )
          ),
          adminReact.createElement('tbody', null,
            nums.length === 0
              ? adminReact.createElement('tr', null,
                  adminReact.createElement('td', { style: { ...adminTdStyle, textAlign: 'center', padding: 30, color: '#999' }, colSpan: 7 }, '暂无靓号数据')
                )
              : nums.map(function (n) {
                  return adminReact.createElement('tr', { key: n.id },
                    adminReact.createElement('td', { style: adminTdStyle }, n.id),
                    adminReact.createElement('td', { style: { ...adminTdStyle, fontSize: 16, fontWeight: 700, letterSpacing: 1, color: '#333' } }, n.number),
                    adminReact.createElement('td', { style: adminTdStyle },
                      adminBadge((n.level || 'A') + '级', levelColor[n.level] || '#999')
                    ),
                    adminReact.createElement('td', { style: { ...adminTdStyle, color: '#ff4d4f', fontWeight: 500 } }, fmtMoney(n.price)),
                    adminReact.createElement('td', { style: { ...adminTdStyle, fontSize: 11, color: '#999', maxWidth: 200 } },
                      adminReact.createElement('div', { style: { overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } }, n.description || '-')
                    ),
                    adminReact.createElement('td', { style: adminTdStyle },
                      n.status === 'on_sale' || n.status === 'available'
                        ? adminBadge('在售', '#52c41a')
                        : adminBadge('已售', '#999')
                    ),
                    adminReact.createElement('td', { style: adminTdStyle },
                      adminBtnGhost('改价', function () { editPrice(n.id); }),
                      (n.status === 'on_sale' || n.status === 'available')
                        ? adminBtn('下架', function () { toggleStatus(n.id); }, 'warning')
                        : adminBtn('上架', function () { toggleStatus(n.id); }, 'success')
                    )
                  );
                })
          )
        )
      )
    )
  );
}

// ========== 纪念堂管理 ==========
function MemorialHallsView(props) {
  var showToast = props.showToast;
  var hallsState = useState([]);
  var halls = hallsState[0];
  var kwState = useState('');

  function loadHalls() {
    try {
      var list = adminLsGet('jcw_memorial_halls', []) || [];
      if (!Array.isArray(list)) list = list.items || [];
      if (kwState[0]) {
        var kw = kwState[0];
        list = list.filter(function (h) { return (h.name || '').indexOf(kw) >= 0; });
      }
      hallsState[1](list);
    } catch (e) { hallsState[1]([]); }
  }

  useEffect(function () { loadHalls(); }, [kwState[0]]);

  function deleteHall(id) {
    if (!confirm('确定删除该纪念堂？此操作不可恢复！')) return;
    try {
      var list = adminLsGet('jcw_memorial_halls', []) || [];
      if (!Array.isArray(list)) list = list.items || [];
      list = list.filter(function (h) { return h.id !== id; });
      adminLsSet('jcw_memorial_halls', list);
      showToast('已删除');
      loadHalls();
    } catch (e) { showToast('删除失败'); }
  }

  return adminReact.createElement('div', null,
    adminReact.createElement('div', { style: {
      background: '#fff', borderRadius: 8, padding: 12, marginBottom: 12,
      display: 'flex', gap: 10, alignItems: 'center',
    }},
      adminReact.createElement('input', {
        placeholder: '搜索纪念堂名称', value: kwState[0],
        onChange: function (e) { kwState[1](e.target.value); },
        style: { width: 300, height: 32, padding: '0 10px', border: '1px solid #d9d9d9', borderRadius: 4, fontSize: 13 },
      }),
      adminReact.createElement('div', { style: { flex: 1 } }),
      adminReact.createElement('div', { style: { fontSize: 12, color: '#999' } }, '共 ' + halls.length + ' 个纪念堂')
    ),

    adminReact.createElement('div', { style: adminCardStyle, padding: 0, overflow: 'hidden' },
      adminReact.createElement('div', { style: { overflowX: 'auto' } },
        adminReact.createElement('table', { style: adminTableStyle },
          adminReact.createElement('thead', null,
            adminReact.createElement('tr', null,
              adminReact.createElement('th', { style: adminThStyle }, 'ID'),
              adminReact.createElement('th', { style: adminThStyle }, '纪念堂名称'),
              adminReact.createElement('th', { style: adminThStyle }, '类型'),
              adminReact.createElement('th', { style: adminThStyle }, '创建者'),
              adminReact.createElement('th', { style: adminThStyle }, '留言/祭品'),
              adminReact.createElement('th', { style: adminThStyle }, '创建时间'),
              adminReact.createElement('th', { style: adminThStyle }, '操作'),
            )
          ),
          adminReact.createElement('tbody', null,
            halls.length === 0
              ? adminReact.createElement('tr', null,
                  adminReact.createElement('td', { style: { ...adminTdStyle, textAlign: 'center', padding: 30, color: '#999' }, colSpan: 7 }, '暂无纪念堂数据')
                )
              : halls.map(function (h) {
                  return adminReact.createElement('tr', { key: h.id },
                    adminReact.createElement('td', { style: adminTdStyle }, h.id),
                    adminReact.createElement('td', { style: adminTdStyle },
                      adminReact.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 8 } },
                        adminReact.createElement('div', { style: {
                          width: 36, height: 36, borderRadius: 6,
                          background: 'linear-gradient(135deg, #f5f7fa, #e8ecf1)',
                          display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 16,
                        }}, h.theme === 'artistic' ? '🎨' : h.theme === 'natural' ? '🌿' : '🕯️'),
                        adminReact.createElement('div', null,
                          adminReact.createElement('div', { style: { fontSize: 13 } }, h.name || ''),
                          h.deceased_name && adminReact.createElement('div', { style: { fontSize: 10, color: '#999' } }, '逝者：' + h.deceased_name)
                        )
                      )
                    ),
                    adminReact.createElement('td', { style: adminTdStyle },
                      adminBadge(h.template || h.theme || '传统', '#722ed1')
                    ),
                    adminReact.createElement('td', { style: adminTdStyle }, h.owner_name || ('用户' + h.user_id)),
                    adminReact.createElement('td', { style: adminTdStyle }, (h.message_count || 0) + ' / ' + (h.offering_count || 0)),
                    adminReact.createElement('td', { style: { ...adminTdStyle, fontSize: 11, color: '#999' } }, fmtDateTime(h.created_at)),
                    adminReact.createElement('td', { style: adminTdStyle },
                      adminBtn('删除', function () { deleteHall(h.id); }, 'danger')
                    )
                  );
                })
          )
        )
      )
    )
  );
}

// ========== 祠堂管理 ==========
function TemplesView(props) {
  var showToast = props.showToast;
  var templesState = useState([]);
  var temples = templesState[0];
  var kwState = useState('');

  function loadTemples() {
    try {
      var list = adminLsGet('jcw_temples', []) || [];
      if (!Array.isArray(list)) list = list.items || [];
      if (kwState[0]) {
        var kw = kwState[0];
        list = list.filter(function (t) { return (t.name || '').indexOf(kw) >= 0 || (t.surname || '').indexOf(kw) >= 0; });
      }
      templesState[1](list);
    } catch (e) { templesState[1]([]); }
  }

  useEffect(function () { loadTemples(); }, [kwState[0]]);

  function deleteTemple(id) {
    if (!confirm('确定删除该祠堂？')) return;
    try {
      var list = adminLsGet('jcw_temples', []) || [];
      list = list.filter(function (t) { return t.id !== id; });
      adminLsSet('jcw_temples', list);
      showToast('已删除');
      loadTemples();
    } catch (e) { showToast('删除失败'); }
  }

  return adminReact.createElement('div', null,
    adminReact.createElement('div', { style: {
      background: '#fff', borderRadius: 8, padding: 12, marginBottom: 12,
      display: 'flex', gap: 10, alignItems: 'center',
    }},
      adminReact.createElement('input', {
        placeholder: '搜索祠堂名称/姓氏', value: kwState[0],
        onChange: function (e) { kwState[1](e.target.value); },
        style: { width: 300, height: 32, padding: '0 10px', border: '1px solid #d9d9d9', borderRadius: 4, fontSize: 13 },
      }),
      adminReact.createElement('div', { style: { flex: 1 } }),
      adminReact.createElement('div', { style: { fontSize: 12, color: '#999' } }, '共 ' + temples.length + ' 个祠堂')
    ),

    adminReact.createElement('div', { style: adminCardStyle, padding: 0, overflow: 'hidden' },
      adminReact.createElement('div', { style: { overflowX: 'auto' } },
        adminReact.createElement('table', { style: adminTableStyle },
          adminReact.createElement('thead', null,
            adminReact.createElement('tr', null,
              adminReact.createElement('th', { style: adminThStyle }, 'ID'),
              adminReact.createElement('th', { style: adminThStyle }, '祠堂名称'),
              adminReact.createElement('th', { style: adminThStyle }, '姓氏'),
              adminReact.createElement('th', { style: adminThStyle }, '创建者'),
              adminReact.createElement('th', { style: adminThStyle }, '成员数'),
              adminReact.createElement('th', { style: adminThStyle }, '创建时间'),
              adminReact.createElement('th', { style: adminThStyle }, '操作'),
            )
          ),
          adminReact.createElement('tbody', null,
            temples.length === 0
              ? adminReact.createElement('tr', null,
                  adminReact.createElement('td', { style: { ...adminTdStyle, textAlign: 'center', padding: 30, color: '#999' }, colSpan: 7 }, '暂无祠堂数据')
                )
              : temples.map(function (t) {
                  return adminReact.createElement('tr', { key: t.id },
                    adminReact.createElement('td', { style: adminTdStyle }, t.id),
                    adminReact.createElement('td', { style: adminTdStyle },
                      adminReact.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 8 } },
                        adminReact.createElement('div', { style: {
                          width: 36, height: 36, borderRadius: 6,
                          background: 'linear-gradient(135deg, #fa8c16, #ff4d4f)',
                          color: '#fff', fontWeight: 700, fontSize: 14,
                          display: 'flex', alignItems: 'center', justifyContent: 'center',
                        }}, (t.surname || t.name || '祠').charAt(0)),
                        t.name || '网上祠堂'
                      )
                    ),
                    adminReact.createElement('td', { style: adminTdStyle }, t.surname || '-'),
                    adminReact.createElement('td', { style: adminTdStyle }, t.founder_name || t.owner_name || ('用户' + t.user_id)),
                    adminReact.createElement('td', { style: adminTdStyle }, t.member_count || 0),
                    adminReact.createElement('td', { style: { ...adminTdStyle, fontSize: 11, color: '#999' } }, fmtDateTime(t.created_at)),
                    adminReact.createElement('td', { style: adminTdStyle },
                      adminBtn('删除', function () { deleteTemple(t.id); }, 'danger')
                    )
                  );
                })
          )
        )
      )
    )
  );
}

// ========== 陵园商家审核 ==========
function CemeteryAuditView(props) {
  var showToast = props.showToast;
  var listState = useState([]);
  var list = listState[0];

  function loadList() {
    try {
      var enterprises = adminLsGet('jcw_enterprises', []) || [];
      var cemeteries = enterprises.filter(function (e) { return e.template === 'cemetery' || e.category === 'cemetery'; });
      listState[1](cemeteries);
    } catch (e) { listState[1]([]); }
  }

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

  function toggleAudit(id, status) {
    try {
      var enterprises = adminLsGet('jcw_enterprises', []) || [];
      for (var i = 0; i < enterprises.length; i++) {
        if (enterprises[i].id === id) enterprises[i].audit_status = status;
      }
      adminLsSet('jcw_enterprises', enterprises);
      showToast(status === 'approved' ? '已通过' : '已驳回');
      loadList();
    } catch (e) { showToast('操作失败'); }
  }

  return adminReact.createElement('div', null,
    adminReact.createElement('div', { style: {
      background: '#fff', borderRadius: 8, padding: 12, marginBottom: 12,
      display: 'flex', justifyContent: 'space-between', alignItems: 'center',
    }},
      adminReact.createElement('div', { style: { fontSize: 12, color: '#666' } }, '陵园商家入驻审核'),
      adminReact.createElement('div', { style: { fontSize: 12, color: '#999' } }, '共 ' + list.length + ' 家陵园')
    ),

    adminReact.createElement('div', { style: adminCardStyle, padding: 0, overflow: 'hidden' },
      adminReact.createElement('div', { style: { overflowX: 'auto' } },
        adminReact.createElement('table', { style: adminTableStyle },
          adminReact.createElement('thead', null,
            adminReact.createElement('tr', null,
              adminReact.createElement('th', { style: adminThStyle }, 'ID'),
              adminReact.createElement('th', { style: adminThStyle }, '陵园名称'),
              adminReact.createElement('th', { style: adminThStyle }, '联系人'),
              adminReact.createElement('th', { style: adminThStyle }, '地址'),
              adminReact.createElement('th', { style: adminThStyle }, '评分'),
              adminReact.createElement('th', { style: adminThStyle }, '审核状态'),
              adminReact.createElement('th', { style: adminThStyle }, '操作'),
            )
          ),
          adminReact.createElement('tbody', null,
            list.length === 0
              ? adminReact.createElement('tr', null,
                  adminReact.createElement('td', { style: { ...adminTdStyle, textAlign: 'center', padding: 30, color: '#999' }, colSpan: 7 }, '暂无陵园商家数据')
                )
              : list.map(function (c) {
                  var st = c.audit_status || 'approved';
                  return adminReact.createElement('tr', { key: c.id },
                    adminReact.createElement('td', { style: adminTdStyle }, c.id),
                    adminReact.createElement('td', { style: adminTdStyle },
                      adminReact.createElement('div', { style: { fontSize: 13, fontWeight: 500 } }, c.name || ''),
                      c.level && adminReact.createElement('div', { style: { fontSize: 10, color: '#999' } }, c.level)
                    ),
                    adminReact.createElement('td', { style: adminTdStyle }, (c.contact || '') + ' ' + (c.phone || '')),
                    adminReact.createElement('td', { style: { ...adminTdStyle, maxWidth: 200, fontSize: 11, color: '#666' } }, c.address || '-'),
                    adminReact.createElement('td', { style: adminTdStyle }, (c.rating || 0).toFixed(1) + ' (' + (c.review_count || 0) + ')'),
                    adminReact.createElement('td', { style: adminTdStyle },
                      st === 'approved' ? adminBadge('已通过', '#52c41a')
                        : st === 'pending' ? adminBadge('待审核', '#faad14')
                        : adminBadge('已驳回', '#ff4d4f')
                    ),
                    adminReact.createElement('td', { style: adminTdStyle },
                      st !== 'approved' && adminBtn('通过', function () { toggleAudit(c.id, 'approved'); }, 'success'),
                      st !== 'rejected' && adminBtnGhost('驳回', function () { toggleAudit(c.id, 'rejected'); }, '#ff4d4f')
                    )
                  );
                })
          )
        )
      )
    )
  );
}

// ========== 企业黄页列表 ==========
function EnterpriseListView(props) {
  var showToast = props.showToast;
  var listState = useState([]);
  var kwState = useState('');

  function loadList() {
    try {
      var list = adminLsGet('jcw_enterprises', []) || [];
      if (kwState[0]) {
        var kw = kwState[0];
        list = list.filter(function (e) { return (e.name || '').indexOf(kw) >= 0; });
      }
      listState[1](list);
    } catch (e) { listState[1]([]); }
  }

  useEffect(function () { loadList(); }, [kwState[0]]);

  function deleteEnt(id) {
    if (!confirm('确定删除该企业？')) return;
    try {
      var list = adminLsGet('jcw_enterprises', []) || [];
      list = list.filter(function (e) { return e.id !== id; });
      adminLsSet('jcw_enterprises', list);
      showToast('已删除');
      loadList();
    } catch (e) { showToast('删除失败'); }
  }

  return adminReact.createElement('div', null,
    adminReact.createElement('div', { style: {
      background: '#fff', borderRadius: 8, padding: 12, marginBottom: 12,
      display: 'flex', gap: 10, alignItems: 'center',
    }},
      adminReact.createElement('input', {
        placeholder: '搜索企业名称', value: kwState[0],
        onChange: function (e) { kwState[1](e.target.value); },
        style: { width: 300, height: 32, padding: '0 10px', border: '1px solid #d9d9d9', borderRadius: 4, fontSize: 13 },
      }),
      adminReact.createElement('div', { style: { flex: 1 } }),
      adminReact.createElement('div', { style: { fontSize: 12, color: '#999' } }, '共 ' + listState[0].length + ' 家企业')
    ),

    adminReact.createElement('div', { style: adminCardStyle, padding: 0, overflow: 'hidden' },
      adminReact.createElement('div', { style: { overflowX: 'auto' } },
        adminReact.createElement('table', { style: adminTableStyle },
          adminReact.createElement('thead', null,
            adminReact.createElement('tr', null,
              adminReact.createElement('th', { style: adminThStyle }, 'ID'),
              adminReact.createElement('th', { style: adminThStyle }, '企业名称'),
              adminReact.createElement('th', { style: adminThStyle }, '分类'),
              adminReact.createElement('th', { style: adminThStyle }, '联系人'),
              adminReact.createElement('th', { style: adminThStyle }, '电话'),
              adminReact.createElement('th', { style: adminThStyle }, '所有者'),
              adminReact.createElement('th', { style: adminThStyle }, '操作'),
            )
          ),
          adminReact.createElement('tbody', null,
            listState[0].length === 0
              ? adminReact.createElement('tr', null,
                  adminReact.createElement('td', { style: { ...adminTdStyle, textAlign: 'center', padding: 30, color: '#999' }, colSpan: 7 }, '暂无企业数据')
                )
              : listState[0].map(function (e) {
                  return adminReact.createElement('tr', { key: e.id },
                    adminReact.createElement('td', { style: adminTdStyle }, e.id),
                    adminReact.createElement('td', { style: { ...adminTdStyle, maxWidth: 240 } },
                      adminReact.createElement('div', { style: { fontSize: 13, fontWeight: 500, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } }, e.name || '')
                    ),
                    adminReact.createElement('td', { style: adminTdStyle }, adminBadge(e.category || 'general', e.template === 'cemetery' ? '#fa8c16' : '#1890ff')),
                    adminReact.createElement('td', { style: adminTdStyle }, e.contact || '-'),
                    adminReact.createElement('td', { style: adminTdStyle }, e.phone || '-'),
                    adminReact.createElement('td', { style: adminTdStyle }, e.owner_name || ('用户' + e.user_id)),
                    adminReact.createElement('td', { style: adminTdStyle },
                      adminBtn('删除', function () { deleteEnt(e.id); }, 'danger')
                    )
                  );
                })
          )
        )
      )
    )
  );
}

// ========== 企业入驻审核 ==========
function EnterpriseAuditView(props) {
  var showToast = props.showToast;
  var listState = useState([]);

  function loadList() {
    try {
      var list = adminLsGet('jcw_enterprises', []) || [];
      list = list.filter(function (e) { return e.audit_status === 'pending' || !e.audit_status; });
      // 实际上所有已有的都视为已通过，演示用
      listState[1](list.filter(function (e) { return e.audit_status === 'pending'; }));
    } catch (e) { listState[1]([]); }
  }

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

  function audit(id, pass) {
    try {
      var list = adminLsGet('jcw_enterprises', []) || [];
      for (var i = 0; i < list.length; i++) {
        if (list[i].id === id) list[i].audit_status = pass ? 'approved' : 'rejected';
      }
      adminLsSet('jcw_enterprises', list);
      showToast(pass ? '已通过' : '已驳回');
      loadList();
    } catch (e) { showToast('操作失败'); }
  }

  return adminReact.createElement('div', null,
    adminReact.createElement('div', { style: {
      background: '#fff', borderRadius: 8, padding: 12, marginBottom: 12,
      fontSize: 12, color: '#666',
    }}, '待审核企业：' + listState[0].length + ' 家'),

    adminReact.createElement('div', { style: adminCardStyle, padding: 0, overflow: 'hidden' },
      adminReact.createElement('div', { style: { overflowX: 'auto' } },
        adminReact.createElement('table', { style: adminTableStyle },
          adminReact.createElement('thead', null,
            adminReact.createElement('tr', null,
              adminReact.createElement('th', { style: adminThStyle }, 'ID'),
              adminReact.createElement('th', { style: adminThStyle }, '企业名称'),
              adminReact.createElement('th', { style: adminThStyle }, '联系人'),
              adminReact.createElement('th', { style: adminThStyle }, '电话'),
              adminReact.createElement('th', { style: adminThStyle }, '地址'),
              adminReact.createElement('th', { style: adminThStyle }, '操作'),
            )
          ),
          adminReact.createElement('tbody', null,
            listState[0].length === 0
              ? adminReact.createElement('tr', null,
                  adminReact.createElement('td', { style: { ...adminTdStyle, textAlign: 'center', padding: 30, color: '#999' }, colSpan: 6 }, '暂无待审核企业')
                )
              : listState[0].map(function (e) {
                  return adminReact.createElement('tr', { key: e.id },
                    adminReact.createElement('td', { style: adminTdStyle }, e.id),
                    adminReact.createElement('td', { style: adminTdStyle }, e.name || ''),
                    adminReact.createElement('td', { style: adminTdStyle }, e.contact || '-'),
                    adminReact.createElement('td', { style: adminTdStyle }, e.phone || '-'),
                    adminReact.createElement('td', { style: { ...adminTdStyle, fontSize: 11, color: '#999' } }, e.address || '-'),
                    adminReact.createElement('td', { style: adminTdStyle },
                      adminBtn('通过', function () { audit(e.id, true); }, 'success'),
                      adminBtnGhost('驳回', function () { audit(e.id, false); }, '#ff4d4f')
                    )
                  );
                })
          )
        )
      )
    )
  );
}

// ========== 财务订单 ==========
function FinanceOrdersView(props) {
  var showToast = props.showToast;
  var tabState = useState('all');
  var tab = tabState[0];

  var ordersState = useState([]);
  var orders = ordersState[0];

  function loadOrders() {
    try {
      var list = adminLsGet('jcw_orders', []) || [];
      if (tab !== 'all') list = list.filter(function (o) { return o.type === tab; });
      list.sort(function (a, b) { return new Date(b.created_at || 0) - new Date(a.created_at || 0); });
      ordersState[1](list);
    } catch (e) { ordersState[1]([]); }
  }

  useEffect(function () { loadOrders(); }, [tab]);

  var typeLabel = {
    all: '全部', member: '会员购买', premium: '靓号购买',
    reward: '打赏', archive: '付费存档', article: '付费阅读',
    download: '付费下载', offering: '祭品订单',
  };

  var tabs = ['all', 'member', 'premium', 'reward', 'archive', 'offering'];

  return adminReact.createElement('div', null,
    adminReact.createElement('div', { style: {
      background: '#fff', borderRadius: 8, padding: 12, marginBottom: 12,
      display: 'flex', gap: 4, alignItems: 'center', flexWrap: 'wrap',
    }},
      tabs.map(function (t) {
        return adminReact.createElement('div', {
          key: t,
          onClick: function () { tabState[1](t); },
          style: {
            padding: '6px 14px', borderRadius: 14, fontSize: 12,
            cursor: 'pointer',
            background: tab === t ? '#1890ff' : '#f5f5f5',
            color: tab === t ? '#fff' : '#666',
          },
        }, typeLabel[t] || t);
      }),
      adminReact.createElement('div', { style: { flex: 1 } }),
      adminReact.createElement('div', { style: { fontSize: 12, color: '#999' } }, '共 ' + orders.length + ' 条')
    ),

    adminReact.createElement('div', { style: adminCardStyle, padding: 0, overflow: 'hidden' },
      adminReact.createElement('div', { style: { overflowX: 'auto' } },
        adminReact.createElement('table', { style: adminTableStyle },
          adminReact.createElement('thead', null,
            adminReact.createElement('tr', null,
              adminReact.createElement('th', { style: adminThStyle }, '订单号'),
              adminReact.createElement('th', { style: adminThStyle }, '商品'),
              adminReact.createElement('th', { style: adminThStyle }, '类型'),
              adminReact.createElement('th', { style: adminThStyle }, '金额'),
              adminReact.createElement('th', { style: adminThStyle }, '用户ID'),
              adminReact.createElement('th', { style: adminThStyle }, '状态'),
              adminReact.createElement('th', { style: adminThStyle }, '时间'),
            )
          ),
          adminReact.createElement('tbody', null,
            orders.length === 0
              ? adminReact.createElement('tr', null,
                  adminReact.createElement('td', { style: { ...adminTdStyle, textAlign: 'center', padding: 30, color: '#999' }, colSpan: 7 }, '暂无订单数据')
                )
              : orders.map(function (o) {
                  return adminReact.createElement('tr', { key: o.id },
                    adminReact.createElement('td', { style: { ...adminTdStyle, fontSize: 11, fontFamily: 'monospace' } }, o.order_no || ('ORD' + o.id)),
                    adminReact.createElement('td', { style: adminTdStyle }, o.product_name || '-'),
                    adminReact.createElement('td', { style: adminTdStyle }, adminBadge(typeLabel[o.type] || o.type, '#1890ff')),
                    adminReact.createElement('td', { style: { ...adminTdStyle, color: '#ff4d4f', fontWeight: 500 } }, fmtMoney(o.amount)),
                    adminReact.createElement('td', { style: adminTdStyle }, o.user_id || '-'),
                    adminReact.createElement('td', { style: adminTdStyle },
                      o.status === 'completed' ? adminBadge('已完成', '#52c41a')
                        : o.status === 'pending' ? adminBadge('待付款', '#faad14')
                        : adminBadge(o.status || '-', '#999')
                    ),
                    adminReact.createElement('td', { style: { ...adminTdStyle, fontSize: 11, color: '#999' } }, fmtDateTime(o.created_at))
                  );
                })
          )
        )
      )
    )
  );
}

// ========== 提现审核 ==========
function WithdrawView(props) {
  var showToast = props.showToast;
  var commissions = adminLsGet('jcw_commission_records', []) || [];
  // 模拟一些提现申请
  var withdraws = commissions.filter(function (c) { return c.status === 'withdrawing'; }) || [];

  return adminReact.createElement('div', null,
    adminReact.createElement('div', { style: {
      background: '#fff', borderRadius: 8, padding: 12, marginBottom: 12,
      fontSize: 12, color: '#666',
    }}, '待审核提现申请：' + withdraws.length + ' 条'),

    adminReact.createElement('div', { style: adminCardStyle },
      adminReact.createElement('div', { style: {
        textAlign: 'center', padding: '40px 20px', color: '#999', fontSize: 13,
      }},
        adminReact.createElement('div', { style: { fontSize: 36, marginBottom: 12 } }, '💰'),
        adminReact.createElement('div', null, '暂无提现申请'),
        adminReact.createElement('div', { style: { fontSize: 11, marginTop: 6, color: '#bbb' } },
          '用户发起提现后将在此处显示，可审核通过或驳回'
        )
      )
    )
  );
}

// ========== 余额流水 ==========
function BalanceFlowView(props) {
  var showToast = props.showToast;

  var flows = [];
  try {
    var commissions = adminLsGet('jcw_commission_records', []) || [];
    var orders = adminLsGet('jcw_orders', []) || [];
    var mallOrders = adminLsGet('jcw_mall_orders', []) || [];

    // 模拟一些流水记录
    var all = [];
    for (var i = 0; i < orders.length; i++) {
      if (orders[i].status === 'completed') {
        all.push({
          id: 10000 + orders[i].id,
          user_id: orders[i].user_id,
          type: 'recharge',
          type_label: '充值',
          amount: orders[i].amount,
          direction: 'in',
          description: orders[i].product_name || '余额充值',
          created_at: orders[i].created_at,
        });
      }
    }
    all.sort(function (a, b) { return new Date(b.created_at || 0) - new Date(a.created_at || 0); });
    flows = all.slice(0, 50);
  } catch (e) {}

  return adminReact.createElement('div', null,
    adminReact.createElement('div', { style: {
      background: '#fff', borderRadius: 8, padding: 12, marginBottom: 12,
      fontSize: 12, color: '#666',
    }}, '余额变动流水（最近50条）'),

    adminReact.createElement('div', { style: adminCardStyle, padding: 0, overflow: 'hidden' },
      adminReact.createElement('div', { style: { overflowX: 'auto' } },
        adminReact.createElement('table', { style: adminTableStyle },
          adminReact.createElement('thead', null,
            adminReact.createElement('tr', null,
              adminReact.createElement('th', { style: adminThStyle }, '流水号'),
              adminReact.createElement('th', { style: adminThStyle }, '用户ID'),
              adminReact.createElement('th', { style: adminThStyle }, '类型'),
              adminReact.createElement('th', { style: adminThStyle }, '金额'),
              adminReact.createElement('th', { style: adminThStyle }, '说明'),
              adminReact.createElement('th', { style: adminThStyle }, '时间'),
            )
          ),
          adminReact.createElement('tbody', null,
            flows.length === 0
              ? adminReact.createElement('tr', null,
                  adminReact.createElement('td', { style: { ...adminTdStyle, textAlign: 'center', padding: 30, color: '#999' }, colSpan: 6 }, '暂无流水数据')
                )
              : flows.map(function (f) {
                  return adminReact.createElement('tr', { key: f.id },
                    adminReact.createElement('td', { style: { ...adminTdStyle, fontSize: 11, fontFamily: 'monospace' } }, 'FL' + f.id),
                    adminReact.createElement('td', { style: adminTdStyle }, f.user_id || '-'),
                    adminReact.createElement('td', { style: adminTdStyle },
                      adminBadge(f.type_label || f.type, f.direction === 'in' ? '#52c41a' : '#ff4d4f')
                    ),
                    adminReact.createElement('td', { style: {
                      ...adminTdStyle,
                      color: f.direction === 'in' ? '#52c41a' : '#ff4d4f',
                      fontWeight: 500,
                    }}, (f.direction === 'in' ? '+' : '-') + fmtMoney(f.amount)),
                    adminReact.createElement('td', { style: adminTdStyle }, f.description || '-'),
                    adminReact.createElement('td', { style: { ...adminTdStyle, fontSize: 11, color: '#999' } }, fmtDateTime(f.created_at))
                  );
                })
          )
        )
      )
    )
  );
}

// ========== SEO 设置 ==========
function SeoSettingsView(props) {
  var showToast = props.showToast;
  var navigate = props.navigate;
  var seoState = useState({});

  function loadSeo() {
    try {
      var s = adminLsGet('jcw_seo_settings', null);
      if (s) seoState[1](s);
    } catch (e) {}
  }

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

  function saveSeo() {
    try {
      adminLsSet('jcw_seo_settings', seoState[0]);
      // 通知 SEO 管理器
      if (window.SEO && window.SEO.load) {
        try { window.SEO.load(); } catch (e) {}
      }
      showToast('SEO 设置已保存');
    } catch (e) { showToast('保存失败'); }
  }

  function updateField(key, val) {
    var next = {};
    for (var k in seoState[0]) next[k] = seoState[0][k];
    next[key] = val;
    seoState[1](next);
  }

  var fields = [
    { key: 'site_title', label: '站点标题' },
    { key: 'site_description', label: '站点描述' },
    { key: 'site_keywords', label: '站点关键词' },
    { key: 'seo_home_title', label: '首页标题' },
    { key: 'seo_home_description', label: '首页描述' },
    { key: 'seo_home_keywords', label: '首页关键词' },
  ];

  return adminReact.createElement('div', null,
    adminReact.createElement('div', { style: {
      background: '#fff', borderRadius: 8, padding: 12, marginBottom: 12,
      display: 'flex', justifyContent: 'space-between', alignItems: 'center',
    }},
      adminReact.createElement('span', { style: { fontSize: 13, fontWeight: 500 } }, 'SEO 全局配置'),
      adminReact.createElement('span', {
        onClick: function () { try { navigate('admin-seo'); } catch (e) {} },
        style: { color: '#1890ff', fontSize: 12, cursor: 'pointer' },
      }, '前往旧版SEO管理 →')
    ),

    adminReact.createElement('div', { style: adminCardStyle },
      fields.map(function (f) {
        return adminReact.createElement('div', { key: f.key, style: { marginBottom: 14 } },
          adminReact.createElement('div', { style: { fontSize: 12, color: '#666', marginBottom: 6 } }, f.label),
          adminReact.createElement('input', {
            value: seoState[0][f.key] || '',
            onChange: function (e) { updateField(f.key, e.target.value); },
            style: {
              width: '100%', height: 36, padding: '0 12px',
              border: '1px solid #d9d9d9', borderRadius: 4, fontSize: 13,
              boxSizing: 'border-box',
            },
          })
        );
      }),
      adminReact.createElement('div', {
        onClick: saveSeo,
        style: {
          display: 'inline-block', padding: '8px 24px',
          borderRadius: 4, background: '#1890ff', color: '#fff',
          fontSize: 13, cursor: 'pointer', marginTop: 8,
        },
      }, '保存设置')
    )
  );
}

// ========== 客服管理 ==========
function CustomerServiceView(props) {
  var showToast = props.showToast;
  var csState = useState([]);
  var cs = csState[0];

  function loadCS() {
    try {
      var list = adminLsGet('jcw_customer_service', []) || [];
      list.sort(function (a, b) { return (a.sort || 0) - (b.sort || 0); });
      csState[1](list);
    } catch (e) { csState[1]([]); }
  }

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

  function addCS() {
    var nickname = prompt('客服昵称：', '');
    if (!nickname) return;
    var jiuLiaoId = prompt('久聊号：', 'cs_');
    if (!jiuLiaoId) return;
    var intro = prompt('简介：', '') || '';
    try {
      var list = adminLsGet('jcw_customer_service', []) || [];
      var newId = Math.max.apply(null, list.map(function (c) { return c.id; }).concat([100])) + 1;
      list.push({
        id: newId, nickname: nickname, avatar: '',
        jiuLiaoId: jiuLiaoId, intro: intro, status: 'online',
        sort: list.length + 1,
      });
      adminLsSet('jcw_customer_service', list);
      showToast('添加成功');
      loadCS();
    } catch (e) { showToast('添加失败'); }
  }

  function toggleStatus(id) {
    try {
      var list = adminLsGet('jcw_customer_service', []) || [];
      for (var i = 0; i < list.length; i++) {
        if (list[i].id === id) list[i].status = list[i].status === 'online' ? 'offline' : 'online';
      }
      adminLsSet('jcw_customer_service', list);
      showToast('状态已更新');
      loadCS();
    } catch (e) { showToast('操作失败'); }
  }

  function deleteCS(id) {
    if (!confirm('确定删除该客服？')) return;
    try {
      var list = adminLsGet('jcw_customer_service', []) || [];
      list = list.filter(function (c) { return c.id !== id; });
      adminLsSet('jcw_customer_service', list);
      showToast('已删除');
      loadCS();
    } catch (e) { showToast('删除失败'); }
  }

  return adminReact.createElement('div', null,
    adminReact.createElement('div', { style: {
      background: '#fff', borderRadius: 8, padding: 12, marginBottom: 12,
      display: 'flex', justifyContent: 'space-between', alignItems: 'center',
    }},
      adminReact.createElement('span', { style: { fontSize: 12, color: '#666' } }, '客服列表：' + cs.length + ' 个'),
      adminReact.createElement('div', {
        onClick: addCS,
        style: {
          padding: '6px 16px', borderRadius: 4,
          background: '#1890ff', color: '#fff',
          fontSize: 12, cursor: 'pointer',
        },
      }, '+ 新增客服')
    ),

    adminReact.createElement('div', { style: adminCardStyle, padding: 0, overflow: 'hidden' },
      adminReact.createElement('div', { style: { overflowX: 'auto' } },
        adminReact.createElement('table', { style: adminTableStyle },
          adminReact.createElement('thead', null,
            adminReact.createElement('tr', null,
              adminReact.createElement('th', { style: adminThStyle }, 'ID'),
              adminReact.createElement('th', { style: adminThStyle }, '昵称'),
              adminReact.createElement('th', { style: adminThStyle }, '久聊号'),
              adminReact.createElement('th', { style: adminThStyle }, '简介'),
              adminReact.createElement('th', { style: adminThStyle }, '状态'),
              adminReact.createElement('th', { style: adminThStyle }, '排序'),
              adminReact.createElement('th', { style: adminThStyle }, '操作'),
            )
          ),
          adminReact.createElement('tbody', null,
            cs.length === 0
              ? adminReact.createElement('tr', null,
                  adminReact.createElement('td', { style: { ...adminTdStyle, textAlign: 'center', padding: 30, color: '#999' }, colSpan: 7 }, '暂无客服数据')
                )
              : cs.map(function (c) {
                  return adminReact.createElement('tr', { key: c.id },
                    adminReact.createElement('td', { style: adminTdStyle }, c.id),
                    adminReact.createElement('td', { style: adminTdStyle }, c.nickname || ''),
                    adminReact.createElement('td', { style: adminTdStyle, fontFamily: 'monospace' }, c.jiuLiaoId || '-'),
                    adminReact.createElement('td', { style: { ...adminTdStyle, fontSize: 11, color: '#666', maxWidth: 200 } },
                      adminReact.createElement('div', { style: { overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } }, c.intro || '-')
                    ),
                    adminReact.createElement('td', { style: adminTdStyle },
                      c.status === 'online'
                        ? adminBadge('在线', '#52c41a')
                        : adminBadge('离线', '#999')
                    ),
                    adminReact.createElement('td', { style: adminTdStyle }, c.sort || 0),
                    adminReact.createElement('td', { style: adminTdStyle },
                      adminBtnGhost(c.status === 'online' ? '设离线' : '设在线', function () { toggleStatus(c.id); }),
                      adminBtn('删除', function () { deleteCS(c.id); }, 'danger')
                    )
                  );
                })
          )
        )
      )
    )
  );
}

// ========== 站点设置 ==========
function SiteSettingsView(props) {
  var showToast = props.showToast;
  var siteState = useState({
    site_name: '久存网',
    site_slogan: '永久保存你的记忆与故事',
    default_member_level: 'normal',
    register_enabled: true,
    site_icp: '蜀ICP备XXXXXXXX号',
    contact_email: 'contact@jiucun.com',
  });

  function loadSite() {
    try {
      var s = adminLsGet('jcw_site_settings', null);
      if (s) siteState[1](s);
    } catch (e) {}
  }

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

  function updateField(key, val) {
    var next = {};
    for (var k in siteState[0]) next[k] = siteState[0][k];
    next[key] = val;
    siteState[1](next);
  }

  function saveSite() {
    try {
      adminLsSet('jcw_site_settings', siteState[0]);
      showToast('站点设置已保存');
    } catch (e) { showToast('保存失败'); }
  }

  var fields = [
    { key: 'site_name', label: '站点名称' },
    { key: 'site_slogan', label: '站点标语' },
    { key: 'site_icp', label: 'ICP备案号' },
    { key: 'contact_email', label: '联系邮箱' },
    { key: 'default_member_level', label: '默认会员等级' },
  ];

  return adminReact.createElement('div', null,
    adminReact.createElement('div', { style: {
      background: '#fff', borderRadius: 8, padding: 12, marginBottom: 12,
      fontSize: 13, fontWeight: 500,
    }}, '站点基本设置'),

    adminReact.createElement('div', { style: adminCardStyle },
      fields.map(function (f) {
        return adminReact.createElement('div', { key: f.key, style: { marginBottom: 14 } },
          adminReact.createElement('div', { style: { fontSize: 12, color: '#666', marginBottom: 6 } }, f.label),
          f.key === 'default_member_level'
            ? adminReact.createElement('select', {
                value: siteState[0][f.key] || '',
                onChange: function (e) { updateField(f.key, e.target.value); },
                style: {
                  width: '100%', height: 36, padding: '0 12px',
                  border: '1px solid #d9d9d9', borderRadius: 4, fontSize: 13,
                  boxSizing: 'border-box',
                },
              },
                adminReact.createElement('option', { value: 'normal' }, '普通用户'),
                adminReact.createElement('option', { value: 'bronze' }, '青铜会员'),
                adminReact.createElement('option', { value: 'silver' }, '白银会员'),
                adminReact.createElement('option', { value: 'gold' }, '黄金会员'),
                adminReact.createElement('option', { value: 'diamond' }, '钻石会员'),
              )
            : adminReact.createElement('input', {
                value: siteState[0][f.key] || '',
                onChange: function (e) { updateField(f.key, e.target.value); },
                style: {
                  width: '100%', height: 36, padding: '0 12px',
                  border: '1px solid #d9d9d9', borderRadius: 4, fontSize: 13,
                  boxSizing: 'border-box',
                },
              })
        );
      }),
      adminReact.createElement('div', {
        onClick: saveSite,
        style: {
          display: 'inline-block', padding: '8px 24px',
          borderRadius: 4, background: '#1890ff', color: '#fff',
          fontSize: 13, cursor: 'pointer', marginTop: 8,
        },
      }, '保存设置')
    )
  );
}

// ========== 暴露到全局 ==========
try {
  Object.assign(window, { AdminPage: AdminPage });
} catch (e) {
  window.AdminPage = AdminPage;
}
