// Section 3 admin pages: Messaging, Announcements, MatchLogs

// === 3.1 通訊中心 ===
const AdminMessagingPage = () => {
  const c = useTokens();
  const D = window.HAOLIN_DATA;
  const [tab, setTab] = useState('compose');
  return (
    <div style={{background:c.bg, minHeight:'100vh'}}>
      <div style={{padding:'28px 40px 0'}}>
        <div style={{display:'flex', justifyContent:'space-between', alignItems:'flex-end', marginBottom:18}}>
          <div>
            <div style={{fontSize:13, color:c.primary, fontWeight:600, letterSpacing:'0.08em'}}>通訊中心</div>
            <h1 style={{fontFamily:'var(--hl-font-heading)', fontSize:30, color:c.ink, margin:'6px 0 4px', fontWeight:500}}>要跟誰說話？</h1>
            <p style={{color:c.inkSoft, fontSize:14, margin:0}}>協會的群發溝通、月報、重要公告都從這裡出去。</p>
          </div>
          <div style={{display:'flex', gap:8, background:c.paper, padding:6, borderRadius:'var(--hl-radius-lg)', border:`1px solid ${c.line}`}}>
            {[['compose','撰寫'],['history','歷史紀錄']].map(([k,l]) => (
              <button key={k} onClick={()=>setTab(k)} style={{
                padding:'8px 18px', border:'none', background: tab===k ? c.primary : 'transparent',
                color: tab===k ? '#fff' : c.inkSoft, borderRadius:'var(--hl-radius-md)',
                fontSize:14, fontWeight: tab===k ? 600 : 500, cursor:'pointer', fontFamily:'var(--hl-font-body)',
              }}>{l}</button>
            ))}
          </div>
        </div>
      </div>

      {tab === 'compose' ? <MessagingCompose/> : <MessagingHistory/>}
    </div>
  );
};

