/* Real administration entry. Features are added as their APIs become ready. */
function AdminLive() {
  const [user, setUser] = React.useState(null);
  const [checking, setChecking] = React.useState(true);
  const [email, setEmail] = React.useState('');
  const [password, setPassword] = React.useState('');
  const [error, setError] = React.useState('');
  const [busy, setBusy] = React.useState(false);
  const [dashboard, setDashboard] = React.useState(null);
  const [tab, setTab] = React.useState('dashboard');
  const [syncPostId,setSyncPostId]=React.useState(null);
  const [wecomEnabled,setWecomEnabled]=React.useState(false);

  React.useEffect(() => {
    let live = true;
    fetch('/api/auth/wecom/status').then(r=>r.ok?r.json():null)
      .then(data=>{if(live)setWecomEnabled(data?.enabled===true);}).catch(()=>{});
    fetch('/api/admin/me').then(async r => {
      if (!live) return;
      if (r.ok) setUser((await r.json()).user);
      else if (r.status !== 401) setError('无法读取登录状态，请稍后重试。');
    }).catch(() => { if (live) setError('无法连接后台，请检查网络。'); })
      .finally(() => { if (live) setChecking(false); });
    return () => { live = false; };
  }, []);

  React.useEffect(() => {
    if (!user) { setDashboard(null); return; }
    if (tab !== 'dashboard') return;
    let live = true;
    fetch('/api/admin/dashboard').then(async r => {
      if (!r.ok) throw new Error(r.status === 401 ? '登录已过期，请重新登录。' : '无法读取看板数据。');
      return r.json();
    }).then(data => { if (live) setDashboard(data); })
      .catch(e => { if (live) setError(e.message || '无法连接后台。'); });
    return () => { live = false; };
  }, [user, tab]);

  async function login(e) {
    e.preventDefault(); setError(''); setBusy(true);
    try {
      const r = await fetch('/api/admin/login', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ email, password }) });
      const body = await r.json();
      if (!r.ok) throw new Error(body.error?.message || '登录失败，请重试。');
      setPassword(''); setUser(body.user);
    } catch (e) { setError(e.message || '无法连接后台，请重试。'); }
    finally { setBusy(false); }
  }
  async function logout() {
    setError('');
    try {
      const r = await fetch('/api/admin/logout', { method: 'POST' });
      if (!r.ok) throw new Error('退出失败，请重试。');
      setUser(null); setTab('dashboard');
    } catch (e) { setError(e.message || '无法连接后台。'); }
  }

  const input = { width: '100%', padding: '11px 12px', border: '1px solid #cbdad9', borderRadius: 4, fontSize: 15 };
  const button = { padding: '10px 16px', border: 0, borderRadius: 4, background: '#17696e', color: '#fff', cursor: 'pointer' };
  if (checking) return <main style={{ padding: 40 }}>正在确认登录状态…</main>;
  if (!user) return <main className="qa-login">
    <form onSubmit={login}><div className="qa-mark">量</div>
      <h1 style={{ fontSize: 25, marginBottom: 8 }}>量子催眠中国 · 运营后台</h1>
      <p style={{ color: '#5e7878', marginBottom: 24 }}>请使用管理员账号登录</p>
      <label style={{ display: 'block', marginBottom: 16 }}>邮箱<input style={input} name="email" type="email" required autoComplete="username" value={email} onChange={e => setEmail(e.target.value)} /></label>
      <label style={{ display: 'block', marginBottom: 16 }}>密码<input style={input} name="password" type="password" required autoComplete="current-password" value={password} onChange={e => setPassword(e.target.value)} /></label>
      {error && <p role="alert" style={{ color: '#a63a30', marginBottom: 12 }}>{error}</p>}
      <button type="submit" disabled={busy} style={{ ...button, width: '100%' }}>{busy ? '正在登录…' : '登录'}</button>
      {wecomEnabled && <a href="/api/auth/wecom/start" style={{display:'block',textAlign:'center',marginTop:14,color:'#17696e'}}>企业微信扫码登录</a>}
      <button type="button" onClick={() => window.__go && window.__go('home')} style={{ marginTop: 12, background: 'none', border: 0, color: '#17696e', cursor: 'pointer' }}>返回官网</button>
    </form>
  </main>;

  const groups = [
    ['工作台', [['dashboard','看板','总览']]],
    ['内容运营', [['articles','文章','01'],['categories','文章分类',''],['courses','课程','02'],['events','活动与相册','03'],['voices','学员证言','04'],['books','书籍','05'],['videos','影像','06'],['faqs','常见问题','07']]],
    ...(user.role !== 'editor' ? [['报名运营', [['orders','报名与订单','订单']]]] : []),
    ['站点管理', [['wechat','公众号连接与同步','微信'],['settings','站点设置','设置'],['accounts','账号与权限','账号']]]
  ];
  const current = groups.flatMap(g => g[1]).find(([key]) => key === tab);
  const roles = { owner:'站点所有者', admin:'管理员', editor:'编辑员' };
  return <div className="qa-admin">
    <aside className="qa-sidebar">
      <div className="qa-brand"><span className="qa-mark">量</span><div><strong>量子催眠中国</strong><span>官网运营工作台</span></div></div>
      <nav aria-label="后台栏目">
        {groups.map(([group, links]) => <div className="qa-nav-group" key={group}><p>{group}</p>
          {links.map(([key,label,code]) => <button key={key} type="button" aria-current={tab === key ? 'page' : undefined} onClick={() => { setError(''); setTab(key); }}><small aria-hidden="true">{code}</small>{label}</button>)}
        </div>)}
      </nav>
      <div className="qa-account"><strong>{roles[user.role] || user.role}</strong><span>{user.email}</span></div>
    </aside>
    <div className="qa-workspace">
      <header className="qa-topbar"><span>运营工作台 <span aria-hidden="true">/</span> <strong>{current?.[1]}</strong></span>
        <div><button type="button" onClick={() => window.__go && window.__go('home')}>返回官网</button><button type="button" onClick={logout}>退出登录</button></div>
      </header>
      <main className="qa-content">
        {error && <p role="alert">{error}</p>}
        {tab === 'dashboard' && <section>
          <div className="qa-overview"><div><p>内容运营</p><h1>运营看板</h1><span>查看官网内容状态，继续编辑文章或维护活动。</span></div>
            <button type="button" onClick={() => setTab('articles')}>管理文章</button></div>
          {!dashboard ? <p className="qa-empty">正在读取数据…</p> : <div className="qa-stats">
            {[["已发布文章",dashboard.content.posts,"articles"],["草稿",dashboard.content.drafts,"articles"],["近期活动",dashboard.content.eventsUpcoming,"events"],["往期活动",dashboard.content.eventsPast,"events"],["展示中证言",dashboard.content.voices,"voices"],...(user.role !== 'editor' ? [["待处理订单",dashboard.enrollments.pending,"orders"]] : [])].map(([label,count,key]) =>
              <button key={label} type="button" onClick={() => setTab(key)}><span>{label}</span><strong>{count}</strong></button>)}
          </div>}
          <div className="qa-quick"><h2>常用操作</h2>
            {[['articles','管理文章','撰写文章，导入微信 HTML 或管理草稿'],['events','活动与相册','维护活动信息与现场照片'],['settings','站点设置','更换品牌图片和联系方式']].map(([key,label,desc]) =>
              <button key={key} type="button" onClick={() => setTab(key)}><span><strong>{label}</strong><small>{desc}</small></span><span aria-hidden="true">›</span></button>)}
          </div>
        </section>}
        {tab === 'orders' && user.role !== 'editor' && <AdminEnrollments />}
        {tab === 'wechat' && <AdminWechat canConfigure={user.role !== 'editor'} onOpenArticle={id=>{setSyncPostId(id);setTab('articles');}} />}
        {tab === 'articles' && <AdminArticles initialPostId={syncPostId} onOpened={()=>setSyncPostId(null)} />}
        {tab === 'categories' && <AdminPostCategories canManage={user.role !== 'editor'} />}
        {ADMIN_COLLECTIONS[tab] && <AdminCollection key={tab} type={tab} canEdit={tab !== 'courses' || user.role !== 'editor'} canFinance={user.role !== 'editor'} />}
        {tab === 'settings' && <AdminSettings canEdit={user.role !== 'editor'} />}
        {tab === 'accounts' && <AdminAccounts user={user} />}
      </main>
    </div>
  </div>;
}
window.AdminLive = AdminLive;

