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

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

var useState = qaReact.useState;
var useEffect = qaReact.useEffect;
var Component = qaReact.Component;

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

// ========== 静态兜底数据 ==========
var STATIC_QUESTIONS = [
  { id: 1, title: '云端存储文件安全吗？', content: '想把一些重要文件存在云端，不知道安全性如何？', answer_count: 3, view_count: 128, category: '技术', author_name: '老王', created_at: '2024-01-15T10:00:00.000Z', bounty: 0 },
  { id: 2, title: '新手怎么开始理财？', content: '刚工作半年，想开始学习理财，有什么入门建议吗？', answer_count: 5, view_count: 256, category: '理财', author_name: '小金', created_at: '2024-01-14T09:00:00.000Z', bounty: 10 },
  { id: 3, title: '网络祭祀有什么讲究？', content: '想了解线上祭扫的相关习俗和注意事项。', answer_count: 2, view_count: 89, category: '生活', author_name: '阿明', created_at: '2024-01-13T08:00:00.000Z', bounty: 0 },
];

var STATIC_EXPERTS = [
  { id: 101, name: '张博士', title: 'AI 技术专家', specialty: '人工智能 / 机器学习', consult_price: 50, rating: 4.9, consult_count: 128, description: '10 年 AI 研发经验' },
  { id: 102, name: '李律师', title: '执业律师', specialty: '民商事 / 合同纠纷', consult_price: 80, rating: 4.8, consult_count: 256, description: '资深律师，擅长合同审查' },
  { id: 103, name: '王医生', title: '主治医师', specialty: '内科 / 健康咨询', consult_price: 30, rating: 4.9, consult_count: 512, description: '三甲医院内科主治医师' },
];

var QA_CATEGORIES = ['全部', '技术', '生活', '法律', '理财', '健康', '职场', '其他'];

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

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

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

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

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

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

  var s0 = useState(STATIC_QUESTIONS); var list = s0[0]; var setList = s0[1];
  var s1 = useState('全部'); var category = s1[0]; var setCategory = s1[1];
  var s2 = useState('latest'); var sort = s2[0]; var setSort = s2[1];
  var s3 = useState(false); var showAsk = s3[0]; var setShowAsk = s3[1];
  var s4 = useState(false); var loading = s4[0]; var setLoading = s4[1];

  // 加载问题列表，失败保留静态数据
  function loadQuestions() {
    try {
      setLoading(true);
      var url = '/qa/questions?sort=' + sort + '&category=' + (category === '全部' ? 'all' : encodeURIComponent(category));
      safeApiGet(url,
        function (data) {
          try {
            if (Array.isArray(data) && data.length > 0) {
              setList(data);
            }
            // 数据为空也保留静态兜底
            setLoading(false);
          } catch (e) { setLoading(false); }
        },
        function () { setLoading(false); }
      );
    } catch (e) { setLoading(false); }
  }

  useEffect(function () {
    loadQuestions();
  }, [sort, category]);

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

  function handleQuestionClick(q) {
    try {
      navigate('qa-question', { id: q.id });
    } catch (e) { try { showToast('功能加载中'); } catch (_) {} }
  }

  return qaReact.createElement('div', { style: {
    display: 'flex', flexDirection: 'column',
    height: '100dvh', overflow: 'hidden',
    background: 'var(--bg-page, #f5f5f5)',
  } },
    qaReact.createElement(QaHeader, {
      title: '问答',
      backTo: 'apps',
      rightBtn: { text: '我要提问', onClick: handleAskClick },
    }),

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

    // 排序栏
    qaReact.createElement('div', {
      style: {
        flexShrink: 0,
        display: 'flex', gap: 4, padding: '8px 16px',
        background: 'var(--bg-card, #fff)',
        borderTop: '1px solid var(--border-light, #f5f5f5)',
      },
    },
      [
        { key: 'latest', label: '最新' },
        { key: 'hot', label: '热门' },
        { key: 'bounty', label: '悬赏' },
      ].map(function (s) {
        var active = sort === s.key;
        return qaReact.createElement('button', {
          key: s.key,
          onClick: function () { try { setSort(s.key); } catch (e) {} },
          style: {
            padding: '4px 12px',
            fontSize: 12,
            borderRadius: 12,
            border: 'none',
            background: active ? 'var(--primary-light, #e8f7ef)' : 'transparent',
            color: active ? 'var(--primary, #1f8a5b)' : 'var(--text-tertiary, #999)',
            cursor: 'pointer',
            fontWeight: active ? 500 : 400,
          },
        }, s.label);
      }),
      qaReact.createElement('div', { style: { flex: 1 } }),
      qaReact.createElement('button', {
        onClick: function () { try { navigate('qa-experts'); } catch (e) {} },
        style: {
          fontSize: 12, color: 'var(--primary, #1f8a5b)',
          background: 'transparent', border: 'none', cursor: 'pointer',
        },
      }, '专家咨询 →')
    ),

    // 问题列表
    qaReact.createElement('div', { style: { flex: 1, minHeight: 0, overflowY: 'auto', padding: '12px 16px' } },
      qaReact.createElement('div', { style: { display: 'flex', flexDirection: 'column', gap: 10 } },
        list.map(function (q) {
          return qaReact.createElement('div', {
            key: q.id,
            onClick: function () { handleQuestionClick(q); },
            style: {
              padding: 14,
              background: 'var(--bg-card, #fff)',
              borderRadius: 10,
              cursor: 'pointer',
              boxShadow: '0 1px 3px rgba(0,0,0,0.04)',
            },
          },
            qaReact.createElement('div', { style: { fontSize: 14, fontWeight: 600, marginBottom: 6, lineHeight: 1.4, color: 'var(--text-primary, #333)' } }, q.title),
            q.content && qaReact.createElement('div', {
              style: {
                fontSize: 12, color: 'var(--text-tertiary, #999)', lineHeight: 1.5,
                overflow: 'hidden', marginBottom: 8,
                display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical',
              },
            }, q.content),
            qaReact.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 8, fontSize: 11, color: 'var(--text-tertiary, #999)' } },
              qaReact.createElement('span', null, q.author_name || '匿名'),
              qaReact.createElement('span', null, '·'),
              qaReact.createElement('span', { style: { padding: '1px 6px', borderRadius: 4, background: 'var(--bg-page, #f5f5f5)' } }, q.category || '其他'),
              qaReact.createElement('span', null, '·'),
              qaReact.createElement('span', null, (q.answer_count || 0) + ' 回答'),
              qaReact.createElement('span', null, '·'),
              qaReact.createElement('span', null, (q.view_count || 0) + ' 浏览'),
              q.bounty > 0 && qaReact.createElement('span', {
                style: { marginLeft: 'auto', color: '#f59e0b', fontWeight: 600 },
              }, '💰 ' + q.bounty + '元悬赏')
            )
          );
        })
      )
    ),

    // 提问弹窗
    showAsk && qaReact.createElement(AskModal, {
      onClose: function () { try { setShowAsk(false); } catch (e) {} },
      onSuccess: function () {
        try {
          setShowAsk(false);
          loadQuestions();
        } catch (e) {}
      },
    }),

    qaReact.createElement('style', null,
      '.qa-page { padding-bottom: 0 !important; }'
    )
  );
}