const MessagingCompose = () => {
  const c = useTokens();
  const D = window.HAOLIN_DATA;
  const [audience, setAudience] = useState('all');
  const [selected, setSelected] = useState(new Set(D.trainees.slice(0,5).map(t=>t.name)));
  const [subject, setSubject] = useState('四月月報：這個月，53 位好鄰居一起走過的路');
  const [body, setBody] = useState(
`{姓名}，

這是四月的月報。

這個月 53 位好鄰居總共辦了 142 場活動。你的 {團名} 辦了 4 場——跟上個月一樣穩，很棒。

協會這邊有三件事想跟你說：
1. 新版活動上傳功能上線了，上傳照片後會自動幫你草擬報導。
2. 五月份主揪共學會主題：「如何接住團裡崩潰的成員」。
3. 若你這陣子有任何累或卡，{對接人} 隨時等你。

一起走著。
—小好`);
  const [previewIdx, setPreviewIdx] = useState(0);
  const [schedule, setSchedule] = useState('now');
  const audiences = [['all','全體好鄰居'],['training','同行者'],['topic','特定主題'],['region','特定地區'],['custom','自訂名單']];
  const pool = audience === 'training' ? D.trainees.filter(t=>t.stage==='training') : D.trainees;
  const previewPerson = [...selected][previewIdx] || '—';
  const previewPersonData = D.trainees.find(t => t.name === previewPerson) || D.trainees[0];
  const rendered = body.replaceAll('{姓名}', previewPersonData?.name || '姓名').replaceAll('{團名}', '新店溪畔共學會').replaceAll('{對接人}', previewPersonData?.contact || '小好').replaceAll('{上次上傳日期}','4/15');

  const toggle = (name) => {
    const next = new Set(selected);
    if (next.has(name)) next.delete(name); else next.add(name);
    setSelected(next);
  };

  return (
    <div style={{display:'grid', gridTemplateColumns:'320px 1fr 380px', gap:0, borderTop:`1px solid ${c.line}`, minHeight:'calc(100vh - 140px)'}}>
      {/* LEFT: Recipient select */}
      <div style={{borderRight:`1px solid ${c.line}`, background:c.paper, display:'flex', flexDirection:'column'}}>
        <div style={{padding:'18px 20px 12px', borderBottom:`1px solid ${c.line}`}}>
          <div style={{fontSize:12, color:c.inkMuted, marginBottom:8, fontWeight:600, letterSpacing:'0.05em'}}>收件對象</div>
          <div style={{display:'flex', flexWrap:'wrap', gap:6}}>
            {audiences.map(([k,l]) => (
              <button key={k} onClick={()=>setAudience(k)} style={{
                padding:'6px 12px', fontSize:12, border:'none',
                background: audience===k ? c.ink : c.bgAlt,
                color: audience===k ? '#fff' : c.inkSoft,
                borderRadius:'var(--hl-radius-md)', cursor:'pointer', fontFamily:'var(--hl-font-body)',
                fontWeight: audience===k ? 600 : 500,
              }}>{l}</button>
            ))}
          </div>
        </div>
        <div style={{flex:1, overflowY:'auto'}}>
          {pool.map(t => {
            const on = selected.has(t.name);
            const statusText = t.stage === 'active' ? '活躍' : t.stage === 'certified' ? '已開團' : t.stage === 'training' ? '支持中' : '報名中';
            return (
              <label key={t.name} style={{
                display:'flex', alignItems:'center', gap:10,
                padding:'10px 20px', borderBottom:`1px solid ${c.lineSoft}`,
                cursor:'pointer', background: on ? c.primarySoft+'50' : 'transparent',
              }}>
                <input type="checkbox" checked={on} onChange={()=>toggle(t.name)} style={{accentColor:c.primary, width:14, height:14}}/>
                <AvatarGeo size={28} seed={t.name.charCodeAt(0)+t.name.charCodeAt(1)}/>
                <div style={{flex:1, minWidth:0}}>
                  <div style={{fontSize:13, fontWeight:600, color:c.ink}}>{t.name}</div>
                  <div style={{fontSize:11, color:c.inkMuted}}>{t.topic} · {t.contact}</div>
                </div>
                <StatusBadge status={statusText}/>
              </label>
            );
          })}
        </div>
        <div style={{padding:'16px 20px', background:c.bgAlt, borderTop:`1px solid ${c.line}`, display:'flex', alignItems:'baseline', gap:10}}>
          <span style={{fontFamily:'var(--hl-font-heading)', fontSize:30, fontWeight:500, color:c.primary}}>{selected.size}</span>
          <span style={{fontSize:13, color:c.inkSoft}}>位收件人已選</span>
          <button onClick={()=>setSelected(new Set(pool.map(t=>t.name)))} style={{marginLeft:'auto', background:'none', border:'none', fontSize:12, color:c.primary, cursor:'pointer'}}>全選</button>
        </div>
      </div>

      {/* CENTER: Editor */}
      <div style={{padding:'24px 32px', display:'flex', flexDirection:'column', gap:14}}>
        <Input label="主題" value={subject} onChange={e=>setSubject(e.target.value)}/>

        {/* Toolbar */}
        <div style={{display:'flex', gap:4, padding:'6px', background:c.paper, border:`1px solid ${c.line}`, borderRadius:'var(--hl-radius-md)', flexWrap:'wrap'}}>
          {['B','I','連結','圖片','分隔線'].map(t => (
            <button key={t} style={{
              padding:'6px 10px', border:'none', background:'transparent', color:c.inkSoft,
              fontSize:12, fontWeight: t==='B' ? 700 : (t==='I' ? 500 : 500),
              fontStyle: t==='I' ? 'italic' : 'normal',
              cursor:'pointer', borderRadius:4, fontFamily:'var(--hl-font-body)',
            }}
            onMouseEnter={e=>e.currentTarget.style.background=c.bgAlt}
            onMouseLeave={e=>e.currentTarget.style.background='transparent'}
            >{t}</button>
          ))}
        </div>

        {/* Body */}
        <textarea value={body} onChange={e=>setBody(e.target.value)} style={{
          flex:1, minHeight:320, padding:'18px 20px',
          background:c.paper, border:`1px solid ${c.line}`, borderRadius:'var(--hl-radius-md)',
          fontFamily:'var(--hl-font-body)', fontSize:14, lineHeight:1.85, color:c.ink,
          outline:'none', resize:'vertical',
        }}/>

        {/* Footer tools */}
        <div style={{display:'flex', gap:10, alignItems:'center', flexWrap:'wrap'}}>
          <select style={{padding:'8px 12px', border:`1px solid ${c.line}`, background:c.paper, borderRadius:'var(--hl-radius-md)', fontSize:13, fontFamily:'var(--hl-font-body)', color:c.inkSoft, cursor:'pointer'}}
            onChange={e=>{
              const t = D.messageTemplates.find(t=>t.key===e.target.value);
              if (t) setSubject(t.label);
            }}>
            <option>使用範本…</option>
            {D.messageTemplates.map(t => <option key={t.key} value={t.key}>{t.label}</option>)}
          </select>

          <div style={{position:'relative'}}>
            <Button variant="secondary" size="sm"><IconPlus size={13}/> 插入變數</Button>
          </div>

          <div style={{display:'flex', gap:6, marginLeft:'auto', alignItems:'center'}}>
            <span style={{fontSize:11, color:c.primary, fontWeight:600, display:'inline-flex', alignItems:'center', gap:4}}>
              <IconSparkle size={12}/> AI 協助
            </span>
            {['潤稿','變溫暖一點','縮短'].map(t => (
              <button key={t} style={{
                padding:'6px 12px', fontSize:12, border:`1px solid ${c.primary}40`,
                background: '#fff', color:c.primary, borderRadius:999, cursor:'pointer', fontFamily:'var(--hl-font-body)',
              }}>{t}</button>
            ))}
          </div>
        </div>

        <div style={{fontSize:11, color:c.inkMuted, textAlign:'right'}}>字數：{body.length}</div>
      </div>

      {/* RIGHT: Preview + schedule */}
      <div style={{borderLeft:`1px solid ${c.line}`, background:c.bgAlt, display:'flex', flexDirection:'column'}}>
        <div style={{padding:'18px 22px 12px', borderBottom:`1px solid ${c.line}`, background:c.paper}}>
          <div style={{display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:10}}>
            <span style={{fontSize:12, color:c.inkMuted, fontWeight:600, letterSpacing:'0.05em'}}>收信人預覽</span>
            <select value={previewIdx} onChange={e=>setPreviewIdx(Number(e.target.value))} style={{fontSize:12, border:`1px solid ${c.line}`, borderRadius:'var(--hl-radius-md)', padding:'4px 8px', fontFamily:'var(--hl-font-body)', color:c.inkSoft, background:c.paper, cursor:'pointer'}}>
              {[...selected].map((n, i) => <option key={n} value={i}>以 {n} 看</option>)}
            </select>
          </div>
        </div>

        <div style={{flex:1, overflowY:'auto', padding:'18px 22px', background:c.paper}}>
          <div style={{border:`1px solid ${c.line}`, borderRadius:'var(--hl-radius-md)', overflow:'hidden'}}>
            {/* Envelope header */}
            <div style={{padding:'12px 16px', background:c.bgAlt, fontSize:11, color:c.inkMuted, borderBottom:`1px solid ${c.line}`}}>
              <div><b style={{color:c.inkSoft}}>寄件人</b>　小好 &lt;hello@haolin.tw&gt;</div>
              <div style={{marginTop:3}}><b style={{color:c.inkSoft}}>收件人</b>　{previewPerson}</div>
              <div style={{marginTop:3}}><b style={{color:c.inkSoft}}>主題</b>　{subject}</div>
            </div>
            <div style={{padding:'18px 20px', fontSize:13, lineHeight:1.85, color:c.ink, fontFamily:'var(--hl-font-body)', whiteSpace:'pre-wrap'}}>
              {rendered}
            </div>
          </div>
        </div>

        {/* Schedule */}
        <div style={{padding:'18px 22px', borderTop:`1px solid ${c.line}`, background:c.paper, display:'flex', flexDirection:'column', gap:14}}>
          <div>
            <div style={{fontSize:12, color:c.inkMuted, marginBottom:8, fontWeight:600}}>發送方式</div>
            <div style={{display:'flex', gap:6}}>
              <button onClick={()=>setSchedule('now')} style={{flex:1, padding:'10px 12px', border:`1px solid ${schedule==='now' ? c.primary : c.line}`, background: schedule==='now' ? c.primarySoft : '#fff', color: schedule==='now' ? c.primaryDark : c.inkSoft, borderRadius:'var(--hl-radius-md)', fontSize:13, fontWeight:500, cursor:'pointer', fontFamily:'var(--hl-font-body)'}}>立即</button>
              <button onClick={()=>setSchedule('later')} style={{flex:1, padding:'10px 12px', border:`1px solid ${schedule==='later' ? c.primary : c.line}`, background: schedule==='later' ? c.primarySoft : '#fff', color: schedule==='later' ? c.primaryDark : c.inkSoft, borderRadius:'var(--hl-radius-md)', fontSize:13, fontWeight:500, cursor:'pointer', fontFamily:'var(--hl-font-body)'}}>排程</button>
            </div>
            {schedule === 'later' && (
              <div style={{display:'flex', gap:6, marginTop:8}}>
                <input type="date" defaultValue="2026-04-22" style={{flex:1, padding:'8px 10px', border:`1px solid ${c.line}`, borderRadius:'var(--hl-radius-md)', fontSize:12, fontFamily:'var(--hl-font-body)'}}/>
                <input type="time" defaultValue="10:00" style={{width:90, padding:'8px 10px', border:`1px solid ${c.line}`, borderRadius:'var(--hl-radius-md)', fontSize:12, fontFamily:'var(--hl-font-body)'}}/>
              </div>
            )}
          </div>

          <div style={{display:'flex', flexDirection:'column', gap:8, fontSize:13, color:c.inkSoft}}>
            <label style={{display:'flex', alignItems:'center', gap:8, cursor:'pointer'}}>
              <input type="checkbox" defaultChecked style={{accentColor:c.primary}}/> 追蹤已開信
            </label>
            <label style={{display:'flex', alignItems:'center', gap:8, cursor:'pointer'}}>
              <input type="checkbox" defaultChecked style={{accentColor:c.primary}}/> 追蹤已點擊連結
            </label>
          </div>

          <Button variant="primary" size="lg" style={{width:'100%'}}><IconSend size={15}/> 發送給 {selected.size} 位</Button>
        </div>
      </div>
    </div>
  );
};