function AdminEnrollments() {
  const [query, setQuery] = React.useState('');
  const [filters, setFilters] = React.useState({ q:'', kind:'', status:'', offset:0 });
  const [rows, setRows] = React.useState(null);
  const [revision, reload] = React.useReducer(n => n + 1, 0);
  const [selection, setSelection] = React.useState(null);
  const [busy, setBusy] = React.useState(false);
  const [error, setError] = React.useState('');
  const [notice, setNotice] = React.useState('');
  const labels = { approve:'通过资格', confirmRegistration:'确认报名', cancel:'取消报名' };
  React.useEffect(() => {
    let active = true;
    setRows(null);
    enrollRequest('/api/admin/enrollments?' + new URLSearchParams(filters)).then(data => { if (active) setRows(data); })
      .catch(e => { if (active) setError(e.message || '读取订单失败。'); });
    return () => { active = false; };
  }, [filters, revision]);
  function filter(patch) {
    setError(''); setNotice(''); setSelection(null); setFilters(current => ({ ...current, offset:0, ...patch }));
  }
  async function submit(e) {
    e.preventDefault(); setBusy(true); setError(''); setNotice('');
    const values = new FormData(e.currentTarget);
    const { row, action } = selection;
    const payload = { action };
    if (action === 'cancel') payload.reference = String(values.get('reference') || '').trim();
    try {
      await enrollRequest('/api/admin/enrollments/' + encodeURIComponent(row.order_no), {method:'PATCH',headers:{'content-type':'application/json'},body:JSON.stringify(payload)});
      setNotice(labels[action] + '已保存 · ' + row.order_no); setSelection(null); reload();
    } catch (e) { setError(e.message || '订单更新失败。'); }
    finally { setBusy(false); }
  }
  return <section className="qa-orders">
    <div className="qa-list-heading"><div><h1>报名与订单</h1><p>查看课程与活动报名，审核资格和管理已占用的名额。</p></div><button type="button" disabled={busy} onClick={() => {setError('');reload();}}>刷新列表</button></div>
    <form className="qa-order-filters" onSubmit={e => {e.preventDefault();filter({q:query.trim()});}}>
      <label>搜索订单<input value={query} onChange={e => setQuery(e.target.value)} placeholder="订单号、姓名或微信号" maxLength={100} /></label>
      <label>报名类型<select value={filters.kind} disabled={busy} onChange={e => filter({kind:e.target.value})}><option value="">全部类型</option><option value="course">课程 / 套餐</option><option value="event">活动</option></select></label>
      <label>订单状态<select value={filters.status} disabled={busy} onChange={e => filter({status:e.target.value})}><option value="">全部状态</option>{Object.entries(ENROLL_STATUS).map(([key,label]) => <option key={key} value={key}>{label}</option>)}</select></label>
      <button type="submit" disabled={busy}>搜索</button>
    </form>
    {notice && <p role="status" className="qa-order-notice">{notice}</p>}
    {error && <p role="alert" className="enrollment-error">{error}</p>}
    {selection && <form className="qa-order-action" onSubmit={submit} key={selection.row.order_no + ':' + selection.action}>
      <h2>{labels[selection.action]}</h2>
      <p>{selection.row.course_title || '历史报名'} · {selection.row.name}</p>
      {selection.action === 'approve' && <p>参训或证书信息：{selection.row.prerequisite_ref || '未填写'}。请核对后通过。</p>}
      {selection.action === 'cancel' && <>
        <p>取消后会释放该报名的名额。</p>
        <label>取消原因<input name="reference" required maxLength={160} /></label>
      </>}
      <div><button type="submit" disabled={busy}>{busy ? '保存中…' : '保存' + labels[selection.action]}</button> <button type="button" disabled={busy} onClick={() => {setSelection(null);setError('');}}>返回列表</button></div>
    </form>}
    {!rows ? <p className="qa-empty">{error ? '请刷新重试。' : '正在读取报名订单…'}</p> : rows.items.length === 0 ? <p className="qa-empty">暂无匹配的报名订单。</p> : <>
      <p className="qa-order-count">共 {rows.total} 笔 · 当前显示 {filters.offset + 1}–{filters.offset + rows.items.length} 笔</p>
      <div className="qa-order-list">{rows.items.map(row => {
        const reviewing = row.payment === 'pending' && row.approval_required && !row.approved_at;
        const status = row.payment === 'paid' ? 'confirmed' : row.payment;
        const cancellable = status === 'pending' || row.payment === 'confirmed' || (row.payment === 'paid' && row.amount_cents === 0);
        const actions = status === 'pending' ? [reviewing ? 'approve' : 'confirmRegistration', 'cancel'] : cancellable ? ['cancel'] : [];
        const timestamp = row.created_at?.includes('T') ? row.created_at : row.created_at?.replace(' ','T') + 'Z';
        return <article key={row.order_no} className="qa-order-row">
          <div><small>{row.event_id ? '活动' : row.bundle ? '课程套餐' : '课程'} · {row.order_no}</small><strong>{row.course_title || row.course_id || '历史报名'}</strong><small>{row.created_at && enrollDate(timestamp)}</small></div>
          <div><strong>{row.name}</strong><small>微信：{row.wechat}</small>{row.phone && <small>手机：{row.phone}</small>}</div>
          <div><span className="qa-status">{reviewing ? '待审核资格' : ENROLL_STATUS[status] || status}</span>
            {row.payment === 'pending' && row.expires_at && <small>保留至 {enrollDate(row.expires_at)}</small>}{row.close_reason && <small>{row.close_reason}</small>}</div>
          <div className="qa-order-actions">{actions.map(action => <button key={action} type="button" disabled={busy} onClick={() => {setError('');setSelection({row,action});document.querySelector('.qa-orders')?.scrollIntoView({block:'start'});}}>{labels[action]}</button>)}</div>
        </article>;
      })}</div>
    </>}
    {!!rows && (filters.offset > 0 || filters.offset + 50 < rows.total) && <div className="qa-order-actions">
      <button type="button" disabled={!filters.offset || busy} onClick={() => filter({offset:Math.max(0,filters.offset-50)})}>上一页</button>
      <button type="button" disabled={filters.offset+50 >= rows.total || busy} onClick={() => filter({offset:filters.offset+50})}>下一页</button>
    </div>}
  </section>;
}