// ========== 提问弹窗 ==========
function AskModal(props) {
  var app = safeUseApp();
  var showToast = app.showToast || function (msg) { try { console.log('[toast]', msg); } catch (_) {} };

  var s0 = useState(''); var title = s0[0]; var setTitle = s0[1];
  var s1 = useState(''); var content = s1[0]; var setContent = s1[1];
  var s2 = useState('技术'); var category = s2[0]; var setCategory = s2[1];
  var s3 = useState(0); var bounty = s3[0]; var setBounty = s3[1];
  var s4 = useState(false); var showBounty = s4[0]; var setShowBounty = s4[1];
  var s5 = useState(false); var submitting = s5[0]; var setSubmitting = s5[1];

  function handleSubmit() {
    try {
      if (!title.trim()) { showToast('请输入问题标题'); return; }
      if (!content.trim()) { showToast('请输入问题描述'); return; }
      if (showBounty && bounty > 0) {
        if (bounty < 1) { showToast('悬赏金额不能小于 1 元'); return; }
      }
      setSubmitting(true);
      safeApiPost('/qa/questions', {
        title: title,
        content: content,
        category: category,
        bounty: showBounty ? bounty : 0,
      }, function (data) {
        try {
          setSubmitting(false);
          showToast('发布成功');
          if (props.onSuccess) props.onSuccess();
        } catch (e) { setSubmitting(false); }
      }, function (err) {
        try {
          setSubmitting(false);
          showToast(err && err.message ? err.message : '发布失败');
        } catch (e) { setSubmitting(false); }
      });
    } catch (e) {
      try { setSubmitting(false); showToast('发布失败'); } catch (_) {}
    }
  }

  return qaReact.createElement('div', {
    onClick: function () { try { props.onClose && props.onClose(); } catch (e) {} },
    style: {
      position: 'fixed', inset: 0, zIndex: 1000,
      background: 'rgba(0,0,0,0.5)',
      display: 'flex', alignItems: 'flex-end', justifyContent: 'center',
    },
  },
    qaReact.createElement('div', {
      onClick: function (e) { try { e.stopPropagation(); } catch (_) {} },
      style: {
        width: '100%', maxWidth: 480, maxHeight: '85vh',
        background: 'var(--bg-card, #fff)',
        borderRadius: '16px 16px 0 0',
        display: 'flex', flexDirection: 'column', overflow: 'hidden',
      },
    },
      qaReact.createElement('div', {
        style: {
          flexShrink: 0, padding: '14px 16px',
          borderBottom: '1px solid var(--border, #eee)',
          display: 'flex', justifyContent: 'space-between', alignItems: 'center',
        },
      },
        qaReact.createElement('div', { style: { fontSize: 16, fontWeight: 600 } }, '发布问题'),
        qaReact.createElement('button', {
          onClick: function () { try { props.onClose && props.onClose(); } catch (e) {} },
          style: { fontSize: 20, color: 'var(--text-tertiary, #999)', background: 'transparent', border: 'none', cursor: 'pointer', padding: 0, lineHeight: 1 },
        }, '×')
      ),
      qaReact.createElement('div', { style: { flex: 1, overflowY: 'auto', padding: 16 } },
        qaReact.createElement('div', { style: { marginBottom: 12 } },
          qaReact.createElement('div', { style: { fontSize: 12, color: 'var(--text-secondary, #666)', marginBottom: 6 } }, '标题'),
          qaReact.createElement('input', {
            type: 'text',
            value: title,
            onChange: function (e) { try { setTitle(e.target.value); } catch (_) {} },
            placeholder: '请输入问题标题',
            style: {
              width: '100%', padding: '10px 12px',
              border: '1px solid var(--border, #ddd)',
              borderRadius: 8, fontSize: 13,
              boxSizing: 'border-box',
              outline: 'none',
            },
          })
        ),
        qaReact.createElement('div', { style: { marginBottom: 12 } },
          qaReact.createElement('div', { style: { fontSize: 12, color: 'var(--text-secondary, #666)', marginBottom: 6 } }, '分类'),
          qaReact.createElement('div', { style: { display: 'flex', flexWrap: 'wrap', gap: 6 } },
            QA_CATEGORIES.filter(function (c) { return c !== '全部'; }).map(function (c) {
              var active = category === c;
              return qaReact.createElement('button', {
                key: c,
                onClick: function () { try { setCategory(c); } catch (e) {} },
                style: {
                  padding: '5px 12px', fontSize: 12,
                  borderRadius: 14, border: 'none', cursor: 'pointer',
                  background: active ? 'var(--primary, #1f8a5b)' : 'var(--bg-page, #f5f5f5)',
                  color: active ? '#fff' : 'var(--text-secondary, #666)',
                },
              }, c);
            })
          )
        ),
        qaReact.createElement('div', { style: { marginBottom: 12 } },
          qaReact.createElement('div', { style: { fontSize: 12, color: 'var(--text-secondary, #666)', marginBottom: 6 } }, '问题描述'),
          qaReact.createElement('textarea', {
            value: content,
            onChange: function (e) { try { setContent(e.target.value); } catch (_) {} },
            placeholder: '详细描述你的问题...',
            rows: 6,
            style: {
              width: '100%', padding: '10px 12px',
              border: '1px solid var(--border, #ddd)',
              borderRadius: 8, fontSize: 13,
              boxSizing: 'border-box',
              resize: 'vertical', outline: 'none',
            },
          })
        ),
        qaReact.createElement('div', { style: { marginBottom: 12 } },
          qaReact.createElement('label', { style: { display: 'flex', alignItems: 'center', gap: 6, fontSize: 12, color: 'var(--text-secondary, #666)', cursor: 'pointer' } },
            qaReact.createElement('input', {
              type: 'checkbox',
              checked: showBounty,
              onChange: function (e) { try { setShowBounty(e.target.checked); } catch (_) {} },
              style: { cursor: 'pointer' },
            }),
            '设置悬赏'
          ),
          showBounty && qaReact.createElement('div', { style: { marginTop: 8, display: 'flex', alignItems: 'center', gap: 8 } },
            qaReact.createElement('input', {
              type: 'number',
              value: bounty,
              min: 0,
              step: 1,
              onChange: function (e) { try { setBounty(parseFloat(e.target.value) || 0); } catch (_) {} },
              style: {
                width: 100, padding: '6px 10px',
                border: '1px solid var(--border, #ddd)',
                borderRadius: 6, fontSize: 13,
              },
            }),
            qaReact.createElement('span', { style: { fontSize: 12, color: 'var(--text-tertiary, #999)' } }, '元')
          )
        )
      ),
      qaReact.createElement('div', {
        style: {
          flexShrink: 0, padding: '12px 16px',
          borderTop: '1px solid var(--border, #eee)',
        },
      },
        qaReact.createElement('button', {
          onClick: handleSubmit,
          disabled: submitting,
          style: {
            width: '100%', padding: '11px 0',
            background: 'var(--primary, #1f8a5b)', color: '#fff',
            border: 'none', borderRadius: 8, fontSize: 14, fontWeight: 500,
            cursor: submitting ? 'not-allowed' : 'pointer',
            opacity: submitting ? 0.6 : 1,
          },
        }, submitting ? '发布中...' : '发布问题')
      )
    )
  );
}

