// Post creation flow.

const PO_BG = '#000';
const PO_CARD = '#0E0E0E';
const PO_TEXT = '#EDEEF0';
const PO_MUTED = '#7A7E85';
const PO_DIVIDER = '#1B1D22';
const PO_BLUE = '#1772F6';
const PO_BLUE_SOFT = '#1B3556';

function PoIcon({ k, color, size = 14 }) {
  const c = color || PO_TEXT;
  const p = { width: size, height: size, viewBox: '0 0 24 24', fill: 'none', stroke: c, strokeWidth: 1.6, strokeLinecap: 'round', strokeLinejoin: 'round' };
  if (k === 'image')  return <svg {...p}><rect x="4" y="5" width="16" height="14" rx="2"/><circle cx="9" cy="10" r="1.4"/><path d="M5 18 L10 13 L14 17 L17 14 L19 16"/></svg>;
  if (k === 'video')  return <svg {...p}><rect x="4" y="6" width="13" height="12" rx="1.5"/><path d="M17 10 L21 8 V16 L17 14 Z"/></svg>;
  if (k === 'hash')   return <svg {...p}><path d="M8 4 L6 20 M16 4 L14 20 M4 9 H20 M4 15 H20"/></svg>;
  if (k === 'poll')   return <svg {...p}><path d="M5 20 V12 M12 20 V6 M19 20 V14"/></svg>;
  if (k === 'smile')  return <svg {...p}><circle cx="12" cy="12" r="8"/><path d="M9 14 Q12 17 15 14"/></svg>;
  if (k === 'more')   return <svg {...p}><circle cx="12" cy="12" r="8"/><circle cx="8" cy="12" r="0.5" fill={c}/><circle cx="12" cy="12" r="0.5" fill={c}/><circle cx="16" cy="12" r="0.5" fill={c}/></svg>;
  if (k === 'pen')    return <svg {...p}><path d="M14 4 L20 10 L9 21 L3 21 L3 15 Z"/></svg>;
  if (k === 'ai')     return <svg {...p}><path d="M12 5 V11 H6 M12 11 V19 M12 11 H18"/></svg>;
  if (k === 'at')     return <svg {...p}><circle cx="12" cy="12" r="3.5"/><path d="M15.5 12 V14 a2 2 0 0 0 4 0 V12 a8 8 0 1 0 -3 6.3"/></svg>;
  if (k === 'search') return <svg {...p}><circle cx="11" cy="11" r="6"/><path d="M16 16 L20 20"/></svg>;
  if (k === 'check')  return <svg {...p}><circle cx="12" cy="12" r="9"/><path d="M8 12 L11 15 L16 9"/></svg>;
  if (k === 'link')   return <svg {...p}><path d="M10 14 a4 4 0 0 0 5.7 0 L19 11 a4 4 0 0 0 -5.7 -5.7 L12 6.5"/><path d="M14 10 a4 4 0 0 0 -5.7 0 L5 13 a4 4 0 0 0 5.7 5.7 L12 17.5"/></svg>;
  if (k === 'tip')    return <svg {...p}><path d="M8 9 a4 4 0 0 1 8 0 c0 3 -4 3 -4 6 M12 18 v0.5"/><rect x="3" y="3" width="18" height="18" rx="2"/></svg>;
  return null;
}