function articleBlocksToHtml(blocks) {
  const escape = value => String(value || '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
  return (blocks || []).map(b => {
    const kind = Array.isArray(b) ? b[0] : b.type;
    const value = Array.isArray(b) ? b[1] : b.text;
    if (kind === 'html') return value || '';
    const tag = kind === 'h2' ? 'h2' : kind === 'q' ? 'blockquote' : 'p';
    return '<' + tag + '>' + escape(value).replace(/\n/g, '<br>') + '</' + tag + '>';
  }).join('');
}

function articleCanvas(html = '') {
  return '<!doctype html><html lang="zh"><meta charset="utf-8">' +
    `<meta http-equiv="Content-Security-Policy" content="default-src 'none'; img-src https: http: data:; style-src 'unsafe-inline' https: http:; base-uri 'none'; form-action 'none'">` +
    '<link rel="stylesheet" href="/assets/quill.snow.css"><style>body{margin:0;background:white;color:#253a35;font:16px/1.8 system-ui,sans-serif}#article-paper{max-width:720px;margin:auto;min-height:350px;padding:24px;box-sizing:border-box;outline:none;white-space:normal;overflow-wrap:anywhere}img{max-width:100%;height:auto}img[data-qa-missing]{display:inline-block;min-width:110px;min-height:38px;border:1px dashed #ab704b;background:#f9eee3;cursor:pointer}img[data-qa-selected]{outline:2px solid #46745e;outline-offset:2px}#article-paper:empty:before{content:"在这里撰写文章正文…";color:#70817b;pointer-events:none}</style><body><div id="article-paper" class="ql-editor">' + html + '</div></body></html>';
}

function ArticleVisualEditor({ initialHtml, onChange, onBusyChange, onError, onImport }) {
  const frame = React.useRef(null);
  const docState = React.useRef(null);
  const callbacks = React.useRef({});
  const file = React.useRef(null);
  const pending = React.useRef(false);
  const selectedImage = React.useRef(null);
  const replaceImage = React.useRef(false);
  callbacks.current = { onChange, onBusyChange, onError, onImport };
  function markMissingImages(paper) {
    for (const image of paper.querySelectorAll('img')) {
      const missing = !image.getAttribute('src') || (image.complete && image.naturalWidth === 0);
      image.toggleAttribute('data-qa-missing', missing);
    }
  }
  function editorHtml(paper) {
    if (!paper.querySelector('img[data-qa-missing], img[data-qa-selected]')) return paper.innerHTML;
    const copy = paper.cloneNode(true);
    for (const image of copy.querySelectorAll('img[data-qa-missing], img[data-qa-selected]')) {
      image.removeAttribute('data-qa-missing');
      image.removeAttribute('data-qa-selected');
    }
    return copy.innerHTML;
  }
  function change() {
    const current = docState.current;
    if (!current) return;
    markMissingImages(current.paper);
    callbacks.current.onChange(editorHtml(current.paper));
  }
  function command(action, value) {
    const current = docState.current;
    if (!current || pending.current) return;
    current.paper.focus();
    current.doc.execCommand(action, false, value);
    change();
  }
  async function insertImage(image) {
    if (!image || !docState.current || pending.current) return;
    const current = docState.current;
    const target = replaceImage.current ? selectedImage.current : null;
    replaceImage.current = false;
    const selection = current.doc.getSelection();
    const range = selection?.rangeCount && current.paper.contains(selection.anchorNode) ? selection.getRangeAt(0).cloneRange() : null;
    pending.current = true; callbacks.current.onBusyChange(true);
    try {
      const body = new FormData(); body.append('file', image);
      const response = await fetch('/api/admin/media', { method: 'POST', body });
      const data = await response.json();
      if (!response.ok) throw new Error(data.error?.message || '图片上传失败');
      if (current !== docState.current) return;
      if (target && current.paper.contains(target)) { target.setAttribute('src', data.url); change(); return; }
      current.paper.focus();
      const point = range || current.doc.createRange();
      if (!range) { point.selectNodeContents(current.paper); point.collapse(false); }
      selection.removeAllRanges(); selection.addRange(point);
      current.doc.execCommand('insertImage', false, data.url);
      change();
    } catch (e) { callbacks.current.onError(e.message || '图片上传失败。'); }
    finally { pending.current = false; callbacks.current.onBusyChange(false); }
  }
  function load() {
    const doc = frame.current?.contentDocument;
    const paper = doc?.getElementById('article-paper');
    if (!paper || docState.current?.doc === doc) return;
    docState.current = { doc, paper };
    paper.innerHTML = initialHtml;
    paper.contentEditable = 'true';
    paper.setAttribute('role', 'textbox');
    paper.setAttribute('aria-label', '正文画布');
    paper.setAttribute('aria-multiline', 'true');
    paper.addEventListener('input', change);
    const markImage = e => {
      if (e.target.tagName === 'IMG') e.target.toggleAttribute('data-qa-missing', e.type === 'error');
    };
    paper.addEventListener('load', markImage, true);
    paper.addEventListener('error', markImage, true);
    markMissingImages(paper);
    paper.addEventListener('click', e => {
      selectedImage.current?.removeAttribute('data-qa-selected');
      selectedImage.current = e.target.closest('img');
      selectedImage.current?.setAttribute('data-qa-selected', '');
      if (e.target.closest('a')) e.preventDefault();
    });
    paper.addEventListener('drop', e => {
      e.preventDefault();
      if (e.dataTransfer.files[0]) insertImage(e.dataTransfer.files[0]);
    });
    paper.addEventListener('paste', async e => {
      e.preventDefault();
      if (pending.current) return;
      const pasted = e.clipboardData;
      const image = Array.from(pasted.files).find(x => x.type.startsWith('image/'));
      const html = pasted.getData('text/html');
      if (image && !html) { insertImage(image); return; }
      if (!html) { command('insertText', pasted.getData('text/plain')); return; }
      const selection = doc.getSelection();
      const range = selection?.rangeCount && paper.contains(selection.anchorNode) ? selection.getRangeAt(0).cloneRange() : null;
      const original = editorHtml(paper);
      pending.current = true; callbacks.current.onBusyChange(true);
      try {
        const result = await callbacks.current.onImport(html);
        if (docState.current?.doc !== doc) return;
        if (editorHtml(paper) !== original) throw Error('导入期间正文有修改，请重新粘贴。');
        paper.focus();
        if (range) { selection.removeAllRanges(); selection.addRange(range); }
        if (!paper.textContent.trim() && !paper.querySelector('img,table,hr')) paper.innerHTML = result.html;
        else doc.execCommand('insertHTML', false, result.html);
        change();
      } catch (e) { callbacks.current.onError(e.message || '粘贴内容导入失败。'); }
      finally { pending.current = false; callbacks.current.onBusyChange(false); }
    });
  }
  return <div className="qa-editor"><div className="qa-tools" aria-label="正文工具">
    {[['bold','加粗'],['italic','斜体'],['underline','下划线'],['insertUnorderedList','项目列表'],['insertOrderedList','编号列表'],['justifyCenter','居中'],['undo','撤销'],['redo','重做']].map(([action,label]) =>
      <button key={action} type="button" onMouseDown={e => e.preventDefault()} onClick={() => command(action)}>{label}</button>)}
    <button type="button" onMouseDown={e => e.preventDefault()} onClick={() => command('formatBlock','h2')}>小标题</button>
    <button type="button" onMouseDown={e => e.preventDefault()} onClick={() => command('formatBlock','blockquote')}>引用</button>
    <button type="button" onMouseDown={e => e.preventDefault()} onClick={() => { const url = window.prompt('输入链接地址（https://）'); if (/^https?:\/\//i.test(url || '')) command('createLink',url); }}>链接</button>
    <button type="button" onMouseDown={e => e.preventDefault()} onClick={() => { replaceImage.current = false; file.current.click(); }}>插入图片</button>
    <button type="button" onMouseDown={e => e.preventDefault()} onClick={() => { if (!selectedImage.current) { callbacks.current.onError('请先在画布内点击要更换的图片。'); return; } replaceImage.current = true; file.current.click(); }}>更换选中图片</button>
    <input ref={file} type="file" hidden accept="image/png,image/jpeg,image/gif,image/webp" onChange={e => { insertImage(e.target.files[0]); e.target.value = ''; }} />
  </div><iframe ref={frame} title="文章可视化编辑" sandbox="allow-same-origin" srcDoc={articleCanvas()} onLoad={load} /></div>;
}

function ArticleCoverPicker({ html, cover, onSelect }) {
  const pictures = React.useMemo(() => {
    if (!html || typeof document === 'undefined') return [];
    const template = document.createElement('template');
    template.innerHTML = html;
    const byUrl = new Map();
    function address(value) {
      const src = value?.trim();
      if (!src || src.length > 5000 || /[\u0000-\u001f\u007f]/.test(src)) return null;
      try {
        const url = new URL(src, document.baseURI);
        if (url.protocol !== 'https:' && url.protocol !== 'http:') return null;
        return { src: src.startsWith('//') ? url.href : src, key: url.href };
      } catch { return null; }
    }
    for (const image of template.content.querySelectorAll('img')) {
      const source = address(image.getAttribute('data-src')) || address(image.getAttribute('src'));
      if (source && !byUrl.has(source.key)) {
        byUrl.set(source.key, { ...source, alt: image.getAttribute('alt')?.trim() });
      }
    }
    return [...byUrl.values()];
  }, [html]);

  return <div id="article-cover-picker" tabIndex={-1} className="qa-cover-picker">
    <strong>从正文选图</strong>
    {pictures.length ? <div className="qa-cover-grid" aria-label="正文图片">
      {pictures.map(({ key, src, alt }, index) =>
        <button type="button" key={key} aria-label={'用正文第 ' + (index + 1) + ' 张图片作封面' + (alt ? '：' + alt : '')}
          aria-pressed={src === cover} onClick={() => onSelect(src)}>
          <img src={src} alt="" loading="lazy" referrerPolicy="no-referrer" />
          <span>{src === cover ? '当前封面' : '图片 ' + (index + 1)}</span>
        </button>
      )}
    </div> : <p className="qa-editor-hint">正文暂无可选图片。插入或导入图片后即可选择。</p>}
  </div>;
}

function AdminPostCategories({ canManage }) {
  const [items, setItems] = React.useState(null);
  const [editing, setEditing] = React.useState(null);
  const [name, setName] = React.useState('');
  const [busy, setBusy] = React.useState(false);
  const [error, setError] = React.useState('');
  const [notice, setNotice] = React.useState('');
  const endpoint = '/api/admin/post-categories';

  async function request(url, method = 'GET', value) {
    const options = value === undefined ? { method } : {
      method, headers: { 'content-type': 'application/json' }, body: JSON.stringify({ name: value })
    };
    const response = await fetch(url, options);
    const data = await response.json();
    if (!response.ok) throw new Error(data.error?.message || '分类操作失败。');
    return data;
  }
  async function reload() { setItems((await request(endpoint)).items); }
  React.useEffect(() => { reload().catch(error => setError(error.message)); }, []);
  async function update(event) {
    event.preventDefault();
    setBusy(true); setError(''); setNotice('');
    try {
      await request(editing ? endpoint + '/' + encodeURIComponent(editing) : endpoint, editing ? 'PATCH' : 'POST', name.trim());
      setName(''); setEditing(null);
      await reload();
      setNotice('分类已保存。');
    } catch (error) { setError(error.message); }
    finally { setBusy(false); }
  }
  async function remove(category) {
    if (!window.confirm('删除空分类「' + category + '」？')) return;
    setBusy(true); setError(''); setNotice('');
    try {
      await request(endpoint + '/' + encodeURIComponent(category), 'DELETE');
      if (editing === category) { setEditing(null); setName(''); }
      await reload();
      setNotice('分类已删除。');
    } catch (error) { setError(error.message); }
    finally { setBusy(false); }
  }
  return <section className="qa-list">
    <h1>文章分类</h1>
    <p>{canManage ? '改名会同步更新所属文章。请先移走文章，再删除分类。' : '编辑文章时可选用以下分类。管理员可以修改分类。'}</p>
    {error && <p role="alert">{error}</p>}
    {notice && <p role="status">{notice}</p>}
    {canManage && <form className="qa-search" onSubmit={update}>
      <input aria-label={editing ? '新分类名称' : '分类名称'} placeholder={editing ? '输入新名称' : '输入分类名称'} value={name} maxLength={60} onChange={event => setName(event.target.value)} required />
      <button type="submit" disabled={busy || !name.trim()}>{editing ? '保存改名' : '新增分类'}</button>
      {editing && <button type="button" onClick={() => { setEditing(null); setName(''); }}>取消改名</button>}
    </form>}
    {items && <div className="qa-category-list">{items.map(item =>
      <div className="qa-category-row" key={item.name}>
        <span><strong>{item.name}</strong> <small>{item.total} 篇文章</small></span>
        {canManage && item.name !== '其它' && <div>
          <button type="button" disabled={busy} onClick={() => { setEditing(item.name); setName(item.name); setError(''); }}>改名</button>
          <button type="button" disabled={busy || item.total > 0} title={item.total > 0 ? '请先移走该分类的文章' : undefined} onClick={() => remove(item.name)}>删除</button>
        </div>}
      </div>
    )}</div>}
  </section>;
}

function AdminArticles({initialPostId,onOpened} = {}) {
  const [items, setItems] = React.useState([]);
  const [page, setPage] = React.useState(1);
  const [total, setTotal] = React.useState(0);
  const [searchInput, setSearchInput] = React.useState('');
  const [query, setQuery] = React.useState('');
  const [filter, setFilter] = React.useState('');
  const [categoryFilter, setCategoryFilter] = React.useState('');
  const [categories, setCategories] = React.useState([]);
  const [categoryError, setCategoryError] = React.useState('');
  const [editing, setEditing] = React.useState(null);
  const [loading, setLoading] = React.useState(true);
  const [busy, setBusy] = React.useState(false);
  const [uploads, setUploads] = React.useState(0);
  const [error, setError] = React.useState('');
  const [notice, setNotice] = React.useState('');
  const [editorMode, setEditorMode] = React.useState('visual');
  const [previewHtml, setPreviewHtml] = React.useState('');
  const [importNotice, setImportNotice] = React.useState('');
  const [importUnavailable, setImportUnavailable] = React.useState(false);
  const preparedHtml = React.useRef('');
  const currentLocation = window.location;
  const olderTestServer = ['127.0.0.1', 'localhost'].includes(currentLocation?.hostname) &&
    ['18766', '18767', '18769', '18770'].includes(currentLocation.port);
  const empty = () => ({ title: '', excerpt: '', cover: '', category: '其它', status: 'draft', body: [{ type: 'p', text: '' }] });
  async function request(url, options) {
    const response = await fetch(url, options);
    const data = await response.json();
    if (!response.ok) {
      const error = new Error(data.error?.message || '请求失败，请重试。');
      error.status = response.status;
      throw error;
    }
    return data;
  }
  async function reload() {
    setLoading(true);
    try { const result = await request('/api/admin/posts?pageSize=200' + (page > 1 ? '&page=' + page : '') + (query ? '&q=' + encodeURIComponent(query) : '') + (filter ? '&status=' + filter : '') + (categoryFilter ? '&category=' + encodeURIComponent(categoryFilter) : '')); setItems(result.items); setTotal(result.total ?? result.items.length); }
    catch (e) { setError(e.message || '无法读取文章。'); }
    finally { setLoading(false); }
  }
  React.useEffect(() => { reload(); }, [page, query, filter, categoryFilter]);
  React.useEffect(() => {
    let current = true;
    request('/api/admin/post-categories').then(result => {
      if (current) setCategories((result.items || []).filter(item => typeof item.name === 'string'));
    }).catch(() => {
      if (current) setCategoryError('未能加载文章分类，请刷新页面或检查验收站版本。');
    });
    return () => { current = false; };
  }, []);
  React.useEffect(()=>{if(initialPostId){open(initialPostId);onOpened&&onOpened();}},[initialPostId]);
  async function importSource(html) {
    setImportUnavailable(false);
    let result;
    try {
      result = await request('/api/admin/posts/import-html', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ html }) });
    } catch (error) {
      if (error.status !== 404) throw error;
      setImportUnavailable(true);
      throw new Error(olderTestServer ? '当前是旧版验收站，无法导入微信 HTML。' : '当前后台未启用微信 HTML 导入，请检查后端版本。');
    }
    if (result.uploaded || result.failed) setImportNotice('已转存 ' + result.uploaded + ' 张图片' + (result.failed ? '；' + result.failed + ' 张未转存，可在画布中重新上传。' : '。'));
    return result;
  }
  async function switchEditorMode(mode) {
    if (mode === editorMode) return;
    if (mode === 'html' || (mode === 'visual' && (editing.html || '') === preparedHtml.current)) { setEditorMode(mode); return; }
    setBusy(true); setError('');
    try {
      const html = editing.html || '';
      if (mode === 'visual') {
        const result = html.trim() ? await importSource(html) : { html: '' };
        preparedHtml.current = result.html;
        setEditing(current => ({ ...current, html: result.html }));
      } else {
        const result = await request('/api/admin/posts/preview', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ html }) });
        setPreviewHtml(result.html);
      }
      setEditorMode(mode);
    } catch (e) { setError(e.message || '无法打开编辑模式。'); }
    finally { setBusy(false); }
  }
  async function pasteSource(e) {
    const plain = e.clipboardData.getData('text/plain');
    const rich = e.clipboardData.getData('text/html');
    const pasted = /<\/?[a-z][^>]*>/i.test(plain) ? plain : rich;
    if (!pasted) return;
    e.preventDefault();
    const input = e.currentTarget;
    const combined = input.value.slice(0, input.selectionStart) + pasted + input.value.slice(input.selectionEnd);
    setEditing(current => ({ ...current, html: combined }));
    setBusy(true); setError('');
    try {
      const result = await importSource(combined);
      preparedHtml.current = result.html;
      setEditing(current => ({ ...current, html: result.html }));
    } catch (e) { setError(e.message || '导入失败，源码仍在，可重新尝试。'); }
    finally { setBusy(false); }
  }
  async function open(id) {
    setError(''); setNotice(''); setBusy(true);
    try {
      const data = await request('/api/admin/posts/' + encodeURIComponent(id));
      preparedHtml.current = articleBlocksToHtml(data.body);
      setImportNotice(''); setEditorMode('visual'); setEditing({ ...data, html: preparedHtml.current, originalHtml: preparedHtml.current });
    } catch (e) { setError(e.message || '无法读取文章。'); }
    finally { setBusy(false); }
  }
  async function save(e) {
    e.preventDefault(); setError(''); setNotice(''); setBusy(true);
    try {
      const html = editing.html || '';
      const payload = { title: editing.title.trim(), excerpt: editing.excerpt || '', cover: editing.cover || '', category: editing.category || '其它', status: editing.status };
      if (!payload.title) throw new Error('请填写文章标题。');
      if (!editing.id || html !== editing.originalHtml) {
        const prepared = editorMode === 'html' && /(?:data-src\s*=|data:image\/|https?:\/\/(?:mmbiz\.qpic\.cn|mmbiz\.qlogo\.cn|res\.wx\.qq\.com)\/)/i.test(html)
          ? (await importSource(html)).html : html;
        payload.body = [{ type: 'html', text: prepared }];
      }
      const url = editing.id ? '/api/admin/posts/' + encodeURIComponent(editing.id) : '/api/admin/posts';
      await request(url, { method: editing.id ? 'PATCH' : 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(payload) });
      setEditing(null); setNotice('文章已保存。'); await reload();
    } catch (e) { setError(e.message || '保存失败，请重试。'); }
    finally { setBusy(false); }
  }
  const field = { display: 'block', width: '100%', border: '1px solid #cbdad9', borderRadius: 4, padding: 9, marginTop: 6, fontSize: 14 };
  const btn = { border: '1px solid #b4cecc', background: '#fff', color: '#174e52', padding: '8px 12px', borderRadius: 4, cursor: 'pointer' };
  if (editing) return <section className="qa-article-page"><h1>{editing.id ? '编辑文章' : '新建文章'}</h1>
    <form className="qa-article-form" onSubmit={save}>
      <div className="qa-article-main">
        <label>标题<input name="title" className="qa-article-title" placeholder="输入文章标题" required value={editing.title || ''} onChange={e => setEditing({ ...editing, title: e.target.value })} /></label>
      <div><strong>文章正文</strong><div className="qa-modes" style={{ display: 'flex', gap: 8, margin: '10px 0', flexWrap: 'wrap' }}>
        {[['visual', '可视化编辑'], ['html', 'HTML 源码'], ['preview', '预览']].map(([mode, label]) => <button key={mode} type="button" disabled={busy || uploads > 0} style={{ ...btn, background: editorMode === mode ? '#17696e' : '#fff', color: editorMode === mode ? '#fff' : '#174e52' }} aria-pressed={editorMode === mode} onClick={() => switchEditorMode(mode)}>{label}</button>)}
        <button type="button" onClick={() => document.getElementById('article-cover-picker')?.focus()}>从正文选封面</button>
      </div>
        {editorMode === 'visual' && <ArticleVisualEditor initialHtml={editing.html || ''} onError={setError} onImport={importSource} onBusyChange={active => setUploads(n => n + (active ? 1 : -1))} onChange={html => { preparedHtml.current = html; setEditing(current => ({ ...current, html })); }} />}
        {editorMode === 'html' && <textarea name="article-html" aria-label="HTML 源码" rows="22" style={{ ...field, fontFamily: 'monospace' }} disabled={busy} value={editing.html || ''} onPaste={pasteSource} onChange={e => setEditing({ ...editing, html: e.target.value })} />}
        {editorMode === 'preview' && <div className="qa-editor"><iframe title="文章正文预览" sandbox="" srcDoc={articleCanvas(previewHtml)} /></div>}
        {importNotice && <p className="qa-import-notice" role="status">{importNotice}</p>}
        <p className="qa-editor-hint">可直接粘贴微信编辑器 HTML。切换模式保留支持的结构与样式；在画布内局部修改文字可最大限度保持原排版。</p>
      </div>
      {error && <p role="alert">{error}{importUnavailable && olderTestServer && <> 请复制源码，在 <a href="http://127.0.0.1:18771/?admin=1" target="_blank" rel="noopener noreferrer">新版验收后台</a>重新粘贴。</>}</p>}
      </div>
      <aside className="qa-publish">
        <h2>发布设置</h2>
        <label>状态<select style={field} value={editing.status} onChange={e => setEditing({ ...editing, status: e.target.value })}><option value="draft">草稿</option><option value="published">发布</option></select></label>
        <label>分类<select style={field} value={editing.category || '其它'} onChange={e => setEditing({ ...editing, category: e.target.value })}>
          {[...new Set(['其它', ...categories.map(item => item.name), editing.category].filter(Boolean))].map(name => <option key={name} value={name}>{name}</option>)}
        </select></label>
        {categoryError && <p role="status">{categoryError}</p>}
        <div>封面图片
          <ArticleCoverPicker html={editing.html} cover={editing.cover} onSelect={cover => setEditing(current => ({ ...current, cover }))} />
          <AdminImageField value={editing.cover || ''} onBusyChange={active => setUploads(n => n + (active ? 1 : -1))} onChange={value => setEditing(current => ({ ...current, cover: value }))} />
        </div>
        <label>摘要<textarea style={field} rows="4" value={editing.excerpt || ''} onChange={e => setEditing({ ...editing, excerpt: e.target.value })} /></label>
        <div className="qa-publish-actions"><button type="submit" disabled={busy || uploads > 0}>{busy ? '处理中…' : uploads ? '等待图片上传…' : '保存文章'}</button><button type="button" disabled={busy || uploads > 0} onClick={() => { setEditing(null); setError(''); }}>取消</button></div>
      </aside>
    </form></section>;
  return <section className="qa-list"><div className="qa-list-heading"><h1>文章管理</h1><button type="button" style={btn} onClick={() => { setError(''); setNotice(''); preparedHtml.current = ''; setImportNotice(''); setEditorMode('visual'); setEditing({ ...empty(), html: '' }); }}>新建文章</button></div>
    {error && <p role="alert" style={{ color: '#a63a30', marginTop: 12 }}>{error}</p>}{notice && <p role="status" style={{ marginTop: 12 }}>{notice}</p>}
    <form className="qa-search" onSubmit={e => { e.preventDefault(); setPage(1); setQuery(searchInput.trim()); }}>
      <input aria-label="按标题或摘要搜索" placeholder="搜索标题或摘要" value={searchInput} onChange={e => setSearchInput(e.target.value)} />
      <select aria-label="按发布状态筛选" value={filter} onChange={e => { setPage(1); setFilter(e.target.value); }}><option value="">全部状态</option><option value="draft">草稿</option><option value="published">已发布</option></select>
      <select aria-label="按文章分类筛选" value={categoryFilter} onChange={e => { setPage(1); setCategoryFilter(e.target.value); }}><option value="">全部分类</option>{categories.map(item => <option key={item.name} value={item.name}>{item.name}</option>)}</select>
      <button type="submit">搜索</button>{(query || filter || categoryFilter) && <button type="button" onClick={() => { setPage(1); setSearchInput(''); setQuery(''); setFilter(''); setCategoryFilter(''); }}>清除</button>}
    </form>
    {loading ? <p>正在读取文章…</p> : <div style={{ marginTop: 18 }}>{items.length === 0 ? <p>{query || filter || categoryFilter ? '没有符合条件的文章。' : '暂无文章。'}</p> : items.map(item => <div key={item.id} className="qa-list-row"><div><strong>{item.title}</strong><small>{item.category || '未分类'}{item.published_at ? ' · ' + item.published_at.slice(0,10) : ''}</small></div><span className={'qa-status ' + (item.status === 'published' ? 'is-live' : '')}>{item.status === 'published' ? '已发布' : '草稿'}</span><button type="button" disabled={busy} style={btn} onClick={() => open(item.id)}>编辑</button></div>)}</div>}
    {total > 200 && <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginTop: 16 }}><button type="button" style={btn} disabled={loading || page <= 1} onClick={() => setPage(page - 1)}>上一页</button><span>第 {page} / {Math.ceil(total / 200)} 页 · 共 {total} 篇</span><button type="button" style={btn} disabled={loading || page * 200 >= total} onClick={() => setPage(page + 1)}>下一页</button></div>}
  </section>;
}