// ========== 问题详情页 ==========
function QaQuestionPage() {
  var app = safeUseApp();
  var navigate = app.navigate || function () {};
  var showToast = app.showToast || function (msg) { try { console.log('[toast]', msg); } catch (_) {} };
  var requireLogin = app.requireLogin || function () { showToast('请先登录'); return false; };
  var currentUser = app.currentUser || null;
  var params = app.pageParams || {};
  var qid = params.id;

  var s0 = useState(null); var question = s0[0]; var setQuestion = s0[1];
  var s1 = useState([]); var answers = s1[0]; var setAnswers = s1[1];
  var s2 = useState(false); var showAnswer = s2[0]; var setShowAnswer = s2[1];
  var s3 = useState(null); var rewardAnswerId = s3[0]; var setRewardAnswerId = s3[1];

  // 静态兜底问题
  var fallbackQuestion = {
    id: qid || 0,
    title: '问题详情加载中...',
    content: '正在获取问题内容，请稍候。',
    author_name: '用户',
    answer_count: 0,
    view_count: 0,
    category: '其他',
    created_at: new Date().toISOString(),
  };

  function loadAll() {
    if (!qid) return;
    try {
      safeApiGet('/qa/questions/' + qid,
        function (data) { try { setQuestion(data); } catch (e) {} },
        function () { try { setQuestion(fallbackQuestion); } catch (e) {} }
      );
      safeApiGet('/qa/questions/' + qid + '/answers',
        function (data) { try { if (Array.isArray(data)) setAnswers(data); } catch (e) {} },
        function () { try { setAnswers([]); } catch (e) {} }
      );
    } catch (e) {}
  }

  useEffect(function () {
    loadAll();
    return function () {};
  }, [qid]);

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

  function handleLike(aid) {
    try {
      requireLogin(function () {
        try {
          safeApiPost('/qa/answers/' + aid + '/like', {},
            function () {
              try {
                showToast('已点赞');
                setAnswers(answers.map(function (a) {
                  if (a.id === aid) return Object.assign({}, a, { like_count: (a.like_count || 0) + 1 });
                  return a;
                }));
              } catch (e) {}
            },
            function (err) { try { showToast(err && err.message ? err.message : '操作失败'); } catch (_) {} }
          );
        } catch (e) {}
      });
    } catch (e) { try { showToast('请先登录'); } catch (_) {} }
  }

  function handlePayAnswer(aid, price) {
    try {
      requireLogin(function () {
        try {
          if (!confirm('确定支付 ' + price + ' 元解锁此回答吗？')) return;
          safeApiPost('/qa/answers/' + aid + '/pay', {},
            function (data) {
              try {
                showToast('解锁成功');
                // 重新加载回答列表
                safeApiGet('/qa/questions/' + qid + '/answers',
                  function (d) { try { if (Array.isArray(d)) setAnswers(d); } catch (e) {} },
                  function () {}
                );
              } catch (e) {}
            },
            function (err) { try { showToast(err && err.message ? err.message : '支付失败'); } catch (_) {} }
          );
        } catch (e) {}
      });
    } catch (e) { try { showToast('请先登录'); } catch (_) {} }
  }

  function handleAdopt(aid) {
    try {
      safeApiPost('/qa/answers/' + aid + '/adopt', {},
        function () {
          try {
            showToast('已采纳为最佳答案');
            loadAll();
          } catch (e) {}
        },
        function (err) { try { showToast(err && err.message ? err.message : '操作失败'); } catch (_) {} }
      );
    } catch (e) {}
  }

  function handleReward(aid, amount) {
    try {
      safeApiPost('/qa/answers/' + aid + '/reward', { amount: amount },
        function () {
          try {
            showToast('打赏成功');
            setRewardAnswerId(null);
            setAnswers(answers.map(function (a) {
              if (a.id === aid) return Object.assign({}, a, { reward_count: (a.reward_count || 0) + 1 });
              return a;
            }));
          } catch (e) {}
        },
        function (err) { try { showToast(err && err.message ? err.message : '打赏失败'); } catch (_) {} }
      );
    } catch (e) {}
  }

  var q = question || fallbackQuestion;
  var isAuthor = currentUser && q && q.user_id && currentUser.id === q.user_id;

  return qaReact.createElement('div', { style: {
    display: 'flex', flexDirection: 'column',
    height: '100dvh', overflow: 'hidden',
    background: 'var(--bg-page, #f5f5f5)',
  } },
    qaReact.createElement(QaHeader, { title: '问题详情', backTo: 'qa' }),

    qaReact.createElement('div', { style: { flex: 1, overflowY: 'auto', paddingBottom: 80 } },
      // 问题区
      qaReact.createElement('div', { style: { padding: 16 } },
        qaReact.createElement('div', { style: { padding: 16, background: 'var(--bg-card, #fff)', borderRadius: 10 } },
          qaReact.createElement('div', { style: { fontSize: 16, fontWeight: 600, marginBottom: 8, color: 'var(--text-primary, #333)' } }, q.title),
          qaReact.createElement('div', { style: { fontSize: 13, color: 'var(--text-secondary, #666)', lineHeight: 1.6, marginBottom: 12 } }, q.content),
          qaReact.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 10, fontSize: 11, color: 'var(--text-tertiary, #999)' } },
            qaReact.createElement('span', null, q.author_name || '匿名'),
            qaReact.createElement('span', null, '·'),
            qaReact.createElement('span', null, (q.view_count || 0) + ' 浏览'),
            qaReact.createElement('span', null, '·'),
            qaReact.createElement('span', null, (q.answer_count || 0) + ' 回答'),
            q.bounty > 0 && qaReact.createElement('span', {
              style: { marginLeft: 'auto', color: '#f59e0b', fontWeight: 600 },
            }, '💰 ' + q.bounty + '元悬赏')
          )
        )
      ),

      // 回答列表
      qaReact.createElement('div', { style: { padding: '0 16px 16px' } },
        qaReact.createElement('div', { style: { fontSize: 14, fontWeight: 600, marginBottom: 10 } }, '回答（' + answers.length + '）'),
        answers.length === 0
          ? qaReact.createElement('div', { style: { textAlign: 'center', padding: 40, color: 'var(--text-tertiary, #999)', fontSize: 13, background: 'var(--bg-card, #fff)', borderRadius: 10 } },
              '暂无回答，快来第一个回答吧')
          : qaReact.createElement('div', { style: { display: 'flex', flexDirection: 'column', gap: 10 } },
              answers.map(function (a) {
                return qaReact.createElement('div', {
                  key: a.id,
                  style: { padding: 14, background: 'var(--bg-card, #fff)', borderRadius: 10 },
                },
                  a.is_best && qaReact.createElement('div', { style: {
                    display: 'inline-block',
                    padding: '2px 8px', borderRadius: 10,
                    background: '#dcfce7', color: '#15803d',
                    fontSize: 11, fontWeight: 600, marginBottom: 8,
                  } }, '✓ 最佳答案'),
                  qaReact.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8 } },
                    qaReact.createElement('div', { style: {
                      width: 32, height: 32, borderRadius: '50%',
                      background: 'var(--primary-light, #e8f7ef)', color: 'var(--primary, #1f8a5b)',
                      display: 'flex', alignItems: 'center', justifyContent: 'center',
                      fontSize: 12, fontWeight: 600,
                    }}, (a.author_name || 'U').charAt(0)),
                    qaReact.createElement('div', null,
                      qaReact.createElement('div', { style: { fontSize: 13, fontWeight: 500 } }, a.author_name || '用户'),
                      qaReact.createElement('div', { style: { fontSize: 11, color: 'var(--text-tertiary, #999)' } },
                        a.created_at ? new Date(a.created_at).toLocaleDateString() : ''
                      )
                    )
                  ),
                  a.needs_pay
                    ? qaReact.createElement('div', null,
                        qaReact.createElement('div', { style: {
                          fontSize: 13, color: 'var(--text-secondary, #666)', lineHeight: 1.7,
                          paddingBottom: 10, borderBottom: '1px dashed var(--border, #eee)',
                        } }, (a.content_preview || '') + '...'),
                        qaReact.createElement('button', {
                          onClick: function () { handlePayAnswer(a.id, a.paid_price); },
                          style: {
                            marginTop: 10, width: '100%',
                            padding: '8px 0', fontSize: 12,
                            background: '#fef3c7', color: '#92400e',
                            border: 'none', borderRadius: 8, cursor: 'pointer', fontWeight: 500,
                          },
                        }, '🔒 支付 ' + a.paid_price + ' 元查看完整回答')
                      )
                    : qaReact.createElement('div', { style: { fontSize: 13, color: 'var(--text-primary, #333)', lineHeight: 1.7 } }, a.content),
                  // 操作栏
                  qaReact.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 12, marginTop: 10, paddingTop: 10, borderTop: '1px solid var(--border-light, #f5f5f5)' } },
                    qaReact.createElement('button', {
                      onClick: function () { handleLike(a.id); },
                      style: { fontSize: 12, color: 'var(--text-tertiary, #999)', background: 'transparent', border: 'none', cursor: 'pointer', padding: 0 },
                    }, '👍 ' + (a.like_count || 0)),
                    qaReact.createElement('button', {
                      onClick: function () { try { setRewardAnswerId(a.id); } catch (e) {} },
                      style: { fontSize: 12, color: 'var(--text-tertiary, #999)', background: 'transparent', border: 'none', cursor: 'pointer', padding: 0 },
                    }, '💴 打赏 ' + (a.reward_count || 0)),
                    isAuthor && !q.best_answer_id && qaReact.createElement('button', {
                      onClick: function () { handleAdopt(a.id); },
                      style: { fontSize: 12, color: 'var(--primary, #1f8a5b)', background: 'transparent', border: 'none', cursor: 'pointer', padding: 0, marginLeft: 'auto' },
                    }, '✓ 采纳')
                  )
                );
              })
            )
      ),

      // 打赏弹窗
      rewardAnswerId && qaReact.createElement(RewardModal, {
        answerId: rewardAnswerId,
        onClose: function () { try { setRewardAnswerId(null); } catch (e) {} },
        onReward: function (amount) { try { handleReward(rewardAnswerId, amount); } catch (e) {} },
      })
    ),

    // 底部回答按钮
    qaReact.createElement('div', {
      style: {
        flexShrink: 0, padding: '10px 16px',
        background: 'var(--bg-card, #fff)',
        borderTop: '1px solid var(--border, #eee)',
      },
    },
      qaReact.createElement('button', {
        onClick: handleAnswerClick,
        style: {
          width: '100%', padding: '10px 0',
          background: 'var(--primary, #1f8a5b)', color: '#fff',
          border: 'none', borderRadius: 8, fontSize: 14, fontWeight: 500,
          cursor: 'pointer',
        },
      }, '写回答')
    ),

    // 回答弹窗
    showAnswer && qaReact.createElement(AnswerModal, {
      questionId: qid,
      onClose: function () { try { setShowAnswer(false); } catch (e) {} },
      onSuccess: function () {
        try {
          setShowAnswer(false);
          loadAll();
        } catch (e) {}
      },
    })
  );
}