// ─── Compose sheet ───────────────────────────────────────────────────────
function ComposeSheet({ onClose, onAsk }) {
  return (
    <div style={{
      position: 'absolute', inset: 0, background: PO_BG, color: PO_TEXT,
      display: 'flex', flexDirection: 'column',
      fontFamily: '-apple-system, "PingFang SC", "Helvetica Neue", sans-serif',
    }}>
      <div style={{ height: 38, flexShrink: 0 }}/>
      <div style={{ height: 36, padding: '0 14px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <div onClick={onClose} style={{ cursor: 'pointer', fontSize: 18 }}>×</div>
        <div style={{ fontSize: 12, color: PO_TEXT }}>草稿 (7)</div>
      </div>
      <div style={{ padding: '4px 14px 0' }}>
        <div style={{ display: 'inline-block', padding: '4px 10px', borderRadius: 11, background: PO_CARD, fontSize: 11, color: PO_TEXT }}>○ 发布到圈子</div>
      </div>
      <div style={{ padding: '12px 14px 0' }}>
        <div style={{ fontSize: 15, color: '#3F4248', fontWeight: 600 }}>标题</div>
        <div style={{ fontSize: 12, color: PO_MUTED, marginTop: 10 }}>分享你此刻的想法...</div>
      </div>
      <div style={{ padding: '16px 14px 0' }}>
        <div style={{ width: 72, height: 72, borderRadius: 5, background: '#16181C', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 4, color: PO_MUTED, fontSize: 10 }}>
          <span style={{ fontSize: 17, color: PO_MUTED }}>+</span>图片/视频
        </div>
      </div>
      <div style={{ flex: 1 }}/>
      <div style={{ padding: '12px 14px 10px', display: 'flex', alignItems: 'center', gap: 16, borderTop: '1px solid ' + PO_DIVIDER }}>
        <PoIcon k="image" size={18}/><PoIcon k="video" size={18}/><PoIcon k="hash" size={18}/><PoIcon k="poll" size={18}/><PoIcon k="smile" size={18}/><PoIcon k="more" size={18}/>
        <div style={{ flex: 1 }}/>
        <PoIcon k="pen" size={18}/><PoIcon k="ai" color="#9D6BFF" size={18}/>
      </div>
      <div style={{ padding: '8px 10px 26px', display: 'flex', gap: 6 }}>
        <div onClick={onAsk} style={modeBtn('#0E8C5C')}>提问题</div>
        <div style={modeBtn(PO_BLUE_SOFT)}>写回答</div>
        <div style={modeBtn('#8A5D1F')}>发文章</div>
      </div>
    </div>
  );
}

function modeBtn(bg) {
  return {
    flex: 1, padding: '9px 0', borderRadius: 6,
    background: bg, color: '#fff',
    textAlign: 'center',
    fontSize: 12, fontWeight: 600, cursor: 'pointer',
  };
}

// ─── Topic data ──────────────────────────────────────────────────────────
const PO_TOPICS = [
  { tag: '知乎新春游戏庆典', count: '9.4 万讨论' },
  { tag: '极地邮轮遭遇汉坦病毒之劫', count: '1844 讨论' },
  { tag: '2024 巴黎奥运会', count: '105 万讨论' },
  { tag: '2023 高考', count: '23.6 万讨论' },
  { tag: '塞尔达传说：王国之泪', count: '21.5 万讨论' },
  { tag: '以一句话为开头写作', count: '572 万讨论' },
  { tag: '好生活，选出来', count: '64.8 万讨论' },
  { tag: '崩坏：星穹铁道（游戏）', count: '231 万讨论' },
  { tag: '新职人密档', count: '4.4 万讨论' },
  { tag: '漫长的季节（电视剧）', count: '16.3 万讨论' },
  { tag: '瞬息全宇宙（电影）', count: '4.5 万讨论' },
];

// ─── Mention user data ──────────────────────────────────────────────────
const PO_USERS = [
  { name: '涂子', sub: '游戏开发等 3 个话题下的优秀答主', color: '#5A8FCC', badge: true },
  { name: '曹多鱼', sub: '知势榜经济与管理领域影响力榜答主', color: '#FFB37E', badge: true },
  { name: '徐斌', sub: '新知答主', color: '#7E84D9', verified: true },
  { name: '糖喵', sub: '爱掉书袋，圈地自萌', color: '#D8D8D8', verified: true },
  { name: 'Mr 深水聊医史', sub: '老媒人 书虫 医史研究僧', color: '#B89A75' },
  { name: 'Terminus', sub: 'CE&ECN双学位，年薪百万，硅谷初创公司 C...', color: '#1F2933' },
  { name: 'Mercer', sub: '新知答主', color: '#9CB1C7', badge: true },
  { name: 'TomZhang', sub: '曲径通幽处 柳暗花明时', color: '#3A3D44', verified: true },
  { name: 'import 潘多拉', sub: '作家，程序员，闲散人士', color: '#B0817F', verified: true },
  { name: '想玩游戏的程序员', sub: '粗糙的程序员', color: '#5C5E66' },
  { name: '知乎用户 AnmLMs', sub: '', color: '#5DA9F0' },
  { name: '时间之外的故人', sub: '', color: '#E8E2C8' },
];

// ─── Ask page (full integrated flow) ─────────────────────────────────────
function AskPage({ onClose, onPublish }) {
  const [title, setTitle] = React.useState('');
  const [body, setBody] = React.useState('');
  const [topics, setTopics] = React.useState([]);
  const [panel, setPanel] = React.useState(null); // null | 'topics' | 'mentions' | 'more'
  const [tipOpen, setTipOpen] = React.useState(false);
  const can = title.trim().length > 0;

  return (
    <div style={{
      position: 'absolute', inset: 0, background: PO_BG, color: PO_TEXT,
      display: 'flex', flexDirection: 'column',
      fontFamily: '-apple-system, "PingFang SC", "Helvetica Neue", sans-serif',
    }}>
      <div style={{ height: 38, flexShrink: 0 }}/>
      <div style={{ height: 34, padding: '0 12px', display: 'flex', alignItems: 'center', position: 'relative' }}>
        <div onClick={onClose} style={{ cursor: 'pointer', fontSize: 16, width: 20 }}>×</div>
        <div style={{ position: 'absolute', left: 0, right: 0, textAlign: 'center', fontSize: 12, fontWeight: 600, pointerEvents: 'none' }}>提问</div>
        <div style={{ flex: 1 }}/>
        <div onClick={can ? () => onPublish(title, body, topics) : undefined} style={{
          padding: '3px 12px', borderRadius: 11,
          background: can ? PO_BLUE : '#1F2933',
          color: can ? '#fff' : '#5A5E66',
          fontSize: 10, fontWeight: 600,
          cursor: can ? 'pointer' : 'default',
        }}>发布</div>
      </div>
      <div style={{ padding: '10px 12px 6px' }}>
        <input value={title} onChange={(e) => setTitle(e.target.value)} placeholder="输入问题并以问号结尾（必填）"
          style={{ width: '100%', background: 'transparent', border: 'none', outline: 'none', color: PO_TEXT, fontSize: 13, padding: 0 }}/>
        <div style={{ marginTop: 8, height: 1, background: PO_DIVIDER }}/>
      </div>
      <div style={{ padding: '4px 12px', flex: 1, display: 'flex', flexDirection: 'column' }}>
        <textarea value={body} onChange={(e) => setBody(e.target.value)} placeholder="详细说明问题，快速获得专业解答（选填）"
          style={{ width: '100%', background: 'transparent', border: 'none', outline: 'none', color: PO_TEXT, fontSize: 11, padding: 0, resize: 'none', flex: 1, fontFamily: 'inherit' }}/>
      </div>

      {/* Tip card */}
      {tipOpen && (
        <div style={{ margin: '0 12px 6px', background: '#15161A', borderRadius: 6, padding: '10px 12px' }}>
          <div style={{ display: 'flex', alignItems: 'center' }}>
            <div style={{ flex: 1, fontSize: 11, fontWeight: 600 }}>如何更好地提问？</div>
            <div onClick={() => setTipOpen(false)} style={{ cursor: 'pointer', color: PO_MUTED, fontSize: 12 }}>×</div>
          </div>
          {[
            ['规范准确', '规范使用语句标点清晰表述'],
            ['讨论价值', '鼓励专业、实用、脑洞等价值讨论'],
            ['客观真实', '理性客观地陈述问题和事实'],
          ].map(([a, b]) => (
            <div key={a} style={{ display: 'flex', marginTop: 6, fontSize: 9.5 }}>
              <div style={{ color: PO_TEXT, width: 70 }}>{a}</div>
              <div style={{ flex: 1, textAlign: 'right', color: PO_MUTED }}>{b}</div>
            </div>
          ))}
        </div>
      )}

      {/* Topic chips */}
      {topics.length > 0 && (
        <div style={{ padding: '4px 12px 6px', display: 'flex', gap: 5, overflowX: 'auto', whiteSpace: 'nowrap' }}>
          {topics.map((t) => (
            <div key={t} onClick={() => setTopics((p) => p.filter((x) => x !== t))} style={{
              flexShrink: 0,
              padding: '3px 9px', borderRadius: 11,
              background: PO_BLUE_SOFT, color: '#7FB0F2',
              fontSize: 10, cursor: 'pointer',
            }}>#{t} ×</div>
          ))}
        </div>
      )}

      {/* Bottom 4 icons */}
      <div style={{ padding: '8px 30px 6px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        {[
          ['hash', 'topics'],
          ['at', 'mentions'],
          ['image', 'image'],
          ['more', 'more'],
        ].map(([k, p]) => (
          <div key={k} onClick={() => setPanel(panel === p ? null : p)} style={{ cursor: 'pointer', padding: 4 }}>
            <PoIcon k={k} size={20} color={panel === p ? PO_BLUE : PO_TEXT}/>
          </div>
        ))}
      </div>

      {/* More panel */}
      {panel === 'more' && (
        <div style={{ padding: '6px 14px 24px' }}>
          <div style={{ fontSize: 10, color: PO_MUTED, marginBottom: 6 }}>更多功能</div>
          <div style={{ display: 'flex', gap: 16 }}>
            <div style={{ width: 48, textAlign: 'center', cursor: 'pointer' }}>
              <div style={{ width: 36, height: 36, borderRadius: 6, background: '#15161A', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto' }}>
                <PoIcon k="link" size={16}/>
              </div>
              <div style={{ fontSize: 9, marginTop: 4 }}>链接卡片</div>
            </div>
            <div onClick={() => { setTipOpen(true); setPanel(null); }} style={{ width: 48, textAlign: 'center', cursor: 'pointer' }}>
              <div style={{ width: 36, height: 36, borderRadius: 6, background: '#15161A', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto' }}>
                <PoIcon k="tip" size={16}/>
              </div>
              <div style={{ fontSize: 9, marginTop: 4 }}>提问建议</div>
            </div>
          </div>
        </div>
      )}

      {panel === 'image' && (
        <div style={{ padding: '10px 14px 24px', fontSize: 10, color: PO_MUTED }}>暂无相册权限</div>
      )}

      {/* Topics sheet overlay */}
      {panel === 'topics' && (
        <TopicsSheetInline picked={topics} setPicked={setTopics} onDone={() => setPanel(null)}/>
      )}

      {/* Mentions full-screen overlay */}
      {panel === 'mentions' && (
        <MentionsPage onCancel={() => setPanel(null)} onPick={(u) => {
          setBody((b) => b + (b ? '\n' : '') + '@' + u);
          setPanel(null);
        }}/>
      )}
    </div>
  );
}

// Inline topics bottom sheet (used inside AskPage)
function TopicsSheetInline({ picked, setPicked, onDone }) {
  const toggle = (t) => setPicked((prev) => prev.includes(t) ? prev.filter((x) => x !== t) : prev.length >= 3 ? prev : [...prev, t]);
  const remaining = 3 - picked.length;
  const visible = PO_TOPICS.filter((t) => !picked.includes(t.tag));
  return (
    <div style={{
      position: 'absolute', left: 0, right: 0, bottom: 0,
      maxHeight: '55%', background: '#0B0C0F',
      borderTopLeftRadius: 10, borderTopRightRadius: 10,
      display: 'flex', flexDirection: 'column',
      boxShadow: '0 -8px 24px rgba(0,0,0,0.4)',
    }}>
      <div style={{ display: 'flex', justifyContent: 'center', padding: '7px 0 2px' }}>
        <div style={{ width: 28, height: 3, borderRadius: 1.5, background: '#3A3D44' }}/>
      </div>
      <div style={{ padding: '4px 14px', display: 'flex', alignItems: 'center' }}>
        <div style={{ fontSize: 13, fontWeight: 700 }}>添加话题</div>
        <div style={{ flex: 1 }}/>
        <div onClick={onDone} style={{
          padding: '3px 11px', borderRadius: 11,
          background: picked.length ? PO_BLUE : '#1F2933',
          color: picked.length ? '#fff' : '#5A5E66',
          fontSize: 11, fontWeight: 600, cursor: 'pointer',
        }}>完成</div>
      </div>
      <div style={{ padding: '8px 14px' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 7, padding: '7px 9px', borderRadius: 5, background: '#16181C' }}>
          <PoIcon k="search" color={PO_MUTED} size={12}/>
          <span style={{ fontSize: 11, color: PO_MUTED }}>搜索话题</span>
        </div>
      </div>
      <div style={{ padding: '0 14px 6px', fontSize: 10, color: PO_MUTED }}>
        {picked.length === 0 ? '添加相关话题可以被更多人看到' : '还可添加 ' + remaining + ' 个话题'}
      </div>
      {picked.length > 0 && (
        <div style={{ padding: '4px 14px 8px', display: 'flex', flexWrap: 'wrap', gap: 6 }}>
          {picked.map((t) => (
            <div key={t} onClick={() => toggle(t)} style={{
              padding: '3px 9px', borderRadius: 11,
              background: PO_BLUE_SOFT, color: '#7FB0F2',
              fontSize: 10, cursor: 'pointer',
            }}>{t} ×</div>
          ))}
        </div>
      )}
      <div style={{ height: 1, background: PO_DIVIDER, margin: '0 14px' }}/>
      <div style={{ flex: 1, overflowY: 'auto' }}>
        {visible.map((t, i) => (
          <div key={t.tag} onClick={() => toggle(t.tag)} style={{
            padding: '11px 14px', display: 'flex', alignItems: 'center',
            cursor: 'pointer',
            borderBottom: i < visible.length - 1 ? '1px solid ' + PO_DIVIDER : 'none',
          }}>
            <div style={{ flex: 1, color: '#7FB0F2', fontSize: 12 }}>#{t.tag}</div>
            <div style={{ color: PO_MUTED, fontSize: 10 }}>{t.count}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

// Full-screen mention picker
function MentionsPage({ onCancel, onPick }) {
  return (
    <div style={{
      position: 'absolute', inset: 0, background: PO_BG,
      display: 'flex', flexDirection: 'column', zIndex: 10,
    }}>
      <div style={{ height: 38, flexShrink: 0 }}/>
      <div style={{ padding: '8px 12px', display: 'flex', alignItems: 'center', gap: 10 }}>
        <div style={{ flex: 1, display: 'flex', alignItems: 'center', gap: 7, padding: '6px 10px', borderRadius: 16, background: '#16181C' }}>
          <PoIcon k="search" color={PO_MUTED} size={12}/>
          <span style={{ fontSize: 11, color: PO_MUTED }}>搜索用户</span>
        </div>
        <div onClick={onCancel} style={{ fontSize: 12, color: '#7FB0F2', cursor: 'pointer' }}>取消</div>
      </div>
      <div style={{ flex: 1, overflowY: 'auto' }}>
        {PO_USERS.map((u, i) => (
          <div key={i} onClick={() => onPick(u.name)} style={{
            padding: '9px 12px', display: 'flex', alignItems: 'center', gap: 10,
            cursor: 'pointer',
          }}>
            <div style={{ width: 30, height: 30, borderRadius: 15, background: u.color, flexShrink: 0, position: 'relative' }}>
              {u.badge && (
                <div style={{ position: 'absolute', right: -1, bottom: -1, width: 9, height: 9, borderRadius: 4.5, background: '#E68B45', color: '#fff', fontSize: 6, display: 'flex', alignItems: 'center', justifyContent: 'center', border: '1px solid #000' }}>★</div>
              )}
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 11.5, fontWeight: 600, display: 'flex', alignItems: 'center', gap: 4 }}>
                {u.name}
                {u.verified && <span style={{ width: 9, height: 9, borderRadius: 4.5, background: PO_BLUE, color: '#fff', fontSize: 6, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>✓</span>}
              </div>
              {u.sub && <div style={{ fontSize: 9, color: PO_MUTED, marginTop: 2 }}>{u.sub}</div>}
            </div>
            <div style={{ padding: '3px 10px', borderRadius: 11, background: '#1F2933', color: PO_MUTED, fontSize: 9.5 }}>已关注</div>
          </div>
        ))}
      </div>
    </div>
  );
}

// ─── Topics sheet (post-publish) ─────────────────────────────────────────
function TopicsSheet({ onDone }) {
  const [picked, setPicked] = React.useState([]);
  return (
    <div style={{
      position: 'absolute', inset: 0, background: 'rgba(0,0,0,0.5)',
      display: 'flex', flexDirection: 'column', justifyContent: 'flex-end',
      color: PO_TEXT,
      fontFamily: '-apple-system, "PingFang SC", "Helvetica Neue", sans-serif',
    }}>
      <div style={{ flex: 1 }} onClick={() => onDone([])}/>
      <div style={{ background: PO_BG, borderTopLeftRadius: 10, borderTopRightRadius: 10, maxHeight: '72%', display: 'flex', flexDirection: 'column' }}>
        <TopicsSheetInline picked={picked} setPicked={setPicked} onDone={() => onDone(picked)}/>
      </div>
    </div>
  );
}

// ─── Question created ────────────────────────────────────────────────────
const PO_INVITEES = [
  { name: '大橘为重', sub: 'TA 已帮助 31 人获得解答', avatar: '#D89A52' },
  { name: '曹多鱼', sub: 'TA 的回答被编辑推荐过', avatar: '#FFB37E', badge: true },
  { name: 'Kfeimeo', sub: 'TA 已帮助 260 人获得解答', avatar: '#A1AAB5' },
  { name: '一剑曾当百万师', sub: 'TA 已帮助 1111 人获得解答', avatar: '#7E84D9' },
];

function QuestionCreatedPage({
  title, onClose, onMirrorAnswer, onSourceTap, onAuthorTap, onLike,
  // mirrorOpen state 由 LeftPhone 控制, 这样跨屏 mount/unmount 也保留
  mirrorOpen: mirrorOpenProp, setMirrorOpen: setMirrorOpenProp,
  // mirrorCache 也由 LeftPhone 控制, 缓存 pipeline 结果 + 滚动位置, 防止返回时重跑
  mirrorCache, setMirrorCache,
  // tour 后期: 答主二次作答内容 + 顶部 banner + synthesis 可见性反馈
  // 离题分支: einsteinAnswer (神秘专家答案)
  newRealAnswer, einsteinAnswer, leftBanner, onBannerDismiss, onSynthesisVisibilityChange,
}) {
  // "开启重要消息通知" 弹窗 — 只在第一次发布问题时弹一次, 之后用 localStorage 记住, 不再打扰.
  // 用户点 × 或 "去开启" 都算"已经看过", 永久 dismiss.
  const NOTIFY_MODAL_KEY = 'notify_modal_seen_v1';
  const [showModal, setShowModal] = React.useState(() => {
    try { return localStorage.getItem(NOTIFY_MODAL_KEY) !== '1'; } catch { return true; }
  });
  const dismissNotifyModal = React.useCallback(() => {
    try { localStorage.setItem(NOTIFY_MODAL_KEY, '1'); } catch {}
    setShowModal(false);
  }, []);
  // 兼容: 如果 props 没传 (旧调用), 走本地 state
  const [mirrorOpenLocal, setMirrorOpenLocal] = React.useState(false);
  const mirrorOpen = mirrorOpenProp != null ? mirrorOpenProp : mirrorOpenLocal;
  const setMirrorOpen = setMirrorOpenProp || setMirrorOpenLocal;
  const bodyScrollRef = React.useRef(null);
  // 跟踪一次"打开" 内是否已经恢复过滚动位置. 避免每次 mirrorCache 更新都强制滚.
  const hasRestoredScrollRef = React.useRef(false);

  // mirrorOpen 关闭时重置 "已恢复" 标记 — 下次打开还能再恢复一次
  React.useEffect(() => {
    if (!mirrorOpen) hasRestoredScrollRef.current = false;
  }, [mirrorOpen]);

  // 触发后处理滚动: 缓存命中 (返回场景) 恢复到上次位置; 否则首次打开滚到底.
  // 依赖 mirrorCache?.scenario, 这样 InlineMirrorPanel 把 scenario 渲染好后再触发.
  React.useEffect(() => {
    if (!mirrorOpen) return;
    if (!bodyScrollRef.current) return;
    if (hasRestoredScrollRef.current) return;
    const cachedScroll = mirrorCache && mirrorCache.scrollTop;
    // 双 RAF 等 InlineMirrorPanel 内容渲染完
    requestAnimationFrame(() => {
      requestAnimationFrame(() => {
        if (!bodyScrollRef.current) return;
        if (cachedScroll && cachedScroll > 0) {
          bodyScrollRef.current.scrollTop = cachedScroll;
        } else {
          bodyScrollRef.current.scrollTop = bodyScrollRef.current.scrollHeight;
        }
        hasRestoredScrollRef.current = true;
      });
    });
  }, [mirrorOpen, mirrorCache?.scenario]);

  // 包装 onSourceTap: 跳转前把当前 scrollTop 写入缓存, 返回时能恢复
  const wrappedOnSourceTap = onSourceTap ? (sourceQid) => {
    if (bodyScrollRef.current && setMirrorCache) {
      const top = bodyScrollRef.current.scrollTop;
      setMirrorCache(prev => prev ? { ...prev, scrollTop: top } : prev);
    }
    onSourceTap(sourceQid);
  } : null;

  // 包装 onAuthorTap: 同样跳转前保存 scrollTop, 返回时还能回到原位
  const wrappedOnAuthorTap = onAuthorTap ? (authorId) => {
    if (bodyScrollRef.current && setMirrorCache) {
      const top = bodyScrollRef.current.scrollTop;
      setMirrorCache(prev => prev ? { ...prev, scrollTop: top } : prev);
    }
    onAuthorTap(authorId);
  } : null;

  return (
    <div style={{
      position: 'absolute', inset: 0, background: PO_BG, color: PO_TEXT,
      display: 'flex', flexDirection: 'column',
      fontFamily: '-apple-system, "PingFang SC", "Helvetica Neue", sans-serif',
    }}>
      <div style={{ height: 38, flexShrink: 0 }}/>
      <div style={{ height: 34, padding: '0 12px', display: 'flex', alignItems: 'center', gap: 10 }}>
        <div onClick={onClose} style={{ cursor: 'pointer', fontSize: 14, width: 16 }}>‹</div>
        <div style={{ flex: 1 }}/>
        <PoIcon k="search"/>
      </div>
      <div style={{ padding: '4px 12px 10px', display: 'flex', alignItems: 'flex-start' }}>
        <div style={{ flex: 1, fontSize: 13, fontWeight: 700 }}>{title || '新问题?'}</div>
      </div>
      <div style={{ height: 1, background: PO_DIVIDER }}/>
      <div style={{ padding: '10px 12px', display: 'flex', alignItems: 'flex-start' }}>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 11, fontWeight: 700 }}>邀请知友为你解答</div>
          <div style={{ fontSize: 8.5, color: PO_MUTED, marginTop: 3 }}>邀请更多知友，更好更快获得解答</div>
        </div>
        <div style={{ display: 'flex', gap: 6, alignItems: 'center', flexShrink: 0 }}>
          <div onClick={() => {
            setMirrorOpen(true);
            // 若上游传了 onMirrorAnswer (老路由用), 跳过它 — 我们就地展开
            if (onMirrorAnswer && false) onMirrorAnswer(title);
          }} style={{
            padding: '3px 9px', borderRadius: 10,
            border: `1px solid ${PO_BLUE}`,
            background: mirrorOpen ? PO_BLUE : 'transparent',
            color: mirrorOpen ? '#fff' : PO_BLUE,
            fontSize: 10, fontWeight: 600, cursor: 'pointer',
            whiteSpace: 'nowrap',
          }}>镜像回答</div>
          <div style={{
            padding: '3px 9px', borderRadius: 10,
            background: PO_BLUE, color: '#fff', fontSize: 10, fontWeight: 600, cursor: 'pointer',
            whiteSpace: 'nowrap',
          }}>一键邀请</div>
        </div>
      </div>
      <div ref={bodyScrollRef} style={{ flex: 1, overflowY: 'auto' }}>
        {!mirrorOpen && PO_INVITEES.map((p, i) => (
          <div key={i} style={{ padding: '8px 12px', display: 'flex', alignItems: 'center', gap: 8 }}>
            <div style={{ width: 26, height: 26, borderRadius: 13, background: p.avatar, flexShrink: 0 }}/>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 10.5, fontWeight: 600 }}>{p.name}</div>
              <div style={{ fontSize: 8.5, color: PO_MUTED, marginTop: 2 }}>{p.sub}</div>
            </div>
            <div style={{ padding: '2px 9px', borderRadius: 10, border: '1px solid ' + PO_BLUE_SOFT, color: '#7FB0F2', fontSize: 9, cursor: 'pointer' }}>邀请</div>
          </div>
        ))}

        {/* 就地展开的镜像回答 panel — 不跳新屏 */}
        {mirrorOpen && typeof InlineMirrorPanel === 'function' && (
          <InlineMirrorPanel
            query={title || ''}
            onCollapse={() => setMirrorOpen(false)}
            onSourceTap={wrappedOnSourceTap}
            onAuthorTap={wrappedOnAuthorTap}
            onLike={onLike}
            newRealAnswer={newRealAnswer}
            einsteinAnswer={einsteinAnswer}
            leftBanner={leftBanner}
            onBannerDismiss={onBannerDismiss}
            onSynthesisVisibilityChange={onSynthesisVisibilityChange}
            cache={mirrorCache}
            setCache={setMirrorCache}/>
        )}
      </div>
      {!mirrorOpen && (
        <div style={{ height: 42, flexShrink: 0, padding: '0 10px', display: 'flex', alignItems: 'center', gap: 5, borderTop: '1px solid ' + PO_DIVIDER }}>
          <div style={bottomBtn(true)}>写回答</div>
          <div style={bottomBtn(false)}>邀请回答</div>
          <div style={bottomBtn(false)}>好问题</div>
        </div>
      )}
      {showModal && (
        <div style={{ position: 'absolute', inset: 0, background: 'rgba(0,0,0,0.6)', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 18 }}>
          <div style={{ width: '86%', background: '#1A1B1F', borderRadius: 9, padding: '14px 16px 16px', position: 'relative', textAlign: 'center' }}>
            <div onClick={dismissNotifyModal} style={{ position: 'absolute', top: 6, right: 9, color: PO_MUTED, fontSize: 13, cursor: 'pointer' }}>×</div>
            <div style={{ width: 56, height: 56, borderRadius: 28, background: '#F4D24A', margin: '0 auto', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 24 }}>🔔</div>
            <div style={{ fontSize: 11.5, fontWeight: 700, marginTop: 10 }}>开启重要消息通知</div>
            <div style={{ fontSize: 9, color: PO_MUTED, marginTop: 4 }}>第一时间看到你提的问题的回答</div>
            <div onClick={dismissNotifyModal} style={{ marginTop: 12, padding: '7px 0', borderRadius: 16, background: PO_BLUE, color: '#fff', fontSize: 11, fontWeight: 600, cursor: 'pointer' }}>去开启</div>
          </div>
        </div>
      )}
    </div>
  );
}

function bottomBtn(primary) {
  return {
    flex: 1, padding: '6px 0', borderRadius: 14,
    background: primary ? PO_BLUE : 'transparent',
    color: primary ? '#fff' : PO_TEXT,
    textAlign: 'center',
    fontSize: 10, fontWeight: 600, cursor: 'pointer',
  };
}

function PublishToast() {
  return (
    <div style={{
      position: 'absolute', inset: 0, display: 'flex',
      alignItems: 'center', justifyContent: 'center',
      pointerEvents: 'none', zIndex: 50,
    }}>
      <div style={{
        padding: '8px 18px', borderRadius: 16,
        background: 'rgba(60, 60, 64, 0.92)', color: '#fff',
        fontSize: 11, fontWeight: 500,
        boxShadow: '0 4px 16px rgba(0,0,0,0.4)',
        display: 'flex', alignItems: 'center', gap: 6,
      }}>
        <PoIcon k="check" color="#fff" size={13}/>
        发布成功
      </div>
    </div>
  );
}

Object.assign(window, { ComposeSheet, AskPage, TopicsSheet, QuestionCreatedPage, PublishToast });