const ADMIN_COLLECTIONS = {
  books: { label: '书籍', title: 'title', fields: [
    ['title', '书名', 'text', true], ['title_en', '英文书名'], ['cover', '封面图片', 'image'], ['lang', '语言'], ['price', '价格说明'], ['theme', '主题'], ['intro', '简介', 'textarea'], ['year', '出版年份', 'number'], ['sort', '排序', 'number'], ['visible', '前台显示', 'visible'] ] },
  videos: { label: '影像', title: 'title', fields: [
    ['title', '标题', 'text', true], ['title_en', '英文标题'], ['kind', '分类'], ['duration', '时长'], ['poster', '封面图片', 'image'], ['src_url', '视频', 'video'], ['featured', '推荐', 'visible'], ['sort', '排序', 'number'], ['visible', '前台显示', 'visible'] ] },
  faqs: { label: '常见问题', title: 'q', fields: [
    ['grp', '分组', 'text', true], ['q', '问题', 'textarea', true], ['a', '回答', 'textarea', true], ['sort', '排序', 'number'], ['visible', '前台显示', 'visible'] ] },
  voices: { label: '学员证言', title: 'name', fields: [
    ['name', '称呼', 'text', true], ['avatar', '头像', 'image'], ['title', '标题'], ['highlight', '摘句', 'textarea'], ['content', '证言内容', 'textarea', true], ['kind', '类型'], ['sort', '排序', 'number'], ['visible', '前台显示', 'visible'] ] },
  courses: { label: '课程', title: 'title', fields: [
    ['id', '课程编号', 'text', true], ['title', '课程名称', 'text', true], ['level', '阶段标识'], ['n', '序号'], ['en', '英文名称'], ['status', '状态', 'courseStatus'], ['status_text', '状态说明'], ['form', '形式'], ['lang', '语言'], ['lead', '引言', 'textarea'], ['descr', '课程介绍', 'textarea'], ['price_cents', '价格（元）', 'money'], ['price_text', '价格文字'], ['seats','总名额（留空不限）','number'], ['seats_left','可报名余位','number'], ['points', '课程要点（每行一项）', 'lines'], ['meta', '附加信息（每行：名称 | 内容）', 'pairs'], ['bundle', '套餐', 'bundle'], ['sort', '排序', 'number'] ] },
  events: { label: '活动与相册', title: 'title', fields: [
    ['title', '活动名称', 'text', true], ['kind', '活动类别'], ['state', '状态', 'eventState'], ['cover', '封面图片', 'image'], ['start_date', '开始日期', 'date'], ['end_date', '结束日期', 'date'], ['date_text', '日期说明'], ['days', '天数', 'number'], ['city', '城市'], ['venue', '地点'], ['teacher', '讲师'], ['form', '形式'], ['level', '阶段'], ['seats', '总名额', 'number'], ['seats_left', '可报名余位', 'number'], ['price_cents','活动参考价格（元，选填）','money'], ['fee', '费用补充说明'], ['deadline', '报名截止', 'date'], ['intro', '活动介绍', 'textarea'], ['agenda', '活动日程（每行一项）', 'lines'], ['note', '补充说明', 'textarea'], ['source_url', '原文链接'], ['people', '参加人数', 'number'], ['year', '年份', 'number'], ['photos', '活动相册', 'photos'] ] }
};