// ========== 回答弹窗 ==========
function AnswerModal(props) {
  var app = safeUseApp();
  var showToast = app.showToast || function (msg) { try { console.log('[toast]', msg); } catch (_) {} };

  var s0 = useState(''); var content = s0[0]; var setContent = s0[1];
  var s1 = useState(false); var isPaid = s1[0]; var setIsPaid = s1[1];
  var s2 = useState(2.99); var price = s2[0]; var setPrice = s2[1];
  var s3 = useState(false); var submitting = s3[0]; var setSubmitting = s3[1];

  function handleSubmit() {
    try {
      if (!content.trim()) { showToast('请输入回答内容'); return; }
      if (isPaid && price < 0.01) { showToast('请输入正确的付费金额'); return; }
      setSubmitting(true);
      safeApiPost('/qa/questions/' + props.questionId + '/answers', {
        content: content,
        is_paid: isPaid,
        paid_price: isPaid ? price : 0,
      }, function () {
        try {
          setSubmitting(false);
          showToast('回答已发布');
          if (props.onSuccess) props.onSuccess();
        } catch (e) { setSubmitting(false); }
      }, function (err) {
        try {
          setSubmitting(false);
          showToast(err && err.message ? err.message : '发布失败');
        } catch (e) { setSubmitting(false); }
      });
    } catch (e) {
      try { setSubmitting(false); showToast('发布失败'); } catch (_) {}
    }
  }

  return qaReact.createElement('div', {
    onClick: function () { try { props.onClose && props.onClose(); } catch (e) {} },
    style: {
      position: 'fixed', inset: 0, zIndex: 1000,
      background: 'rgba(0,0,0,0.5)',
      display: 'flex', alignItems: 'flex-end', justifyContent: 'center',
    },
  },
    qaReact.createElement('div', {
      onClick: function (e) { try { e.stopPropagation(); } catch (_) {} },
      style: {
        width: '100%', maxWidth: 480, maxHeight: '85vh',
        background: 'var(--bg-card, #fff)',
        borderRadius: '16px 16px 0 0',
        display: 'flex', flexDirection: 'column', overflow: 'hidden',
      },
    },
      qaReact.createElement('div', {
        style: {
          flexShrink: 0, padding: '14px 16px',
          borderBottom: '1px solid var(--border, #eee)',
          display: 'flex', justifyContent: 'space-between', alignItems: 'center',
        },
      },
        qaReact.createElement('div', { style: { fontSize: 16, fontWeight: 600 } }, '写回答'),
        qaReact.createElement('button', {
          onClick: function () { try { props.onClose && props.onClose(); } catch (e) {} },
          style: { fontSize: 20, color: 'var(--text-tertiary, #999)', background: 'transparent', border: 'none', cursor: 'pointer', padding: 0, lineHeight: 1 },
        }, '×')
      ),
      qaReact.createElement('div', { style: { flex: 1, overflowY: 'auto', padding: 16 } },
        qaReact.createElement('textarea', {
          value: content,
          onChange: function (e) { try { setContent(e.target.value); } catch (_) {} },
          placeholder: '写下你的回答...',
          rows: 10,
          style: {
            width: '100%', padding: '10px 12px',
            border: '1px solid var(--border, #ddd)',
            borderRadius: 8, fontSize: 13,
            boxSizing: 'border-box',
            resize: 'vertical', outline: 'none',
          },
        }),
        qaReact.createElement('div', { style: { marginTop: 12 } },
          qaReact.createElement('label', { style: { display: 'flex', alignItems: 'center', gap: 6, fontSize: 12, color: 'var(--text-secondary, #666)', cursor: 'pointer' } },
            qaReact.createElement('input', {
              type: 'checkbox',
              checked: isPaid,
              onChange: function (e) { try { setIsPaid(e.target.checked); } catch (_) {} },
              style: { cursor: 'pointer' },
            }),
            '设置为付费回答'
          ),
          isPaid && qaReact.createElement('div', { style: { marginTop: 8, display: 'flex', alignItems: 'center', gap: 8 } },
            qaReact.createElement('input', {
              type: 'number',
              value: price,
              min: 0.01,
              step: 0.01,
              onChange: function (e) { try { setPrice(parseFloat(e.target.value) || 0); } catch (_) {} },
              style: {
                width: 100, padding: '6px 10px',
                border: '1px solid var(--border, #ddd)',
                borderRadius: 6, fontSize: 13,
              },
            }),
            qaReact.createElement('span', { style: { fontSize: 12, color: 'var(--text-tertiary, #999)' } }, '元（用户需支付后查看完整回答）')
          )
        )
      ),
      qaReact.createElement('div', {
        style: {
          flexShrink: 0, padding: '12px 16px',
          borderTop: '1px solid var(--border, #eee)',
        },
      },
        qaReact.createElement('button', {
          onClick: handleSubmit,
          disabled: submitting,
          style: {
            width: '100%', padding: '11px 0',
            background: 'var(--primary, #1f8a5b)', color: '#fff',
            border: 'none', borderRadius: 8, fontSize: 14, fontWeight: 500,
            cursor: submitting ? 'not-allowed' : 'pointer',
            opacity: submitting ? 0.6 : 1,
          },
        }, submitting ? '发布中...' : '发布回答')
      )
    )
  );
}