const MessagingHistory = () => {
  const c = useTokens();
  const D = window.HAOLIN_DATA;
  const [selected, setSelected] = useState(null);
  return (
    <div style={{padding:'24px 40px 40px'}}>
      <Card padding={false}>
        <table style={{width:'100%', borderCollapse:'collapse'}}>
          <thead>
            <tr style={{background:c.bgAlt, borderBottom:`1px solid ${c.line}`}}>
              {['主題','對象','收件','發送時間','開信率','點擊率','回覆'].map(h => (
                <th key={h} style={{padding:'14px 18px', textAlign:'left', fontSize:12, fontWeight:600, color:c.inkMuted, letterSpacing:'0.05em'}}>{h}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {D.campaigns.map(r => {
              const draft = r.status === '草稿';
              return (
                <tr key={r.id} onClick={()=>setSelected(r)} style={{borderBottom:`1px solid ${c.lineSoft}`, cursor:'pointer'}}
                  onMouseEnter={e=>e.currentTarget.style.background=c.bgAlt}
                  onMouseLeave={e=>e.currentTarget.style.background='transparent'}>
                  <td style={{padding:'14px 18px', fontSize:13, color:c.ink, fontWeight:500, maxWidth:360}}>
                    {draft && <span style={{display:'inline-block', padding:'1px 7px', fontSize:10, background:c.bgAlt, color:c.inkMuted, borderRadius:4, marginRight:6, fontWeight:600}}>草稿</span>}
                    {r.subject}
                  </td>
                  <td style={{padding:'14px 18px', fontSize:12, color:c.inkSoft}}>{r.audience}</td>
                  <td style={{padding:'14px 18px', fontSize:13, color:c.inkSoft}}>{r.recipients}</td>
                  <td style={{padding:'14px 18px', fontSize:12, color:c.inkMuted, fontFamily:'var(--hl-font-mono, monospace)'}}>{r.sentAt}</td>
                  <td style={{padding:'14px 18px', fontSize:13, color:c.ink}}>{draft ? '—' : <RateBar pct={r.openRate} color={c.accent}/>}</td>
                  <td style={{padding:'14px 18px', fontSize:13, color:c.ink}}>{draft ? '—' : <RateBar pct={r.clickRate} color={c.primary}/>}</td>
                  <td style={{padding:'14px 18px', fontSize:13, color:c.inkSoft}}>{draft ? '—' : `${r.replies} 則`}</td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </Card>

      {selected && (
        <div onClick={()=>setSelected(null)} style={{position:'fixed', inset:0, background:'rgba(30,20,10,0.4)', zIndex:60, display:'flex', justifyContent:'flex-end'}}>
          <div onClick={e=>e.stopPropagation()} style={{width:560, maxWidth:'92vw', height:'100vh', overflowY:'auto', background:c.bg, padding:'28px 32px'}}>
            <div style={{display:'flex', justifyContent:'space-between', alignItems:'flex-start', marginBottom:18}}>
              <div>
                <div style={{fontSize:12, color:c.inkMuted, marginBottom:4}}>{selected.sentAt} · 寄給 {selected.recipients} 位 · {selected.audience}</div>
                <h3 style={{fontFamily:'var(--hl-font-heading)', fontSize:20, color:c.ink, margin:0, fontWeight:500}}>{selected.subject}</h3>
              </div>
              <button onClick={()=>setSelected(null)} style={{background:'none', border:'none', cursor:'pointer'}}><IconX size={18} stroke={c.inkMuted}/></button>
            </div>
            <div style={{display:'grid', gridTemplateColumns:'repeat(3, 1fr)', gap:10, marginBottom:20}}>
              {[['開信率', selected.openRate+'%', c.accent], ['點擊率', selected.clickRate+'%', c.primary], ['回覆', selected.replies+' 則', c.gold]].map(([l,v,col]) => (
                <div key={l} style={{background:c.paper, border:`1px solid ${c.line}`, borderRadius:'var(--hl-radius-md)', padding:'14px 16px'}}>
                  <div style={{fontSize:11, color:c.inkMuted, marginBottom:4}}>{l}</div>
                  <div style={{fontFamily:'var(--hl-font-heading)', fontSize:24, color:col, fontWeight:500}}>{v}</div>
                </div>
              ))}
            </div>
            <div style={{background:c.paper, border:`1px solid ${c.line}`, borderRadius:'var(--hl-radius-md)', padding:'18px 20px', fontSize:13, lineHeight:1.85, color:c.inkSoft}}>
              此處顯示完整信件內容（略）。
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

const RateBar = ({ pct, color }) => {
  const c = useTokens();
  return (
    <div style={{display:'flex', alignItems:'center', gap:8}}>
      <div style={{flex:1, height:4, background:c.bgAlt, borderRadius:999, overflow:'hidden', maxWidth:80}}>
        <div style={{width:`${pct}%`, height:'100%', background:color, borderRadius:999}}/>
      </div>
      <span style={{fontSize:12, color:c.inkSoft, fontWeight:500, minWidth:28}}>{pct}%</span>
    </div>
  );
};

// === 3.2 公告管理 ===
const AdminAnnouncementsPage = () => {
  const c = useTokens();
  const D = window.HAOLIN_DATA;
  const [showNew, setShowNew] = useState(false);
  return (
    <div style={{padding:'32px 40px', background:c.bg, minHeight:'100vh'}}>
      <div style={{display:'flex', justifyContent:'space-between', alignItems:'flex-end', marginBottom:24}}>
        <div>
          <div style={{fontSize:13, color:c.primary, fontWeight:600, letterSpacing:'0.08em'}}>公告管理</div>
          <h1 style={{fontFamily:'var(--hl-font-heading)', fontSize:30, color:c.ink, margin:'6px 0 4px', fontWeight:500}}>協會要說的話，放這裡。</h1>
          <p style={{color:c.inkSoft, fontSize:14, margin:0}}>公告會同步出現在前台與好鄰居後台。</p>
        </div>
        <Button size="sm" onClick={()=>setShowNew(true)}><IconPlus size={14}/> 新增公告</Button>
      </div>

      <Card padding={false}>
        {D.announcements.map((a, i) => (
          <div key={a.id} style={{
            padding:'18px 24px', borderBottom: i<D.announcements.length-1 ? `1px solid ${c.lineSoft}` : 'none',
            display:'grid', gridTemplateColumns:'1fr auto auto auto', gap:18, alignItems:'center', cursor:'pointer',
          }}
          onMouseEnter={e=>e.currentTarget.style.background=c.bgAlt}
          onMouseLeave={e=>e.currentTarget.style.background='transparent'}
          >
            <div>
              <div style={{display:'flex', alignItems:'center', gap:8, marginBottom:4}}>
                <div style={{fontSize:15, fontWeight:600, color:c.ink}}>{a.title}</div>
                {a.pushedTrainee && <span style={{fontSize:10, padding:'1px 7px', background:c.accentSoft, color:'#4D6D41', borderRadius:4, fontWeight:600}}>推送主揪後台</span>}
              </div>
              <div style={{fontSize:13, color:c.inkSoft, lineHeight:1.6}}>{a.summary}</div>
            </div>
            <div style={{fontSize:12, color:c.inkMuted}}>{a.audience}</div>
            <div style={{fontSize:12, color:c.inkMuted, fontFamily:'var(--hl-font-mono, monospace)', minWidth:90}}>{a.publishAt}</div>
            <AnnouncementStatusBadge status={a.status}/>
          </div>
        ))}
      </Card>

      {showNew && <NewAnnouncementModal onClose={()=>setShowNew(false)}/>}
    </div>
  );
};

const AnnouncementStatusBadge = ({ status }) => {
  const c = useTokens();
  const map = {
    '草稿':    { bg:c.lineSoft, color:c.inkMuted, dot:c.inkMuted },
    '排程中':  { bg:'#F6E5C9', color:'#8B6830', dot:'#D9A84A' },
    '已發送':  { bg:c.accentSoft, color:'#4D6D41', dot:c.accent },
  };
  const m = map[status] || map['草稿'];
  return (
    <span style={{display:'inline-flex', alignItems:'center', gap:6, padding:'3px 10px', fontSize:12, fontWeight:500, borderRadius:999, background:m.bg, color:m.color, minWidth:70, justifyContent:'center'}}>
      <span style={{width:6, height:6, borderRadius:'50%', background:m.dot}}/>
      {status}
    </span>
  );
};

const NewAnnouncementModal = ({ onClose }) => {
  const c = useTokens();
  return (
    <div onClick={onClose} style={{position:'fixed', inset:0, background:'rgba(30,20,10,0.4)', zIndex:60, display:'flex', alignItems:'center', justifyContent:'center'}}>
      <div onClick={e=>e.stopPropagation()} style={{width:560, maxWidth:'92vw', background:c.paper, borderRadius:'var(--hl-radius-xl)', padding:'28px 32px'}}>
        <div style={{display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:18}}>
          <h3 style={{fontFamily:'var(--hl-font-heading)', fontSize:22, color:c.ink, margin:0, fontWeight:500}}>新增公告</h3>
          <button onClick={onClose} style={{background:'none',border:'none',cursor:'pointer'}}><IconX size={18} stroke={c.inkMuted}/></button>
        </div>
        <div style={{display:'flex', flexDirection:'column', gap:14}}>
          <Input label="標題" placeholder="例：五月份主揪共學會報名開放"/>
          <div>
            <label style={{fontSize:12, color:c.inkMuted, fontWeight:600, marginBottom:6, display:'block'}}>內文</label>
            <textarea rows={5} placeholder="把想說的話寫清楚⋯" style={{
              width:'100%', padding:'12px 14px', border:`1px solid ${c.line}`, borderRadius:'var(--hl-radius-md)',
              fontFamily:'var(--hl-font-body)', fontSize:14, lineHeight:1.8, color:c.ink, outline:'none', resize:'vertical', boxSizing:'border-box',
            }}/>
          </div>
          <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:12}}>
            <div>
              <label style={{fontSize:12, color:c.inkMuted, fontWeight:600, marginBottom:6, display:'block'}}>對象</label>
              <select style={{width:'100%', padding:'10px 12px', border:`1px solid ${c.line}`, borderRadius:'var(--hl-radius-md)', fontSize:13, fontFamily:'var(--hl-font-body)', background:'#fff'}}>
                <option>全體好鄰居</option>
                <option>同行中好鄰居</option>
                <option>已開團好鄰居</option>
                <option>活躍好鄰居</option>
              </select>
            </div>
            <div>
              <label style={{fontSize:12, color:c.inkMuted, fontWeight:600, marginBottom:6, display:'block'}}>發布時間</label>
              <select style={{width:'100%', padding:'10px 12px', border:`1px solid ${c.line}`, borderRadius:'var(--hl-radius-md)', fontSize:13, fontFamily:'var(--hl-font-body)', background:'#fff'}}>
                <option>立即發布</option>
                <option>排程發布</option>
              </select>
            </div>
          </div>
          <label style={{display:'flex', alignItems:'center', gap:8, fontSize:13, color:c.inkSoft, marginTop:4}}>
            <input type="checkbox" defaultChecked style={{accentColor:c.primary}}/> 同步推送到主揪後台
          </label>
        </div>
        <div style={{display:'flex', gap:10, marginTop:22}}>
          <Button variant="secondary" style={{flex:1}} onClick={onClose}>儲存為草稿</Button>
          <Button variant="primary" style={{flex:1}} onClick={onClose}>發布公告</Button>
        </div>
      </div>
    </div>
  );
};

// === 3.3 媒合紀錄查看 ===
const AdminMatchLogsPage = () => {
  const c = useTokens();
  const D = window.HAOLIN_DATA;
  const [selected, setSelected] = useState(null);

  return (
    <div style={{padding:'32px 40px', background:c.bg, minHeight:'100vh'}}>
      <div style={{marginBottom:24}}>
        <div style={{fontSize:13, color:c.primary, fontWeight:600, letterSpacing:'0.08em'}}>媒合紀錄</div>
        <h1 style={{fontFamily:'var(--hl-font-heading)', fontSize:30, color:c.ink, margin:'6px 0 4px', fontWeight:500}}>這些人找上門了。</h1>
        <p style={{color:c.inkSoft, fontSize:14, margin:0}}>AI 推薦之後，到底有沒有真的連起來？這裡看得清楚。</p>
      </div>

      <div style={{display:'grid', gridTemplateColumns:'repeat(3, 1fr)', gap:16, marginBottom:24}}>
        <Card style={{padding:'22px 26px'}}>
          <div style={{fontSize:12, color:c.inkMuted, marginBottom:6}}>本月媒合數</div>
          <div style={{fontFamily:'var(--hl-font-heading)', fontSize:42, fontWeight:500, color:c.ink, lineHeight:1}}>{D.matchStats.monthlyMatches}</div>
          <div style={{fontSize:12, color:c.accent, marginTop:8, fontWeight:600}}>{D.matchStats.monthlyDelta} 比上月</div>
        </Card>
        <Card style={{padding:'22px 26px', display:'flex', gap:20, alignItems:'center'}}>
          <div>
            <div style={{fontSize:12, color:c.inkMuted, marginBottom:6}}>推薦採用率</div>
            <div style={{fontFamily:'var(--hl-font-heading)', fontSize:42, fontWeight:500, color:c.ink, lineHeight:1}}>{D.matchStats.adoptionRate}%</div>
            <div style={{fontSize:12, color:c.accent, marginTop:8, fontWeight:600}}>{D.matchStats.adoptionDelta} 比上月</div>
          </div>
          <CircleProgress pct={D.matchStats.adoptionRate}/>
        </Card>
        <Card style={{padding:'22px 26px'}}>
          <div style={{fontSize:12, color:c.inkMuted, marginBottom:10}}>熱門需求 Top 3</div>
          <div style={{display:'flex', flexDirection:'column', gap:8}}>
            {D.matchStats.topTopics.map((t, i) => (
              <div key={t.label} style={{display:'flex', alignItems:'center', gap:10}}>
                <span style={{fontSize:12, color:c.inkMuted, width:14, textAlign:'right', fontWeight:600}}>{i+1}</span>
                <span style={{fontSize:13, color:c.ink, fontWeight:500, flex:1}}>{t.label}</span>
                <span style={{fontSize:12, color:c.inkSoft, fontWeight:600}}>{t.count}</span>
              </div>
            ))}
          </div>
        </Card>
      </div>

      <Card padding={false}>
        <table style={{width:'100%', borderCollapse:'collapse'}}>
          <thead>
            <tr style={{background:c.bgAlt, borderBottom:`1px solid ${c.line}`}}>
              {['時間','訪客','需求摘要','推薦的團','狀態','備註'].map(h => (
                <th key={h} style={{padding:'14px 18px', textAlign:'left', fontSize:12, fontWeight:600, color:c.inkMuted, letterSpacing:'0.05em'}}>{h}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {D.matchLogs.map(r => (
              <tr key={r.id} onClick={()=>setSelected(r)} style={{borderBottom:`1px solid ${c.lineSoft}`, cursor:'pointer'}}
                onMouseEnter={e=>e.currentTarget.style.background=c.bgAlt}
                onMouseLeave={e=>e.currentTarget.style.background='transparent'}>
                <td style={{padding:'14px 18px', fontSize:12, color:c.inkMuted, fontFamily:'var(--hl-font-mono, monospace)', whiteSpace:'nowrap'}}>{r.at}</td>
                <td style={{padding:'14px 18px', fontSize:13, color:c.inkSoft, fontFamily:'var(--hl-font-mono, monospace)'}}>{r.email}</td>
                <td style={{padding:'14px 18px', fontSize:13, color:c.ink, maxWidth:280}}>{r.need}</td>
                <td style={{padding:'14px 18px'}}>
                  <div style={{display:'flex', alignItems:'center', gap:-6}}>
                    {r.recs.map((n, i) => (
                      <div key={i} title={n} style={{marginLeft: i===0 ? 0 : -6, border:`2px solid ${c.paper}`, borderRadius:'50%'}}>
                        <AvatarGeo size={26} seed={n.charCodeAt(0)+n.charCodeAt(1)}/>
                      </div>
                    ))}
                  </div>
                </td>
                <td style={{padding:'14px 18px'}}><MatchStatusBadge status={r.status}/></td>
                <td style={{padding:'14px 18px', fontSize:12, color:c.inkMuted, maxWidth:160}}>{r.note}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </Card>

      {selected && <MatchLogDrawer log={selected} onClose={()=>setSelected(null)}/>}
    </div>
  );
};

const CircleProgress = ({ pct }) => {
  const c = useTokens();
  const r = 28, circ = 2*Math.PI*r;
  const offset = circ * (1 - pct/100);
  return (
    <svg width="72" height="72" viewBox="0 0 72 72">
      <circle cx="36" cy="36" r={r} fill="none" stroke={c.bgAlt} strokeWidth="7"/>
      <circle cx="36" cy="36" r={r} fill="none" stroke={c.accent} strokeWidth="7" strokeDasharray={circ} strokeDashoffset={offset} strokeLinecap="round" transform="rotate(-90 36 36)"/>
      <text x="36" y="40" textAnchor="middle" fontFamily="var(--hl-font-heading)" fontSize="14" fill={c.ink} fontWeight="500">{pct}%</text>
    </svg>
  );
};

const MatchStatusBadge = ({ status }) => {
  const c = useTokens();
  const map = {
    '未聯絡':   { bg:c.lineSoft,  color:c.inkMuted,    dot:c.inkMuted },
    '已聯絡':   { bg:'#F6E5C9',   color:'#8B6830',     dot:'#D9A84A' },
    '媒合成功': { bg:c.accentSoft,color:'#4D6D41',     dot:c.accent },
    '媒合失敗': { bg:'#F0D8D0',   color:'#8A4E3A',     dot:'#B87060' },
  };
  const m = map[status] || map['未聯絡'];
  return (
    <span style={{display:'inline-flex', alignItems:'center', gap:6, padding:'3px 10px', fontSize:12, fontWeight:500, borderRadius:999, background:m.bg, color:m.color}}>
      <span style={{width:6, height:6, borderRadius:'50%', background:m.dot}}/>
      {status}
    </span>
  );
};

const MatchLogDrawer = ({ log, onClose }) => {
  const c = useTokens();
  return (
    <div onClick={onClose} style={{position:'fixed', inset:0, background:'rgba(30,20,10,0.4)', zIndex:60, display:'flex', justifyContent:'flex-end'}}>
      <div onClick={e=>e.stopPropagation()} style={{width:580, maxWidth:'92vw', height:'100vh', overflowY:'auto', background:c.bg, padding:'28px 32px'}}>
        <div style={{display:'flex', justifyContent:'space-between', alignItems:'flex-start', marginBottom:18}}>
          <div>
            <div style={{fontSize:12, color:c.inkMuted, marginBottom:4, fontFamily:'var(--hl-font-mono, monospace)'}}>{log.at}</div>
            <h3 style={{fontFamily:'var(--hl-font-heading)', fontSize:20, color:c.ink, margin:0, fontWeight:500}}>{log.email}</h3>
            <div style={{marginTop:10}}><MatchStatusBadge status={log.status}/></div>
          </div>
          <button onClick={onClose} style={{background:'none',border:'none',cursor:'pointer'}}><IconX size={18} stroke={c.inkMuted}/></button>
        </div>

        <div style={{fontSize:12, color:c.inkMuted, fontWeight:600, marginBottom:8, letterSpacing:'0.05em'}}>訪客的需求</div>
        <div style={{background:c.paper, border:`1px solid ${c.line}`, borderRadius:'var(--hl-radius-md)', padding:'14px 16px', fontSize:14, color:c.inkSoft, lineHeight:1.8, marginBottom:20}}>
          {log.need}
        </div>

        <div style={{fontSize:12, color:c.inkMuted, fontWeight:600, marginBottom:8, letterSpacing:'0.05em'}}>AI 推薦的原始理由</div>
        <div style={{background:c.paper, border:`1px solid ${c.line}`, borderRadius:'var(--hl-radius-md)', padding:'14px 16px', fontSize:13, color:c.inkSoft, lineHeight:1.8, marginBottom:8, fontFamily:'var(--hl-font-mono, monospace)'}}>
          「訪客需求包含<b>地緣（新北市）</b>、<b>週末可帶小孩</b>、<b>育兒主題</b>。三個候選團都符合時間與地緣，但『新店溪畔共學會』最接近『戶外＋親子＋免費』的組合。」
        </div>
        <div style={{fontSize:12, color:c.inkMuted, marginBottom:20}}>推薦信心分數：0.87 / 0.72 / 0.58</div>

        <div style={{fontSize:12, color:c.inkMuted, fontWeight:600, marginBottom:8, letterSpacing:'0.05em'}}>推薦的三個團</div>
        <div style={{display:'flex', flexDirection:'column', gap:8, marginBottom:20}}>
          {log.recs.map((n, i) => (
            <div key={i} style={{display:'flex', alignItems:'center', gap:12, background:c.paper, border:`1px solid ${c.line}`, borderRadius:'var(--hl-radius-md)', padding:'10px 14px'}}>
              <span style={{fontSize:11, color:c.inkMuted, fontWeight:600, width:14}}>{i+1}</span>
              <AvatarGeo size={32} seed={n.charCodeAt(0)+n.charCodeAt(1)}/>
              <div style={{flex:1, fontSize:13, color:c.ink, fontWeight:500}}>{n}</div>
              <span style={{fontSize:11, color:c.inkMuted}}>信心 {[87,72,58][i]}%</span>
            </div>
          ))}
        </div>

        <div style={{fontSize:12, color:c.inkMuted, fontWeight:600, marginBottom:8, letterSpacing:'0.05em'}}>後續回饋</div>
        <div style={{background:c.bgAlt, borderRadius:'var(--hl-radius-md)', padding:'14px 16px', fontSize:13, color:c.inkSoft, lineHeight:1.8}}>
          {log.note === '—' ? '尚無回饋。' : log.note}
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { AdminMessagingPage, AdminAnnouncementsPage, AdminMatchLogsPage });