function AdminCollection({ type, canEdit = true, canFinance = true }) {
  const financeField = name => ['seats','seats_left','price_cents'].includes(name);
  const config = ADMIN_COLLECTIONS[type];
  const [items, setItems] = React.useState([]);
  const [editing, setEditing] = React.useState(null);
  const [loading, setLoading] = React.useState(true);
  const [busy, setBusy] = React.useState(false);
  const [uploads, setUploads] = React.useState(0);
  const [error, setError] = React.useState('');
  const [notice, setNotice] = React.useState('');
  const fieldStyle = { display: 'block', width: '100%', padding: 9, marginTop: 6, border: '1px solid #cbdad9', borderRadius: 4, fontSize: 14 };
  const buttonStyle = { border: '1px solid #b4cecc', background: '#fff', color: '#174e52', padding: '8px 12px', borderRadius: 4, cursor: 'pointer' };
  async function request(url, options) {
    const response = await fetch(url, options); const body = await response.json();
    if (!response.ok) throw new Error(body.error?.message || '请求失败，请重试。');
    return body;
  }
  async function reload() {
    setLoading(true); setError('');
    try { setItems((await request('/api/admin/content/' + type)).items); }
    catch (e) { setError(e.message || '读取失败。'); }
    finally { setLoading(false); }
  }
  React.useEffect(() => { setEditing(null); setNotice(''); reload(); }, [type]);
  function formFor(item) {
    const out = {};
    for (const [name, label, kind] of config.fields) {
      const v = item?.[name];
      if (kind === 'visible') out[name] = v == null ? (name === 'visible' ? '1' : '0') : String(v);
      else if (['json', 'photos', 'bundle'].includes(kind)) { try { out[name] = v ? JSON.stringify(typeof v === 'string' ? JSON.parse(v) : v, null, 2) : ''; } catch { out[name] = v || ''; } }
      else if (kind === 'lines' || kind === 'pairs') { try { const arr = typeof v === 'string' ? JSON.parse(v) : (v || []); out[name] = arr.map(x => kind === 'pairs' ? x.join(' | ') : x).join('\n'); } catch { out[name] = ''; } }
      else if (kind === 'money') out[name] = v == null ? '' : String(v / 100);
      else out[name] = v == null ? (kind === 'eventState' ? 'draft' : kind === 'courseStatus' ? 'draft' : '') : String(v);
    }
    return { id: item?.id, data: out, original: { ...out }, inventorySnapshot: item ? { seats:item.seats, left:item.seats_left } : null };
  }
  function updateField(name, value, kind) {
    setEditing(current => ({ ...current, data: { ...current.data, [name]: value,
      ...(kind === 'money' && type === 'courses' ? { price_text: value === '' ? '待定' : Number(value) === 0 ? '免费' : '¥' + Number(value).toLocaleString('zh-CN') } : {}) } }));
  }
  async function save(e) {
    e.preventDefault(); setError(''); setNotice(''); setBusy(true);
    try {
      const payload = {};
      for (const [name, label, kind, required] of config.fields) {
        if ((name === 'id' && editing.id) || (!canFinance && financeField(name))) continue;
        const v = editing.data[name];
        if (editing.id && v === editing.original[name]) continue;
        if (required && !String(v || '').trim()) throw new Error('请填写' + label + '。');
        if (['json', 'photos', 'bundle'].includes(kind)) { if (v.trim()) { try { payload[name] = JSON.parse(v); } catch { throw new Error(label + '格式不正确。'); } } }
        else if (kind === 'lines') payload[name] = v.split('\n').map(x => x.trim()).filter(Boolean);
        else if (kind === 'pairs') payload[name] = v.split('\n').map(x => x.trim()).filter(Boolean).map(x => { const pos = x.indexOf('|'); if (pos < 0) throw new Error('附加信息每行需以 | 分隔名称与内容。'); return [x.slice(0, pos).trim(), x.slice(pos + 1).trim()]; });
        else if (kind === 'number' || kind === 'money' || kind === 'visible') {
          if (v !== '') { const n = Number(v); if (!Number.isFinite(n) || n < 0 || (kind !== 'money' && !Number.isInteger(n))) throw new Error(label + '格式不正确。'); payload[name] = kind === 'money' ? Math.round(n * 100) : n; }
          else if (editing.id) payload[name] = null;
        } else payload[name] = v;
      }
      if (editing.id && Object.keys(payload).length === 0) throw new Error('没有需要保存的修改。');
      if (editing.id && ('seats' in payload || 'seats_left' in payload)) payload.inventorySnapshot = editing.inventorySnapshot;
      const base = '/api/admin/content/' + type;
      await request(editing.id ? base + '/' + encodeURIComponent(editing.id) : base, { method: editing.id ? 'PATCH' : 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(payload) });
      setEditing(null); setNotice('已保存。'); await reload();
    } catch (e) { setError(e.message || '保存失败。'); }
    finally { setBusy(false); }
  }
  if (editing) return <section className="qa-standard-form"><h1>{editing.id ? '编辑' : '新增'}{config.label}</h1>
    <form onSubmit={save} style={{ display: 'grid', gap: 14, maxWidth: 850, marginTop: 20 }}>
      {['events','courses'].includes(type) && <p>{canFinance ? '首次填写总名额时，余位留空会自动计算。调整总名额会保留已占用的名额。' : '活动名额和收费由管理员设置。'}</p>}
      {config.fields.filter(([name]) => canFinance || !financeField(name)).map(([name, label, kind = 'text', required]) => <div key={name}><label htmlFor={'content-' + name}>{label}{required ? ' *' : ''}</label>
        {kind === 'image' || kind === 'video' ? <AdminImageField inputId={'content-' + name} mediaType={kind} value={editing.data[name]} onBusyChange={active => setUploads(n => n + (active ? 1 : -1))} onChange={value => setEditing(current => ({ ...current, data: { ...current.data, [name]: value } }))} /> : kind === 'photos' ? <AdminPhotosField value={editing.data[name]} onBusyChange={active => setUploads(n => n + (active ? 1 : -1))} onChange={value => setEditing(current => ({ ...current, data: { ...current.data, [name]: value } }))} /> : kind === 'bundle' ? <AdminBundleField value={editing.data[name]} onChange={value => setEditing(current => ({ ...current, data: { ...current.data, [name]: value } }))} /> : kind === 'visible' || kind === 'eventState' || kind === 'courseStatus' ? <select id={'content-' + name} name={name} style={fieldStyle} value={editing.data[name]} onChange={e => setEditing({ ...editing, data: { ...editing.data, [name]: e.target.value } })}>
          {kind === 'visible' ? <><option value="1">是</option><option value="0">否</option></> : kind === 'eventState' ? <><option value="draft">草稿 / 下架</option><option value="upcoming">即将到来</option><option value="past">往期活动</option></> : <><option value="draft">草稿 / 下架</option><option value="open">开放</option><option value="locked">需前置课程</option><option value="soon">即将开放</option></>}
        </select> : ['textarea', 'json', 'lines', 'pairs'].includes(kind) ? <textarea id={'content-' + name} name={name} rows="4" required={!!required} style={fieldStyle} value={editing.data[name]} onChange={e => setEditing({ ...editing, data: { ...editing.data, [name]: e.target.value } })} /> : <input id={'content-' + name} name={name} type={kind === 'date' ? 'date' : kind === 'number' || kind === 'money' ? 'number' : 'text'} step={kind === 'money' ? '0.01' : undefined} required={!!required} disabled={name === 'id' && !!editing.id} style={fieldStyle} value={editing.data[name]} onChange={e => updateField(name, e.target.value, kind)} />}
      </div>)}
      {error && <p role="alert" style={{ color: '#a63a30' }}>{error}</p>}
      <div style={{ display: 'flex', gap: 10 }}><button type="submit" disabled={busy || uploads > 0} style={{ ...buttonStyle, background: '#17696e', color: '#fff' }}>{busy ? '保存中…' : uploads ? '等待图片上传…' : '保存'}</button><button type="button" disabled={uploads > 0} style={buttonStyle} onClick={() => { setEditing(null); setError(''); }}>取消</button></div>
    </form></section>;
  return <section className="qa-list"><div className="qa-list-heading"><h1>{config.label}管理</h1>{canEdit && <button type="button" style={buttonStyle} onClick={() => { setError(''); setNotice(''); setEditing(formFor(null)); }}>新增</button>}</div>
    {!canEdit && <p>课程可查看，管理员可以修改。</p>}
    {error && <p role="alert" style={{ color: '#a63a30', marginTop: 12 }}>{error}</p>}{notice && <p role="status" style={{ marginTop: 12 }}>{notice}</p>}
    {loading ? <p>正在读取…</p> : items.length === 0 ? <p>暂无内容。</p> : <div style={{ marginTop: 18 }}>{items.map(item => <div key={item.id} className="qa-list-row"><span>{item[config.title]} {item.visible === 0 ? '· 已隐藏' : item.state === 'draft' || item.status === 'draft' ? '· 草稿' : ''}</span>{canEdit && <button type="button" style={buttonStyle} onClick={() => { setError(''); setNotice(''); setEditing(formFor(item)); }}>编辑</button>}</div>)}</div>}
  </section>;
}