// ========== 打赏弹窗 ==========
function RewardModal(props) {
  var app = safeUseApp();
  var showToast = app.showToast || function (msg) { try { console.log('[toast]', msg); } catch (_) {} };
  var requireLogin = app.requireLogin || function () { showToast('请先登录'); return false; };

  var s0 = useState(2); var amount = s0[0]; var setAmount = s0[1];
  var presetAmounts = [1, 2, 5, 10, 20, 50];

  function handleReward() {
    try {
      requireLogin(function () {
        try {
          if (amount <= 0) { showToast('请输入打赏金额'); return; }
          if (props.onReward) props.onReward(amount);
        } catch (e) {}
      });
    } catch (e) { try { showToast('请先登录'); } catch (_) {} }
  }

  return qaReact.createElement('div', {
    onClick: function () { try { props.onClose && props.onClose(); } catch (e) {} },
    style: {
      position: 'fixed', inset: 0, zIndex: 1000,
      background: 'rgba(0,0,0,0.5)',
      display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20,
    },
  },
    qaReact.createElement('div', {
      onClick: function (e) { try { e.stopPropagation(); } catch (_) {} },
      style: {
        width: '100%', maxWidth: 320,
        background: 'var(--bg-card, #fff)',
        borderRadius: 16, padding: 20,
      },
    },
      qaReact.createElement('div', { style: { fontSize: 16, fontWeight: 600, textAlign: 'center', marginBottom: 16 } }, '打赏回答'),
      qaReact.createElement('div', { style: { display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8, marginBottom: 16 } },
        presetAmounts.map(function (val) {
          var active = amount === val;
          return qaReact.createElement('button', {
            key: val,
            onClick: function () { try { setAmount(val); } catch (e) {} },
            style: {
              padding: '10px 0', fontSize: 14,
              borderRadius: 8, border: '1px solid',
              borderColor: active ? 'var(--primary, #1f8a5b)' : 'var(--border, #ddd)',
              background: active ? 'var(--primary-light, #e8f7ef)' : 'transparent',
              color: active ? 'var(--primary, #1f8a5b)' : 'var(--text-primary, #333)',
              cursor: 'pointer', fontWeight: active ? 600 : 400,
            },
          }, val + ' 元');
        })
      ),
      qaReact.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 8, marginBottom: 16 } },
        qaReact.createElement('span', { style: { fontSize: 12, color: 'var(--text-secondary, #666)' } }, '自定义：'),
        qaReact.createElement('input', {
          type: 'number',
          value: amount,
          min: 1,
          onChange: function (e) { try { setAmount(parseFloat(e.target.value) || 0); } catch (_) {} },
          style: {
            flex: 1, padding: '6px 10px',
            border: '1px solid var(--border, #ddd)',
            borderRadius: 6, fontSize: 13,
          },
        }),
        qaReact.createElement('span', { style: { fontSize: 12, color: 'var(--text-tertiary, #999)' } }, '元')
      ),
      qaReact.createElement('div', { style: { display: 'flex', gap: 10 } },
        qaReact.createElement('button', {
          onClick: function () { try { props.onClose && props.onClose(); } catch (e) {} },
          style: {
            flex: 1, padding: '10px 0',
            background: 'var(--bg-page, #f5f5f5)', color: 'var(--text-secondary, #666)',
            border: 'none', borderRadius: 8, fontSize: 13, cursor: 'pointer',
          },
        }, '取消'),
        qaReact.createElement('button', {
          onClick: handleReward,
          style: {
            flex: 1, padding: '10px 0',
            background: 'var(--primary, #1f8a5b)', color: '#fff',
            border: 'none', borderRadius: 8, fontSize: 13, fontWeight: 500, cursor: 'pointer',
          },
        }, '打赏 ' + amount + ' 元')
      )
    )
  );
}

// ========== 专家列表页 ==========
function QaExpertsPage() {
  var app = safeUseApp();
  var navigate = app.navigate || function () {};
  var showToast = app.showToast || function (msg) { try { console.log('[toast]', msg); } catch (_) {} };

  var s0 = useState(STATIC_EXPERTS); var experts = s0[0]; var setExperts = s0[1];

  useEffect(function () {
    try {
      safeApiGet('/qa/experts',
        function (data) {
          try { if (Array.isArray(data) && data.length > 0) setExperts(data); } catch (e) {}
        },
        function () {}
      );
    } catch (e) {}
  }, []);

  function handleConsult(expert) {
    try { navigate('qa-consult', { expertId: expert.id, expertName: expert.name }); }
    catch (e) { try { showToast('功能加载中'); } catch (_) {} }
  }

  return qaReact.createElement('div', { style: {
    display: 'flex', flexDirection: 'column',
    height: '100dvh', overflow: 'hidden',
    background: 'var(--bg-page, #f5f5f5)',
  } },
    qaReact.createElement(QaHeader, { title: '专家咨询', backTo: 'qa' }),

    qaReact.createElement('div', { style: { flex: 1, padding: 12, overflowY: 'auto' } },
      qaReact.createElement('div', { style: { display: 'flex', flexDirection: 'column', gap: 10 } },
        experts.map(function (e) {
          return qaReact.createElement('div', {
            key: e.id,
            style: {
              padding: 14, background: 'var(--bg-card, #fff)', borderRadius: 10,
              display: 'flex', gap: 12, alignItems: 'center',
              boxShadow: '0 1px 3px rgba(0,0,0,0.04)',
            },
          },
            qaReact.createElement('div', { style: {
              width: 48, height: 48, borderRadius: '50%',
              background: 'var(--primary-light, #e8f7ef)', color: 'var(--primary, #1f8a5b)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontSize: 16, fontWeight: 600, flexShrink: 0,
            }}, (e.name || '专').charAt(0)),
            qaReact.createElement('div', { style: { flex: 1, minWidth: 0 } },
              qaReact.createElement('div', { style: { fontSize: 14, fontWeight: 600, marginBottom: 2 } }, e.name),
              qaReact.createElement('div', { style: { fontSize: 11, color: 'var(--text-secondary, #666)', marginBottom: 4 } }, e.title || ''),
              qaReact.createElement('div', { style: { fontSize: 11, color: 'var(--text-tertiary, #999)', display: 'flex', gap: 8, flexWrap: 'wrap' } },
                qaReact.createElement('span', null, e.specialty || '专业咨询'),
                qaReact.createElement('span', null, '⭐ ' + (e.rating || 0)),
                qaReact.createElement('span', null, (e.consult_count || 0) + ' 次咨询')
              )
            ),
            qaReact.createElement('button', {
              onClick: function () { handleConsult(e); },
              style: {
                fontSize: 12, padding: '5px 12px',
                background: 'var(--primary, #1f8a5b)', color: '#fff',
                border: 'none', borderRadius: 14, cursor: 'pointer', flexShrink: 0,
              },
            }, '¥' + (e.consult_price || 0) + ' 咨询')
          );
        })
      )
    ),

    // 我的咨询入口
    qaReact.createElement('div', {
      style: {
        flexShrink: 0, padding: '10px 16px',
        background: 'var(--primary-light, #e8f7ef)',
        borderTop: '1px solid var(--border, #eee)',
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        fontSize: 12,
      },
    },
      qaReact.createElement('span', { style: { color: 'var(--primary, #1f8a5b)' } }, '查看我的咨询记录'),
      qaReact.createElement('button', {
        onClick: function () { try { navigate('qa-consult'); } catch (e) {} },
        style: {
          fontSize: 12, padding: '4px 10px',
          background: 'var(--primary, #1f8a5b)', color: '#fff',
          border: 'none', borderRadius: 12, cursor: 'pointer',
        },
      }, '去查看 →')
    )
  );
}