function AdminImageField({ inputId, value, onChange, fallback, onBusyChange, mediaType = 'image' }) {
  const [busy, setBusy] = React.useState(false);
  const [error, setError] = React.useState('');
  async function upload(e) {
    const file = e.target.files && e.target.files[0];
    if (!file) return;
    const input = e.target;
    setBusy(true); setError(''); if (onBusyChange) onBusyChange(true);
    try {
      const body = new FormData(); body.append('file', file);
      const response = await fetch(mediaType === 'video' ? '/api/admin/video' : '/api/admin/media', { method: 'POST', body });
      const data = await response.json();
      if (!response.ok) throw new Error(data.error?.message || '上传失败。');
      onChange(data.url);
    } catch (e) { setError(e.message || '上传失败。'); }
    finally { setBusy(false); if (onBusyChange) onBusyChange(false); input.value = ''; }
  }
  return <div className="qa-media-field" style={{ display: 'grid', gap: 8, marginTop: 6 }}>
    <input id={inputId} type="text" aria-label={inputId ? undefined : mediaType === 'video' ? '视频地址' : '图片地址'} value={value || ''} onChange={e => onChange(e.target.value)} style={{ width: '100%', border: '1px solid #cbdad9', borderRadius: 4, padding: 9 }} />
    <div>{busy ? '正在上传…' : mediaType === 'video' ? '上传 MP4 视频（最多 100MB）' : '上传图片'} <input aria-label={mediaType === 'video' ? '上传视频' : '上传图片'} type="file" accept={mediaType === 'video' ? 'video/mp4' : 'image/png,image/jpeg,image/webp,image/gif'} disabled={busy} onChange={upload} /></div>
    {(value || fallback) && (mediaType === 'video' ? <video src={value || fallback} controls preload="metadata" style={{ maxWidth: 300, maxHeight: 180 }} /> : <img src={value || fallback} alt="图片预览" style={{ maxWidth: 220, maxHeight: 120, objectFit: 'contain' }} />)}
    {error && <span role="alert" style={{ color: '#a63a30' }}>{error}</span>}
  </div>;
}
function AdminVideoField(props) { return <AdminImageField {...props} mediaType="video" />; }

function AdminSettings({ canEdit = true }) {
  const [site, setSite] = React.useState(null);
  const [error, setError] = React.useState('');
  const [notice, setNotice] = React.useState('');
  const [busy, setBusy] = React.useState(false);
  const [uploads, setUploads] = React.useState(0);
  React.useEffect(() => {
    let active = true;
    fetch('/api/admin/settings').then(async r => {
      const data = await r.json();
      if (!r.ok) throw new Error(data.error?.message || '读取失败。');
      if (active) setSite({ ...(data.settings.site || {}), images: { ...((data.settings.site || {}).images || {}) } });
    }).catch(e => { if (active) setError(e.message || '无法连接后台。'); });
    return () => { active = false; };
  }, []);
  async function save(e) {
    e.preventDefault(); setBusy(true); setError(''); setNotice('');
    try {
      const r = await fetch('/api/admin/settings/site', { method: 'PUT', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ value: site }) });
      const data = await r.json(); if (!r.ok) throw new Error(data.error?.message || '保存失败。');
      if (window.QD) window.QD.site = { ...site };
      setNotice('站点设置已保存。');
    } catch (e) { setError(e.message || '保存失败。'); }
    finally { setBusy(false); }
  }
  const fieldStyle = { display: 'block', width: '100%', padding: 9, marginTop: 6, border: '1px solid #cbdad9', borderRadius: 4, fontSize: 14 };
  if (!site) return <section><h1>站点设置</h1><p role={error ? 'alert' : undefined}>{error || '正在读取…'}</p></section>;
  if (!canEdit) return <section className="qa-standard-form">
    <h1>站点信息与图片</h1>
    <p>站点设置可查看，管理员可以修改。</p>
    <dl>{[['name','站点名称'],['email','联系邮箱'],['wechat','公众号名称'],['serviceWechat','客服微信'],['serviceName','客服称呼'],['icp','备案信息']].map(([key,label]) =>
      <React.Fragment key={key}><dt>{label}</dt><dd>{site[key] || '未设置'}</dd></React.Fragment>
    )}</dl>
  </section>;
  return <section className="qa-standard-form"><h1>站点信息与图片</h1><p>修改后请点击保存；图片上传后也需要保存设置。</p>
    <form onSubmit={save} style={{ display: 'grid', gap: 16, marginTop: 20, maxWidth: 850 }}>
      {[["name", "站点名称"], ["email", "联系邮箱"], ["wechat", "公众号名称"], ["serviceWechat", "客服微信"], ["serviceName", "客服称呼"], ["icp", "备案信息"]].map(([key, label]) => <label key={key}>{label}<input name={key} style={fieldStyle} value={site[key] || ''} onChange={e => setSite({ ...site, [key]: e.target.value })} /></label>)}
      <h2>站点图片</h2>
      {Object.entries((window.QD && window.QD.siteImages) || {}).map(([key, def]) => <div key={key} style={{ background: '#fff', border: '1px solid #dce8e7', padding: 14 }}><strong>{def.label}</strong><AdminImageField value={site.images[key] || ''} fallback={def.v} onBusyChange={active => setUploads(n => n + (active ? 1 : -1))} onChange={value => setSite(current => ({ ...current, images: { ...current.images, [key]: value } }))} /><small>留空使用默认图片</small></div>)}
      {error && <p role="alert" style={{ color: '#a63a30' }}>{error}</p>}{notice && <p role="status">{notice}</p>}
      <button type="submit" disabled={busy || uploads > 0} style={{ width: 'fit-content', padding: '10px 18px', background: '#17696e', color: '#fff', border: 0, borderRadius: 4 }}>{busy ? '保存中…' : uploads ? '等待图片上传…' : '保存设置'}</button>
    </form>
  </section>;
}

function AdminAccounts({ user }) {
  const [items, setItems] = React.useState([]);
  const [email, setEmail] = React.useState('');
  const [password, setPassword] = React.useState('');
  const [role, setRole] = React.useState('editor');
  const [currentPassword, setCurrentPassword] = React.useState('');
  const [newPassword, setNewPassword] = React.useState('');
  const [error, setError] = React.useState('');
  const [notice, setNotice] = React.useState('');
  const [busy, setBusy] = React.useState(false);
  const field = { display: 'block', width: '100%', padding: 9, marginTop: 6, border: '1px solid #cbdad9', borderRadius: 4 };
  const button = { padding: '9px 14px', border: 0, borderRadius: 4, background: '#17696e', color: '#fff' };
  async function request(url, options) {
    const response = await fetch(url, options); const data = await response.json();
    if (!response.ok) throw new Error(data.error?.message || '请求失败。');
    return data;
  }
  async function reload() { setItems((await request('/api/admin/accounts')).items); }
  React.useEffect(() => { if (user.role === 'owner') reload().catch(e => setError(e.message)); }, [user.role]);
  async function create(e) {
    e.preventDefault(); setBusy(true); setError(''); setNotice('');
    try {
      await request('/api/admin/accounts', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ email, password, role }) });
      setPassword(''); setEmail(''); await reload(); setNotice('账号已创建。');
    } catch (e) { setError(e.message || '创建失败。'); } finally { setBusy(false); }
  }
  async function changePassword(e) {
    e.preventDefault(); setBusy(true); setError(''); setNotice('');
    try {
      await request('/api/admin/password', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ currentPassword, newPassword }) });
      setCurrentPassword(''); setNewPassword(''); setNotice('密码已修改，其他登录会话已退出。');
    } catch (e) { setError(e.message || '修改失败。'); } finally { setBusy(false); }
  }
  return <section><h1>账号与权限</h1>
    {error && <p role="alert" style={{ color: '#a63a30', marginTop: 12 }}>{error}</p>}{notice && <p role="status" style={{ marginTop: 12 }}>{notice}</p>}
    {user.role === 'owner' && <div style={{ marginTop: 24, maxWidth: 650 }}><h2>创建后台账号</h2>
      <p>管理员可以修改课程和站点设置；编辑员可以维护文章和其他内容。</p>
      <form onSubmit={create} style={{ display: 'grid', gap: 12, marginTop: 14 }}>
        <label>邮箱<input name="newEmail" type="email" required value={email} onChange={e => setEmail(e.target.value)} style={field} /></label>
        <label>初始密码<input name="newAccountPassword" type="password" minLength="10" required autoComplete="new-password" value={password} onChange={e => setPassword(e.target.value)} style={field} /></label>
        <label>角色<select value={role} onChange={e => setRole(e.target.value)} style={field}><option value="editor">编辑员</option><option value="admin">管理员</option></select></label>
        <button type="submit" disabled={busy} style={button}>创建账号</button>
      </form>
      <h2 style={{ marginTop: 24 }}>现有账号</h2><ul>{items.map(item => <li key={item.id} style={{ padding: 8 }}>{item.email} · {item.role}</li>)}</ul>
    </div>}
    <div style={{ marginTop: 30, maxWidth: 650 }}><h2>修改我的密码</h2>
      <form onSubmit={changePassword} style={{ display: 'grid', gap: 12, marginTop: 14 }}>
        <label>当前密码<input name="currentPassword" type="password" required autoComplete="current-password" value={currentPassword} onChange={e => setCurrentPassword(e.target.value)} style={field} /></label>
        <label>新密码<input name="newPassword" type="password" required minLength="10" autoComplete="new-password" value={newPassword} onChange={e => setNewPassword(e.target.value)} style={field} /></label>
        <button type="submit" disabled={busy} style={button}>修改密码</button>
      </form>
    </div>
  </section>;
}

function AdminPhotosField({ value, onChange, onBusyChange }) {
  const [newUrl, setNewUrl] = React.useState('');
  let photos = [];
  try { const parsed = JSON.parse(value || '[]'); if (Array.isArray(parsed)) photos = parsed.map(p => typeof p === 'string' ? { url: p, cap: '' } : p); } catch { /* Existing value remains unchanged until edited. */ }
  function update(next) { onChange(JSON.stringify(next, null, 2)); }
  return <div style={{ display: 'grid', gap: 10, marginTop: 8 }}>
    {photos.map((photo, index) => <div key={index} style={{ display: 'flex', flexWrap: 'wrap', alignItems: 'center', gap: 8, background: '#fff', padding: 10 }}>
      <img src={photo.url} alt="活动照片" style={{ width: 110, height: 70, objectFit: 'cover' }} />
      <input aria-label={'照片说明 ' + (index + 1)} placeholder="照片说明" value={photo.cap || ''} onChange={e => update(photos.map((p, i) => i === index ? { ...p, cap: e.target.value } : p))} />
      <button type="button" onClick={() => update(photos.filter((_, i) => i !== index))}>移除</button>
    </div>)}
    <AdminImageField value={newUrl} onChange={setNewUrl} onBusyChange={onBusyChange} />
    <button type="button" disabled={!newUrl.trim()} onClick={() => { update([...photos, { url: newUrl.trim(), cap: '' }]); setNewUrl(''); }} style={{ width: 'fit-content', padding: '8px 12px' }}>添加照片</button>
  </div>;
}

function AdminBundleField({ value, onChange }) {
  let bundle = null;
  try { bundle = value ? JSON.parse(value) : null; } catch { /* Show an empty form only when explicitly enabled. */ }
  const field = { display: 'block', width: '100%', padding: 8, marginTop: 4, border: '1px solid #cbdad9', borderRadius: 4 };
  function change(key, next) {
    const data = { ...(bundle || {}), [key]: key === 'price' ? Number(next) : next };
    if (key === 'price' && next !== '' && Number.isFinite(Number(next))) data.priceText = '¥' + Number(next).toLocaleString('zh-CN');
    onChange(JSON.stringify(data, null, 2));
  }
  if (!bundle) return <button type="button" onClick={() => onChange(JSON.stringify({ t: '课程套餐', sub: '', price: 0, priceText: '¥0', save: '' }))}>添加套餐</button>;
  return <div style={{ display: 'grid', gap: 10, marginTop: 8 }}>
    {[["t", "套餐名称", 'text'], ["sub", "套餐说明", 'text'], ["price", "套餐价格（元）", 'number'], ["priceText", "价格显示文字", 'text'], ["save", "优惠说明", 'text']].map(([key, label, type]) =>
      <label key={key}>{label}<input name={'bundle-' + key} type={type} min={type === 'number' ? '0' : undefined} step={type === 'number' ? '0.01' : undefined} style={field} value={bundle[key] == null ? '' : bundle[key]} onChange={e => change(key, e.target.value)} /></label>)}
    <button type="button" onClick={() => onChange('null')} style={{ width: 'fit-content' }}>移除套餐</button>
  </div>;
}