// ========== 我的咨询 / 发起咨询页 ==========
function QaConsultPage() {
  var app = safeUseApp();
  var navigate = app.navigate || function () {};
  var showToast = app.showToast || function (msg) { try { console.log('[toast]', msg); } catch (_) {} };
  var requireLogin = app.requireLogin || function () { showToast('请先登录'); return false; };
  var params = app.pageParams || {};
  var expertId = params.expertId;
  var expertName = params.expertName || '专家';

  var s0 = useState([]); var consults = s0[0]; var setConsults = s0[1];
  var s1 = useState(false); var showNew = s1[0]; var setShowNew = s1[1];
  var s2 = useState(''); var newTitle = s2[0]; var setNewTitle = s2[1];
  var s3 = useState(''); var newContent = s3[0]; var setNewContent = s3[1];
  var s4 = useState(false); var submitting = s4[0]; var setSubmitting = s4[1];

  function loadConsults() {
    try {
      safeApiGet('/qa/consults',
        function (data) { try { if (Array.isArray(data)) setConsults(data); } catch (e) {} },
        function () { try { setConsults([]); } catch (e) {} }
      );
    } catch (e) {}
  }

  useEffect(function () {
    // 如果带了 expertId，直接弹发起咨询
    if (expertId) {
      try { setShowNew(true); } catch (e) {}
    }
    loadConsults();
    return function () {};
  }, [expertId]);

  function handleNewConsult() {
    try {
      requireLogin(function () {
        try {
          if (!newTitle.trim()) { showToast('请输入问题标题'); return; }
          if (!newContent.trim()) { showToast('请输入问题描述'); return; }
          setSubmitting(true);
          safeApiPost('/qa/experts/' + expertId + '/consult', {
            title: newTitle,
            content: newContent,
          }, function () {
            try {
              setSubmitting(false);
              showToast('咨询已发送');
              setShowNew(false);
              setNewTitle('');
              setNewContent('');
              loadConsults();
            } catch (e) { setSubmitting(false); }
          }, function (err) {
            try {
              setSubmitting(false);
              showToast(err && err.message ? err.message : '发送失败');
            } catch (e) { setSubmitting(false); }
          });
        } catch (e) { setSubmitting(false); }
      });
    } catch (e) { try { showToast('请先登录'); } catch (_) {} }
  }

  return qaReact.createElement('div', { style: {
    display: 'flex', flexDirection: 'column',
    height: '100dvh', overflow: 'hidden',
    background: 'var(--bg-page, #f5f5f5)',
  } },
    qaReact.createElement(QaHeader, { title: '我的咨询', backTo: 'qa-experts' }),

    qaReact.createElement('div', { style: { flex: 1, padding: 12, overflowY: 'auto' } },
      consults.length === 0
        ? qaReact.createElement('div', { style: { textAlign: 'center', padding: 60, color: 'var(--text-tertiary, #999)', fontSize: 13 } },
            '暂无咨询记录')
        : qaReact.createElement('div', { style: { display: 'flex', flexDirection: 'column', gap: 10 } },
            consults.map(function (c) {
              var statusText = c.status === 'answered' ? '已回复' : c.status === 'pending' ? '待回复' : '已完成';
              var statusColor = c.status === 'answered' ? '#15803d' : c.status === 'pending' ? '#92400e' : '#6b7280';
              var statusBg = c.status === 'answered' ? '#dcfce7' : c.status === 'pending' ? '#fef3c7' : '#f3f4f6';
              return qaReact.createElement('div', {
                key: c.id,
                style: {
                  padding: 14, background: 'var(--bg-card, #fff)', borderRadius: 10,
                  cursor: 'pointer', boxShadow: '0 1px 3px rgba(0,0,0,0.04)',
                },
              },
                qaReact.createElement('div', { style: { display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 6 } },
                  qaReact.createElement('div', { style: { fontSize: 13, fontWeight: 600 } }, c.expert_name || expertName),
                  qaReact.createElement('span', { style: {
                    fontSize: 11, padding: '2px 8px', borderRadius: 8,
                    background: statusBg, color: statusColor,
                  }}, statusText)
                ),
                qaReact.createElement('div', { style: { fontSize: 13, color: 'var(--text-secondary, #666)', marginBottom: 6 } }, c.title || c.question),
                c.answer && qaReact.createElement('div', {
                  style: {
                    fontSize: 12, color: 'var(--text-tertiary, #999)',
                    padding: 10, background: 'var(--bg-page, #f5f5f5)', borderRadius: 6,
                    lineHeight: 1.5,
                  },
                }, '专家回复：' + c.answer),
                qaReact.createElement('div', { style: { fontSize: 11, color: 'var(--text-tertiary, #999)', marginTop: 6 } },
                  c.created_at ? new Date(c.created_at).toLocaleString() : '')
              );
            })
          )
    ),

    // 发起咨询弹窗
    showNew && qaReact.createElement('div', {
      onClick: function () { try { setShowNew(false); } catch (e) {} },
      style: {
        position: 'fixed', inset: 0, zIndex: 1000,
        background: 'rgba(0,0,0,0.5)',
        display: 'flex', alignItems: 'flex-end', justifyContent: 'center',
      },
    },
      qaReact.createElement('div', {
        onClick: function (e) { try { e.stopPropagation(); } catch (_) {} },
        style: {
          width: '100%', maxWidth: 480, maxHeight: '85vh',
          background: 'var(--bg-card, #fff)',
          borderRadius: '16px 16px 0 0',
          display: 'flex', flexDirection: 'column', overflow: 'hidden',
        },
      },
        qaReact.createElement('div', {
          style: {
            flexShrink: 0, padding: '14px 16px',
            borderBottom: '1px solid var(--border, #eee)',
            display: 'flex', justifyContent: 'space-between', alignItems: 'center',
          },
        },
          qaReact.createElement('div', { style: { fontSize: 16, fontWeight: 600 } }, '向 ' + expertName + ' 咨询'),
          qaReact.createElement('button', {
            onClick: function () { try { setShowNew(false); } catch (e) {} },
            style: { fontSize: 20, color: 'var(--text-tertiary, #999)', background: 'transparent', border: 'none', cursor: 'pointer', padding: 0, lineHeight: 1 },
          }, '×')
        ),
        qaReact.createElement('div', { style: { flex: 1, overflowY: 'auto', padding: 16 } },
          qaReact.createElement('div', { style: { marginBottom: 12 } },
            qaReact.createElement('div', { style: { fontSize: 12, color: 'var(--text-secondary, #666)', marginBottom: 6 } }, '问题标题'),
            qaReact.createElement('input', {
              type: 'text', value: newTitle,
              onChange: function (e) { try { setNewTitle(e.target.value); } catch (_) {} },
              placeholder: '简要描述您的问题',
              style: {
                width: '100%', padding: '10px 12px',
                border: '1px solid var(--border, #ddd)',
                borderRadius: 8, fontSize: 13, boxSizing: 'border-box', outline: 'none',
              },
            })
          ),
          qaReact.createElement('div', { style: { marginBottom: 12 } },
            qaReact.createElement('div', { style: { fontSize: 12, color: 'var(--text-secondary, #666)', marginBottom: 6 } }, '详细描述'),
            qaReact.createElement('textarea', {
              value: newContent, rows: 6,
              onChange: function (e) { try { setNewContent(e.target.value); } catch (_) {} },
              placeholder: '详细描述您的问题和需求...',
              style: {
                width: '100%', padding: '10px 12px',
                border: '1px solid var(--border, #ddd)',
                borderRadius: 8, fontSize: 13,
                boxSizing: 'border-box', resize: 'vertical', outline: 'none',
              },
            })
          )
        ),
        qaReact.createElement('div', {
          style: {
            flexShrink: 0, padding: '12px 16px',
            borderTop: '1px solid var(--border, #eee)',
          },
        },
          qaReact.createElement('button', {
            onClick: handleNewConsult,
            disabled: submitting,
            style: {
              width: '100%', padding: '11px 0',
              background: 'var(--primary, #1f8a5b)', color: '#fff',
              border: 'none', borderRadius: 8, fontSize: 14, fontWeight: 500,
              cursor: submitting ? 'not-allowed' : 'pointer',
              opacity: submitting ? 0.6 : 1,
            },
          }, submitting ? '发送中...' : '发送咨询')
        )
      )
    )
  );
}

// ========== 导出 ==========
function withQaBoundary(Component) {
  return function (props) {
    return qaReact.createElement(QaErrorBoundary, {},
      qaReact.createElement(Component, props)
    );
  };
}

window.QaPage = withQaBoundary(QaPage);
window.QaQuestionPage = withQaBoundary(QaQuestionPage);
window.QaExpertsPage = withQaBoundary(QaExpertsPage);
window.QaConsultPage = withQaBoundary(QaConsultPage);