/* A real editorial inbox for WeChat imports. Every action has a server endpoint. */
function AdminWechat({canConfigure,onOpenArticle}) {
  const [status,setStatus]=React.useState(null),[form,setForm]=React.useState(null),[jobs,setJobs]=React.useState({items:[],counts:[],total:0});
  const [filter,setFilter]=React.useState(''),[offset,setOffset]=React.useState(0),[detail,setDetail]=React.useState(null),[acceptWarnings,setAcceptWarnings]=React.useState(false);
  const [busy,setBusy]=React.useState(false),[error,setError]=React.useState(''),[notice,setNotice]=React.useState('');
  const labels={queued:'等待导入',running:'正在导入',review:'等待审核',failed:'导入失败',ok:'已处理',superseded:'已有新版本'};
  const scanLabels={running:'正在扫描',ok:'扫描完成',partial:'本批完成，可继续扫描',failed:'扫描失败',interrupted:'扫描中断'};
  async function request(url,method='GET',body){const r=await fetch(url,{method,headers:body?{'content-type':'application/json'}:undefined,body:body?JSON.stringify(body):undefined});const d=await r.json();if(!r.ok)throw new Error(d.error?.message||'请求失败');return d;}
  async function reload(){const [s,j]=await Promise.all([request('/api/admin/wechat/status'),request('/api/admin/sync-jobs?offset='+offset+(filter?'&state='+filter:''))]);setStatus(s);setForm(prev=>prev||s.options);setJobs(j);}
  React.useEffect(()=>{let active=true;async function load(){try{const [s,j]=await Promise.all([request('/api/admin/wechat/status'),request('/api/admin/sync-jobs?offset='+offset+(filter?'&state='+filter:''))]);if(active){setStatus(s);setForm(prev=>prev||s.options);setJobs(j);}}catch(e){if(active)setError(e.message);}}load();const timer=setInterval(load,7000);return()=>{active=false;clearInterval(timer);};},[filter,offset]);
  async function action(fn){setBusy(true);setError('');setNotice('');try{await fn();await reload();}catch(e){setError(e.message);}finally{setBusy(false);}}
  async function open(id){await action(async()=>{setDetail(await request('/api/admin/sync-jobs/'+id));setAcceptWarnings(false);});}
  function html(body){try{return JSON.parse(body||'[]').map(b=>b.type==='html'?b.text:'<p>'+String(b.text||'').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;')+'</p>').join('');}catch{return '';}}
  function document(body){return '<!doctype html><html><head><meta http-equiv="Content-Security-Policy" content="default-src \'none\'; img-src https: http: data:; style-src \'unsafe-inline\';"><style>body{font-family:system-ui,sans-serif;padding:20px;color:#24433b;overflow-wrap:anywhere}img{max-width:100%;height:auto}</style></head><body>'+html(body)+'</body></html>';}
  const config=status?.configuration;
  return <section className="qa-wechat">
    <div className="qa-list-heading"><div><h1>公众号连接与同步</h1><p className="qa-wechat-lead">文章进入编辑工作流，审核后再更新官网。</p></div><button disabled={busy||!config?.apiConfigured||status?.scan?.state==='running'} onClick={()=>action(async()=>{await request('/api/admin/sync/scan','POST');setNotice('扫描已开始，任务列表会自动刷新。');})}>扫描公众号文章</button></div>
    {error&&<p role="alert">{error}</p>}{notice&&<p className="qa-order-notice" role="status">{notice}</p>}
    {!status?<p className="qa-empty">正在读取公众号状态…</p>:<>
      <div className="qa-wx-connection"><div><span className={'qa-status '+(config.apiConfigured?'is-live':'')}>{config.apiConfigured?'凭据已配置，待检测权限':'等待配置公众号'}</span><h2>量子催眠中国公众号</h2><p>{config.appid?'AppID '+config.appid:'由服务器安全配置文件提供凭据'}</p></div><div className="qa-wx-checks">
        {[[config.appIdSet,'AppID'],[config.secretSet,'AppSecret'],[config.tokenSet,'消息回调 Token'],[config.aesKeySet,'消息加密密钥']].map(([ok,title])=><span key={title}><b aria-hidden="true">{ok?'✓':'○'}</b>{title}<small>{ok?'已配置':'未配置'}</small></span>)}
      </div><div className="qa-wx-connect-foot"><p>登录：{config.loginMode==='message'?'公众号消息口令':config.loginMode==='auto'?'自动检测二维码 / 消息口令':'带参二维码'}；回调：{config.messageMode==='aes'?'安全加密模式':'明文模式'}。接口权限和公网回调需分别验收。</p>{canConfigure&&<button disabled={busy||!config.apiConfigured} onClick={()=>action(async()=>{const d=await request('/api/admin/wechat/test','POST');setNotice('已连接文章接口，当前来源共 '+d.total+' 条图文。登录回调仍需在微信中测试。');})}>检测文章接口</button>}</div></div>
      <div className="qa-wx-settings"><div><h2>自动同步</h2><p>首次导入存为草稿；公众号内容更新后保留官网现有版本，等待人工审核。</p></div><form onSubmit={e=>{e.preventDefault();action(async()=>{await request('/api/admin/wechat/settings','PUT',form);setNotice('同步设置已保存。');});}}>
        <label><input type="checkbox" disabled={!canConfigure||busy} checked={form?.enabled||false} onChange={e=>setForm({...form,enabled:e.target.checked})}/>开启定时扫描</label>
        <label>扫描周期<select disabled={!canConfigure||busy} value={form?.intervalMinutes||60} onChange={e=>setForm({...form,intervalMinutes:Number(e.target.value)})}>{[[15,'15 分钟'],[30,'30 分钟'],[60,'1 小时'],[180,'3 小时'],[360,'6 小时'],[1440,'每天']].map(([v,t])=><option value={v} key={v}>{t}</option>)}</select></label>
        <label>文章来源<select disabled={!canConfigure||busy} value={form?.source||'published'} onChange={e=>setForm({...form,source:e.target.value})}><option value="published">已发布文章（建议）</option><option value="materials">永久图文素材（可能含未发布内容）</option></select></label>
        {canConfigure&&<button disabled={busy} type="submit">保存同步设置</button>}
      </form></div>
      <div className="qa-wx-scan" role="status"><strong>{scanLabels[status.scan?.state]||'尚未扫描'}</strong><span>{status.scan?.at?new Date(status.scan.at).toLocaleString('zh-CN'):''}{status.scan?.pages?'；已读取 '+status.scan.pages+' 页，新增 '+status.scan.queued+' 个任务':''}</span>{status.scan?.error&&<p>{status.scan.error}</p>}</div>
      <div className="qa-wx-filters" aria-label="任务状态筛选">{[['','全部'],['review','待审核'],['failed','失败'],['queued','待导入'],['ok','已处理']].map(([v,t])=><button key={v} aria-pressed={filter===v} onClick={()=>{setOffset(0);setFilter(v);}}>{t}<small>{v?jobs.counts.find(c=>c.state===v)?.count||0:jobs.counts.reduce((n,c)=>n+c.count,0)}</small></button>)}</div>
      <div className="qa-wx-job-list">{!jobs.items.length?<div className="qa-wx-empty"><h2>暂无{filter?labels[filter]:''}同步任务</h2><p>{config.apiConfigured?'点击“扫描公众号文章”，读取真实文章并导入草稿。':'配置公众号后，先检测文章接口，再开始扫描。'}</p></div>:jobs.items.map(job=><div className="qa-wx-job" key={job.id}><div><strong>{job.title}</strong><small>任务 #{job.id}　{job.created_at} {job.attempts?'　已尝试 '+job.attempts+' 次':''}</small>{job.error&&<p>{job.error}</p>}</div><span className={'qa-status '+(job.state==='ok'?'is-live':'')}>{labels[job.state]||job.state}</span><div><button disabled={busy} onClick={()=>open(job.id)}>查看任务</button>{job.stage==='draft'&&job.post_id&&<button disabled={busy} onClick={()=>onOpenArticle(job.post_id)}>编辑草稿</button>}</div></div>)}</div>
      <div className="qa-wx-pagination"><span>共 {jobs.total} 个任务</span><button disabled={!offset||busy} onClick={()=>setOffset(n=>Math.max(0,n-40))}>上一页</button><button disabled={offset+40>=jobs.total||busy} onClick={()=>setOffset(n=>n+40)}>下一页</button></div>
    </>}
    {detail&&<div className="qa-wx-review" role="dialog" aria-modal="true" aria-labelledby="wx-review-title"><div className="qa-wx-review-paper"><div className="qa-list-heading"><div><h2 id="wx-review-title">{detail.title}</h2><p>任务 #{detail.id} · {labels[detail.state]||detail.state}</p></div><button onClick={()=>setDetail(null)}>关闭审核</button></div>
      {error&&<p role="alert">{error}</p>}
      {detail.payload?.warnings?.length>0&&<div className="qa-wx-warning"><strong>图片仍需处理</strong><p>{detail.payload.warnings.length} 张图片未能转存，可能无法在官网稳定显示。可重试转存或在文章编辑器手动上传。</p></div>}
      {detail.error&&<p role="alert">{detail.error}</p>}
      {detail.stage==='deleted'&&<p>官网原文章已被删除，此任务保留供核对，不会自动重建。</p>}
      {detail.stage==='revision'&&detail.target&&<p className="qa-order-notice">官网当前为{detail.target.status==='published'?'已发布':'草稿 / 下架'}，分类为“{detail.target.category}”。应用更新会替换标题、摘要、封面和正文，并保持当前发布状态及分类。</p>}
      {detail.payload?.candidate&&<div className={'qa-wx-previews '+(detail.stage==='revision'?'is-compare':'')}>
        {detail.stage==='revision'&&detail.target&&<div><h3>官网当前版本：{detail.target.title}</h3><iframe title="官网当前文章" sandbox="" srcDoc={document(detail.target.body)}/></div>}
        <div><h3>{detail.stage==='revision'?'公众号新版本':'导入内容'}：{detail.payload.candidate.title}</h3><iframe title="公众号导入文章" sandbox="" srcDoc={document(detail.payload.candidate.body)}/></div>
      </div>}
      <div className="qa-wx-review-actions">
        {['failed','review'].includes(detail.state)&&<button disabled={busy} onClick={()=>action(async()=>{await request('/api/admin/sync-jobs/'+detail.id+'/retry','POST');setDetail(null);setNotice('任务已重新排队。');})}>重试导入与图片转存</button>}
        {detail.post_id&&detail.stage==='draft'&&<button disabled={busy} onClick={()=>onOpenArticle(detail.post_id)}>进入文章编辑与发布</button>}
        {detail.state==='review'&&detail.stage==='revision'&&detail.target&&<>
          {!!detail.payload.warnings?.length&&<label><input type="checkbox" checked={acceptWarnings} onChange={e=>setAcceptWarnings(e.target.checked)}/>已核对未转存的图片，仍应用此版本</label>}
          <button className="qa-wx-primary" disabled={busy||(!acceptWarnings&&!!detail.payload.warnings?.length)} onClick={()=>action(async()=>{await request('/api/admin/sync-jobs/'+detail.id+'/apply','POST',{targetHash:detail.targetHash,acceptImageWarnings:acceptWarnings});setDetail(null);setNotice('已应用公众号更新，文章发布状态保持原样。');})}>{detail.target.status==='published'?'审核通过并更新已发布文章':'审核通过并更新草稿'}</button>
        </>}
        {detail.state==='review'&&<button disabled={busy} onClick={()=>action(async()=>{await request('/api/admin/sync-jobs/'+detail.id+'/dismiss','POST');setDetail(null);setNotice('已保留官网内容，此次任务标为已处理。');})}>保留官网内容，结束本次审核</button>}
      </div>
    </div></div>}
  </section>;
}
