// Page 7: Admin Dashboard + Page 8: Neighbors management + Page 10: Training

const AdminDashPage = () => {
  const c = useTokens();
  const D = window.HAOLIN_DATA;
  // 12-week trend sparkline data
  const trend = [32, 38, 35, 44, 48, 42, 52, 58, 54, 66, 72, 86];
  const maxT = Math.max(...trend);

  return (
    <div style={{padding:'32px 40px', background:c.bg, minHeight:'100vh'}}>
      <div style={{display:'flex', justifyContent:'space-between', alignItems:'flex-end', marginBottom:28}}>
        <div>
          <div style={{fontSize:13, color:c.primary, fontWeight:600, letterSpacing:'0.08em'}}>總覽</div>
          <h1 style={{fontFamily:'var(--hl-font-heading)', fontSize:34, color:c.ink, margin:'6px 0 4px', fontWeight:500}}>早安，今天協會有 3 件事要看看</h1>
          <p style={{color:c.inkSoft, fontSize:14, margin:0}}>2026 年 4 月 20 日 · 週日</p>
        </div>
        <div style={{display:'flex', gap:10}}>
          <Button variant="secondary" size="sm"><IconCalendar size={14}/> 本月</Button>
          <Button size="sm"><IconPlus size={14}/> 新增好鄰居</Button>
        </div>
      </div>

      {/* Stat cards */}
      <div style={{display:'grid', gridTemplateColumns:'repeat(4, 1fr)', gap:16, marginBottom:28}}>
        <StatCard label="活躍好鄰居團" n={D.stats.active} delta="+4" tone="primary" icon={<IconUsers size={18}/>}/>
        <StatCard label="本月活動" n={D.stats.eventsMonth} delta="+18%" tone="accent" icon={<IconCalendar size={18}/>}/>
        <StatCard label="累計媒合" n={D.stats.matches.toLocaleString()} delta="+142 本月" tone="warm" icon={<IconSparkle size={18}/>}/>
        <StatCard label="同行中的好鄰居" n={D.stats.training} delta="5 人即將開團" tone="info" icon={<IconHeartHands size={18}/>}/>
      </div>

      {/* Trend */}
      <Card style={{marginBottom:28}}>
        <div style={{display:'flex', justifyContent:'space-between', alignItems:'flex-start', marginBottom:24}}>
          <div>
            <h3 style={{fontFamily:'var(--hl-font-heading)', fontSize:20, color:c.ink, margin:0, fontWeight:500}}>活動量趨勢</h3>
            <p style={{fontSize:13, color:c.inkSoft, margin:'4px 0 0'}}>最近 12 週，每週舉辦的活動總場次</p>
          </div>
          <div style={{display:'flex', gap:8}}>
            <FilterChip active>12 週</FilterChip>
            <FilterChip>半年</FilterChip>
            <FilterChip>全年</FilterChip>
          </div>
        </div>
        <Chart data={trend}/>
      </Card>

      {/* Bottom 2 cols */}
      <div style={{display:'grid', gridTemplateColumns:'1.2fr 1fr', gap:20}}>
        <Card padding={false}>
          <div style={{padding:'20px 24px', borderBottom:`1px solid ${c.line}`, display:'flex', justifyContent:'space-between', alignItems:'center'}}>
            <h3 style={{fontFamily:'var(--hl-font-heading)', fontSize:18, color:c.ink, margin:0, fontWeight:500}}>最近活動紀錄</h3>
            <span style={{fontSize:12, color:c.inkMuted}}>需要審核 <strong style={{color:c.primary}}>2 則</strong></span>
          </div>
          <div>
            {D.recentEvents.map((e, i) => (
              <div key={i} style={{padding:'14px 24px', borderBottom: i<D.recentEvents.length-1 ? `1px solid ${c.lineSoft}` : 'none', display:'flex', alignItems:'center', gap:14}}>
                <div style={{width:40, height:40, borderRadius:'var(--hl-radius-sm)', background:c.bgAlt, display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0}}>
                  <IconImage size={16} stroke={c.inkMuted}/>
                </div>
                <div style={{flex:1, minWidth:0}}>
                  <div style={{fontSize:14, fontWeight:600, color:c.ink, overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap'}}>{e.title}</div>
                  <div style={{fontSize:12, color:c.inkMuted, marginTop:2}}>{e.group} · {e.photos} 張照片</div>
                </div>
                <span style={{fontSize:12, color:c.inkMuted}}>{e.date}</span>
                <StatusBadge status={e.status}/>
              </div>
            ))}
          </div>
        </Card>

        <Card padding={false}>
          <div style={{padding:'20px 24px', borderBottom:`1px solid ${c.line}`}}>
            <h3 style={{fontFamily:'var(--hl-font-heading)', fontSize:18, color:c.ink, margin:0, fontWeight:500}}>最近媒合紀錄</h3>
            <p style={{fontSize:12, color:c.inkMuted, margin:'4px 0 0'}}>過去 3 天的 AI 媒合結果</p>
          </div>
          <div>
            {D.recentMatches.map((m, i) => (
              <div key={i} style={{padding:'14px 24px', borderBottom: i<D.recentMatches.length-1 ? `1px solid ${c.lineSoft}` : 'none'}}>
                <div style={{display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:4}}>
                  <span style={{fontSize:13, fontWeight:600, color:c.ink}}>{m.user}</span>
                  <span style={{fontSize:11, color:c.inkMuted}}>{m.when}</span>
                </div>
                <div style={{fontSize:12, color:c.inkSoft, marginBottom:6, lineHeight:1.5}}>{m.wants}</div>
                <div style={{display:'flex', alignItems:'center', gap:6, flexWrap:'wrap'}}>
                  <IconArrow size={12} stroke={c.inkMuted}/>
                  <span style={{fontSize:12, color:c.ink, fontWeight:500}}>{m.matched}</span>
                  <span style={{marginLeft:'auto', fontSize:11, padding:'2px 8px', borderRadius:'999px',
                    background: m.contacted ? c.accentSoft : c.bgAlt,
                    color: m.contacted ? '#4D6D41' : c.inkMuted,
                  }}>{m.contacted ? '已聯絡' : '未聯絡'}</span>
                </div>
              </div>
            ))}
          </div>
        </Card>
      </div>
    </div>
  );
};

const StatCard = ({ label, n, delta, tone, icon }) => {
  const c = useTokens();
  const toneMap = {
    primary: { bg: c.primarySoft, color: c.primaryDark },
    accent:  { bg: c.accentSoft, color: '#4D6D41' },
    warm:    { bg:'#F7E3D2', color:'#9C5B39' },
    info:    { bg:'#F7E3D2', color: c.info },
  };
  const t = toneMap[tone];
  return (
    <Card style={{padding:'20px 22px'}}>
      <div style={{display:'flex', justifyContent:'space-between', alignItems:'flex-start', marginBottom:16}}>
        <span style={{fontSize:13, color:c.inkSoft}}>{label}</span>
        <div style={{width:34, height:34, borderRadius:'var(--hl-radius-sm)', background:t.bg, color:t.color, display:'flex', alignItems:'center', justifyContent:'center'}}>{icon}</div>
      </div>
      <div style={{fontFamily:'var(--hl-font-heading)', fontSize:32, fontWeight:500, color:c.ink, lineHeight:1}}>{n}</div>
      <div style={{fontSize:12, color:t.color, marginTop:8, fontWeight:500}}>{delta}</div>
    </Card>
  );
};

const Chart = ({ data }) => {
  const c = useTokens();
  const maxV = Math.max(...data);
  const w = 900, h = 200;
  const stepX = w / (data.length - 1);
  const pts = data.map((v, i) => [i * stepX, h - (v/maxV) * (h - 20)]);
  const path = pts.map((p, i) => (i===0 ? 'M' : 'L') + p[0] + ' ' + p[1]).join(' ');
  const fill = path + ` L ${w} ${h} L 0 ${h} Z`;

  return (
    <div style={{width:'100%'}}>
      <svg viewBox={`0 0 ${w} ${h+20}`} width="100%" height="220">
        <defs>
          <linearGradient id="chartGrad" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor={c.primary} stopOpacity="0.22"/>
            <stop offset="100%" stopColor={c.primary} stopOpacity="0"/>
          </linearGradient>
        </defs>
        {[0, 1, 2, 3].map(i => (
          <line key={i} x1="0" x2={w} y1={h * i / 3} y2={h * i / 3} stroke={c.lineSoft} strokeDasharray="3 4"/>
        ))}
        <path d={fill} fill="url(#chartGrad)"/>
        <path d={path} fill="none" stroke={c.primary} strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"/>
        {pts.map((p, i) => (
          <g key={i}>
            <circle cx={p[0]} cy={p[1]} r="4" fill={c.paper} stroke={c.primary} strokeWidth="2"/>
            <text x={p[0]} y={h + 16} textAnchor="middle" fontSize="10" fill={c.inkMuted}>W{i+1}</text>
          </g>
        ))}
      </svg>
    </div>
  );
};

// === PAGE 8: Neighbors Management ===
const AdminNeighborsPage = () => {
  const c = useTokens();
  const D = window.HAOLIN_DATA;
  const [selected, setSelected] = useState(null);
  const [statusFilter, setStatusFilter] = useState('all');
  const [search, setSearch] = useState('');

  const rows = D.groups.map((g, i) => ({
    ...g,
    status: ['活躍','活躍','活躍','支持中','活躍','已開團','活躍','休眠'][i],
  }));
  const filtered = rows.filter(r => {
    if (statusFilter !== 'all' && r.status !== statusFilter) return false;
    if (search && !r.name.includes(search)) return false;
    return true;
  });

  return (
    <div style={{padding:'32px 40px', background:c.bg, minHeight:'100vh', display:'flex', gap:0}}>
      <div style={{flex:1}}>
        <div style={{display:'flex', justifyContent:'space-between', alignItems:'flex-end', marginBottom:24}}>
          <div>
            <h1 style={{fontFamily:'var(--hl-font-heading)', fontSize:30, color:c.ink, margin:0, fontWeight:500}}>好鄰居管理</h1>
            <p style={{color:c.inkSoft, fontSize:14, margin:'6px 0 0'}}>共 {rows.length} 個團體 · {rows.filter(r=>r.status==='活躍').length} 個活躍</p>
          </div>
          <Button size="sm"><IconPlus size={14}/> 新增團體</Button>
        </div>

        <div style={{display:'flex', gap:10, marginBottom:16, alignItems:'center', flexWrap:'wrap'}}>
          <div style={{flex:1, maxWidth:320}}>
            <Input placeholder="搜尋團名或主揪" icon={<IconSearch size={15}/>} value={search} onChange={e=>setSearch(e.target.value)}/>
          </div>
          <FilterChip active={statusFilter==='all'} onClick={()=>setStatusFilter('all')}>全部</FilterChip>
          {['支持中','已開團','活躍','休眠'].map(s => (
            <FilterChip key={s} active={statusFilter===s} onClick={()=>setStatusFilter(statusFilter===s?'all':s)}>{s}</FilterChip>
          ))}
        </div>

        <Card padding={false} style={{overflow:'hidden'}}>
          <table style={{width:'100%', borderCollapse:'collapse', fontFamily:'var(--hl-font-body)'}}>
            <thead>
              <tr style={{background:c.bgAlt, textAlign:'left', fontSize:12, color:c.inkMuted, letterSpacing:'0.05em'}}>
                <th style={{padding:'14px 20px', fontWeight:600}}>團名 / 主揪</th>
                <th style={{padding:'14px 20px', fontWeight:600}}>狀態</th>
                <th style={{padding:'14px 20px', fontWeight:600}}>主題</th>
                <th style={{padding:'14px 20px', fontWeight:600}}>地區</th>
                <th style={{padding:'14px 20px', fontWeight:600}}>最近活動</th>
                <th style={{padding:'14px 20px'}}/>
              </tr>
            </thead>
            <tbody>
              {filtered.map((r, i) => (
                <tr
                  key={r.id}
                  onClick={()=>setSelected(r)}
                  style={{
                    borderTop: `1px solid ${c.lineSoft}`,
                    cursor:'pointer',
                    background: selected?.id === r.id ? c.bgAlt : 'transparent',
                    transition:'background 120ms',
                  }}
                  onMouseEnter={e=>{ if (selected?.id!==r.id) e.currentTarget.style.background = c.bgSoft }}
                  onMouseLeave={e=>{ if (selected?.id!==r.id) e.currentTarget.style.background = 'transparent' }}
                >
                  <td style={{padding:'14px 20px', fontSize:14}}>
                    <div style={{display:'flex', alignItems:'center', gap:12}}>
                      <AvatarGeo size={32} seed={r.id.charCodeAt(1)}/>
                      <div>
                        <div style={{fontWeight:600, color:c.ink}}>{r.name}</div>
                        <div style={{fontSize:12, color:c.inkMuted, marginTop:1}}>主揪 {r.host.name}</div>
                      </div>
                    </div>
                  </td>
                  <td style={{padding:'14px 20px'}}><StatusBadge status={r.status}/></td>
                  <td style={{padding:'14px 20px', fontSize:13, color:c.inkSoft}}>{D.categories.find(c=>c.key===r.cat).label}</td>
                  <td style={{padding:'14px 20px', fontSize:13, color:c.inkSoft}}>{r.region}</td>
                  <td style={{padding:'14px 20px', fontSize:13, color:c.inkSoft}}>{r.next.split(' ')[0]}</td>
                  <td style={{padding:'14px 20px', textAlign:'right'}}><IconChevronR size={14} stroke={c.inkMuted}/></td>
                </tr>
              ))}
            </tbody>
          </table>
        </Card>
      </div>

      {/* Side drawer */}
      {selected && (
        <div style={{width:360, marginLeft:20, flexShrink:0, position:'sticky', top:32, height:'calc(100vh - 64px)', overflowY:'auto'}}>
          <Card>
            <div style={{display:'flex', justifyContent:'space-between', alignItems:'flex-start', marginBottom:16}}>
              <div style={{display:'flex', gap:12, alignItems:'center'}}>
                <AvatarGeo size={48} seed={selected.id.charCodeAt(1)}/>
                <div>
                  <div style={{fontFamily:'var(--hl-font-heading)', fontSize:18, color:c.ink, fontWeight:500}}>{selected.name}</div>
                  <div style={{fontSize:12, color:c.inkMuted}}>主揪 {selected.host.name}</div>
                </div>
              </div>
              <button onClick={()=>setSelected(null)} style={{background:'none', border:'none', cursor:'pointer', color:c.inkMuted}}><IconX size={16}/></button>
            </div>
            <Divider style={{margin:'8px 0 16px'}}/>
            <div style={{display:'flex', flexDirection:'column', gap:14}}>
              <DetailLine label="狀態" value={<StatusBadge status={selected.status}/>}/>
              <DetailLine label="成立" value={selected.stats.since}/>
              <DetailLine label="活動次數" value={`${selected.stats.events} 次`}/>
              <DetailLine label="成員" value={`${selected.stats.members} 人`}/>
              <DetailLine label="費用" value={selected.fee}/>
              <DetailLine label="形式" value={selected.form}/>
            </div>
            <Divider style={{margin:'20px 0 16px'}}/>
            <div style={{fontSize:12, color:c.inkMuted, marginBottom:8}}>標籤</div>
            <div style={{display:'flex', gap:6, flexWrap:'wrap'}}>
              {selected.tags.map(t => <Tag key={t}>{t}</Tag>)}
            </div>
            <div style={{display:'flex', gap:8, marginTop:20}}>
              <Button variant="primary" size="sm" style={{flex:1}}><IconEdit size={14}/> 編輯</Button>
              <Button variant="secondary" size="sm"><IconChat size={14}/></Button>
            </div>
          </Card>
        </div>
      )}
    </div>
  );
};

const DetailLine = ({ label, value }) => {
  const c = useTokens();
  return (
    <div style={{display:'flex', justifyContent:'space-between', alignItems:'center'}}>
      <span style={{fontSize:12, color:c.inkMuted}}>{label}</span>
      <span style={{fontSize:13, color:c.ink, fontWeight:500}}>{value}</span>
    </div>
  );
};

// === PAGE 10: Support management (同行者支持管理) ===
const AdminTrainingPage = () => {
  const c = useTokens();
  const D = window.HAOLIN_DATA;
  const [filter, setFilter] = useState('all'); // all / signup / training / certified
  const [contactFilter, setContactFilter] = useState('all');
  const [topicFilter, setTopicFilter] = useState('all');
  const [search, setSearch] = useState('');
  const [selected, setSelected] = useState(null);

  const stageMap = {
    signup:    { label:'剛加入',  status:'報名中' },
    training:  { label:'支持中',  status:'支持中' },
    certified: { label:'已開團',  status:'已開團' },
    active:    { label:'已開團',  status:'活躍' },
  };
  const filters = [
    { key:'all',       label:'全部',   count: D.trainees.length },
    { key:'signup',    label:'剛加入', count: D.trainees.filter(t=>t.stage==='signup').length },
    { key:'training',  label:'支持中', count: D.trainees.filter(t=>t.stage==='training').length },
    { key:'certified', label:'已開團', count: D.trainees.filter(t=>t.stage==='certified'||t.stage==='active').length },
  ];

  const filtered = D.trainees.filter(t => {
    if (filter === 'certified') { if (!(t.stage==='certified'||t.stage==='active')) return false; }
    else if (filter !== 'all' && t.stage !== filter) return false;
    if (contactFilter !== 'all' && t.contact !== contactFilter) return false;
    if (topicFilter !== 'all' && t.topic !== topicFilter) return false;
    if (search && !t.name.includes(search)) return false;
    return true;
  });

  return (
    <div style={{padding:'32px 40px', background:c.bg, minHeight:'100vh'}}>
      {/* Header */}
      <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}}>我們陪著 42 位好鄰居</h1>
          <p style={{color:c.inkSoft, fontSize:14, margin:0}}>沒有線性時程表——每個人在六個面向上被接住的節奏不同。</p>
        </div>
        <Button size="sm"><IconPlus size={14}/> 新增新夥伴</Button>
      </div>

      {/* Segmented filter */}
      <div style={{display:'flex', gap:6, marginBottom:20, background:c.paper, padding:6, borderRadius:'var(--hl-radius-lg)', border:`1px solid ${c.line}`, width:'fit-content'}}>
        {filters.map(f => (
          <button key={f.key} onClick={()=>setFilter(f.key)} style={{
            padding:'8px 16px', border:'none', background: filter===f.key ? c.primary : 'transparent',
            color: filter===f.key ? '#fff' : c.inkSoft, borderRadius:'var(--hl-radius-md)',
            fontSize:14, fontWeight: filter===f.key ? 600 : 500, cursor:'pointer',
            display:'flex', alignItems:'center', gap:8, fontFamily:'var(--hl-font-body)',
          }}>
            {f.label}
            <span style={{fontSize:12, padding:'1px 8px', borderRadius:999,
              background: filter===f.key ? 'rgba(255,255,255,0.22)' : c.bgAlt,
              color: filter===f.key ? '#fff' : c.inkMuted,
            }}>{f.count}</span>
          </button>
        ))}
      </div>

      {/* Secondary filters */}
      <div style={{display:'flex', gap:10, alignItems:'center', marginBottom:24, flexWrap:'wrap'}}>
        <div style={{flex:1, minWidth:220, maxWidth:320}}>
          <Input placeholder="搜尋夥伴名字" icon={<IconSearch size={15}/>} value={search} onChange={e=>setSearch(e.target.value)}/>
        </div>
        <SelectChip label="對接人" value={contactFilter} options={[['all','全部'],['小好','小好'],['阿麗','阿麗']]} onChange={setContactFilter}/>
        <SelectChip label="主題" value={topicFilter} options={[['all','全部'],['育兒','育兒'],['喘息','喘息'],['讀書','讀書'],['職場','職場'],['靈性','靈性'],['共學','共學'],['農耕','農耕']]} onChange={setTopicFilter}/>
      </div>

      {/* Card grid */}
      <div style={{display:'grid', gridTemplateColumns:'repeat(auto-fill, minmax(280px, 1fr))', gap:16}}>
        {filtered.map((t, i) => (
          <SupportCard key={t.name} t={t} stageMap={stageMap} onClick={()=>setSelected(t)} tone={i%2===0 ? 'accent' : 'info'}/>
        ))}
        {filtered.length === 0 && (
          <div style={{gridColumn:'1/-1', padding:'60px 20px', textAlign:'center', color:c.inkMuted, fontSize:14}}>
            目前沒有符合條件的夥伴
          </div>
        )}
      </div>

      {/* Drawer */}
      {selected && <SupportDrawer t={selected} stageMap={stageMap} onClose={()=>setSelected(null)}/>}
    </div>
  );
};

const SelectChip = ({ label, value, options, onChange }) => {
  const c = useTokens();
  return (
    <label style={{display:'inline-flex', alignItems:'center', gap:8, padding:'8px 14px',
      background:c.paper, border:`1px solid ${c.line}`, borderRadius:'var(--hl-radius-md)',
      fontSize:13, color:c.inkSoft, cursor:'pointer'}}>
      <span>{label}</span>
      <select value={value} onChange={e=>onChange(e.target.value)} style={{
        border:'none', background:'transparent', fontSize:13, fontFamily:'var(--hl-font-body)',
        color:c.ink, fontWeight:500, outline:'none', cursor:'pointer',
      }}>
        {options.map(([v, l]) => <option key={v} value={v}>{l}</option>)}
      </select>
    </label>
  );
};

const SupportCard = ({ t, stageMap, onClick, tone }) => {
  const c = useTokens();
  const [hover, setHover] = useState(false);
  const stage = stageMap[t.stage];
  return (
    <div
      onClick={onClick}
      onMouseEnter={()=>setHover(true)} onMouseLeave={()=>setHover(false)}
      style={{
        background: c.paper, border:`1px solid ${hover ? c.primary+'60' : c.line}`,
        borderRadius:'var(--hl-radius-xl)', padding:'20px 22px 18px',
        cursor:'pointer',
        boxShadow: hover ? '0 12px 30px rgba(80,50,25,0.10)' : '0 1px 2px rgba(64,40,20,0.04)',
        transition:'box-shadow 180ms, border-color 180ms, transform 180ms',
        transform: hover ? 'translateY(-2px)' : 'none',
        position:'relative',
      }}>
      {/* Header row */}
      <div style={{display:'flex', gap:12, alignItems:'flex-start', marginBottom:14}}>
        <AvatarGeo size={44} seed={t.name.charCodeAt(0)+t.name.charCodeAt(1)}/>
        <div style={{flex:1, minWidth:0}}>
          <div style={{fontSize:15, fontWeight:600, color:c.ink, marginBottom:2}}>{t.name}</div>
          <div style={{fontSize:11, color:c.inkMuted}}>加入於 {t.joinedAt} · {t.topic}</div>
        </div>
        <StatusBadge status={stage.status}/>
      </div>

      {/* Radar mini + memo */}
      <div style={{display:'flex', gap:14, alignItems:'center'}}>
        <div style={{flexShrink:0}}>
          <RadarChart scores={t.scores} size={84} labels={false} tone={tone}/>
        </div>
        <div style={{flex:1, minWidth:0, fontSize:12, lineHeight:1.6, color:c.inkSoft}}>
          {t.memo.length > 52 ? t.memo.slice(0, 50) + '…' : t.memo}
        </div>
      </div>

      {/* Footer row */}
      <div style={{display:'flex', alignItems:'center', justifyContent:'space-between', marginTop:14, paddingTop:12, borderTop:`1px dashed ${c.lineSoft}`}}>
        <div style={{display:'flex', alignItems:'center', gap:8, fontSize:11, color:c.inkMuted}}>
          <AvatarGeo size={22} seed={t.contact.charCodeAt(0)*3}/>
          <span>對接人 <strong style={{color:c.inkSoft, fontWeight:500}}>{t.contact}</strong></span>
        </div>
        <span style={{fontSize:11, color: hover ? c.primary : c.inkMuted, fontWeight:500}}>
          {hover ? '查看支持紀錄 →' : `${t.resources.length} 筆連結資源`}
        </span>
      </div>
    </div>
  );
};

const SupportDrawer = ({ t, stageMap, onClose }) => {
  const c = useTokens();
  const [hoverFacet, setHoverFacet] = useState(null);
  const stage = stageMap[t.stage];
  const byFacet = {};
  SUPPORT_FACETS.forEach(f => { byFacet[f.key] = t.resources.filter(r => r.facet === f.key); });

  return (
    <div onClick={onClose} style={{
      position:'fixed', inset:0, background:'rgba(30, 20, 10, 0.4)',
      zIndex:60, display:'flex', justifyContent:'flex-end',
      animation:'haolin-fade-in 160ms ease',
    }}>
      <div onClick={e=>e.stopPropagation()} style={{
        width:620, maxWidth:'92vw', height:'100vh', overflowY:'auto',
        background: c.bg, boxShadow:'-20px 0 60px rgba(40,20,10,0.2)',
        padding:'28px 32px', animation:'haolin-slide-in 260ms ease',
      }}>
        {/* Header */}
        <div style={{display:'flex', justifyContent:'space-between', alignItems:'flex-start', marginBottom:20}}>
          <div style={{display:'flex', gap:14, alignItems:'center'}}>
            <AvatarGeo size={54} seed={t.name.charCodeAt(0)+t.name.charCodeAt(1)}/>
            <div>
              <div style={{fontFamily:'var(--hl-font-heading)', fontSize:22, color:c.ink, fontWeight:500, lineHeight:1.2}}>{t.name}</div>
              <div style={{fontSize:12, color:c.inkMuted, marginTop:4}}>加入於 {t.joinedAt} · 主題 {t.topic} · 對接人 {t.contact}</div>
              <div style={{marginTop:8}}><StatusBadge status={stage.status}/></div>
            </div>
          </div>
          <button onClick={onClose} style={{background:'none',border:'none',cursor:'pointer',color:c.inkMuted,padding:6}}>
            <IconX size={18}/>
          </button>
        </div>

        {/* Big radar */}
        <Card style={{padding:'20px 24px', marginBottom:18}}>
          <div style={{display:'flex', gap:20, alignItems:'center'}}>
            <div style={{flexShrink:0}}>
              <RadarChart scores={t.scores} size={230} tone="accent" interactive onFacetHover={setHoverFacet}/>
            </div>
            <div style={{flex:1, minWidth:0}}>
              <div style={{fontSize:12, color:c.inkMuted, marginBottom:6}}>六面向支持雷達</div>
              <div style={{fontSize:13, color:c.inkSoft, lineHeight:1.7, marginBottom:14}}>
                每軸 0–3 分代表目前被接住的程度。滑鼠移到軸上可看對應已連結資源。
              </div>
              <Button variant="secondary" size="sm" style={{marginRight:8}}><IconEdit size={13}/> 調整分數</Button>
              <Button size="sm"><IconPlus size={13}/> 新增連結資源</Button>
            </div>
          </div>
        </Card>

        {/* Per-facet resources */}
        <div style={{fontSize:13, color:c.inkMuted, letterSpacing:'0.05em', marginBottom:10, fontWeight:600}}>已連結資源</div>
        <div style={{display:'flex', flexDirection:'column', gap:10, marginBottom:22}}>
          {SUPPORT_FACETS.map(f => {
            const items = byFacet[f.key];
            const score = t.scores[f.key] || 0;
            const highlighted = hoverFacet === f.key;
            return (
              <div key={f.key} style={{
                background: highlighted ? f.bg : c.paper,
                border:`1px solid ${highlighted ? f.color+'40' : c.line}`,
                borderRadius:'var(--hl-radius-md)', padding:'12px 16px',
                transition:'background 160ms, border-color 160ms',
              }}>
                <div style={{display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom: items.length ? 8 : 0}}>
                  <div style={{display:'flex', alignItems:'center', gap:10}}>
                    <div style={{width:8, height:8, borderRadius:'50%', background:f.color}}/>
                    <span style={{fontSize:14, fontWeight:600, color:c.ink}}>{f.label}</span>
                    <span style={{fontSize:11, color:c.inkMuted}}>({score}/3)</span>
                  </div>
                  {items.length === 0 && <span style={{fontSize:11, color:c.inkMuted}}>尚未連結</span>}
                </div>
                {items.length > 0 && (
                  <div style={{display:'flex', flexDirection:'column', gap:6, marginLeft:18}}>
                    {items.map((r, i) => (
                      <div key={i} style={{fontSize:13, color:c.inkSoft, display:'flex', alignItems:'center', gap:6}}>
                        <IconCheck size={12} stroke={f.color}/>
                        {r.title}
                      </div>
                    ))}
                  </div>
                )}
              </div>
            );
          })}
        </div>

        {/* Memo */}
        <div style={{fontSize:13, color:c.inkMuted, letterSpacing:'0.05em', marginBottom:8, fontWeight:600}}>最新需求備忘</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.7, marginBottom:18}}>
          {t.memo}
        </div>

        <div style={{display:'flex', gap:10}}>
          <Button variant="secondary" style={{flex:1}}><IconChat size={14}/> 聯絡 {t.name}</Button>
          <Button variant="primary" style={{flex:1}}><IconEdit size={14}/> 編輯同行計畫</Button>
        </div>
      </div>
    </div>
  );
};

// === PAGE 12: Support Resource Map (支持資源地圖) ===
const AdminSupportMapPage = () => {
  const c = useTokens();
  const D = window.HAOLIN_DATA;
  const res = D.supportResources;
  const [expanded, setExpanded] = useState(null);

  const totalResources = SUPPORT_FACETS.reduce((s, f) => s + res[f.key].length, 0);

  return (
    <div style={{padding:'32px 40px', background:c.bg, minHeight:'100vh'}}>
      {/* Header */}
      <div style={{display:'flex', justifyContent:'space-between', alignItems:'flex-end', marginBottom:8}}>
        <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, lineHeight:1.7, maxWidth:620}}>
            支持是一張網。這裡是協會目前有的 {totalResources} 項資源，分成六個面向——誰需要、我們就遞過去。
          </p>
        </div>
        <Button size="sm"><IconPlus size={14}/> 新增資源</Button>
      </div>

      {/* Intro callout */}
      <div style={{
        background: c.paper, border:`1px solid ${c.line}`, borderRadius:'var(--hl-radius-xl)',
        padding:'20px 24px', margin:'24px 0 28px',
        display:'grid', gridTemplateColumns:'200px 1fr', gap:28, alignItems:'center',
      }}>
        <RadarChart scores={{marketing:3,admin:3,ai:3,emotional:3,peer:3,spirit:3}} size={180} tone="accent"/>
        <div>
          <div style={{fontSize:13, color:c.inkMuted, marginBottom:6, letterSpacing:'0.05em', fontWeight:600}}>支持的六個面向</div>
          <div style={{fontFamily:'var(--hl-font-heading)', fontSize:20, color:c.ink, fontWeight:500, lineHeight:1.5, marginBottom:10}}>
            行銷、行政、AI、情感、同儕、靈性。
          </div>
          <div style={{fontSize:13, color:c.inkSoft, lineHeight:1.8}}>
            每一位好鄰居在這六個面向上被接住的情況不一樣。我們不要求大家都走同一條路——而是根據每個人缺的那塊，把對應的資源遞過去。
          </div>
        </div>
      </div>

      {/* Facet grid */}
      <div style={{display:'grid', gridTemplateColumns:'repeat(3, 1fr)', gap:16}}>
        {SUPPORT_FACETS.map(f => {
          const items = res[f.key];
          const isOpen = expanded === f.key;
          return (
            <div key={f.key} style={{
              background: c.paper, border:`1px solid ${c.line}`,
              borderRadius:'var(--hl-radius-xl)', overflow:'hidden',
              transition:'box-shadow 200ms', boxShadow: isOpen ? '0 14px 32px rgba(80,50,25,0.10)' : '0 1px 2px rgba(64,40,20,0.04)',
            }}>
              {/* Facet header */}
              <div style={{padding:'20px 22px 18px', background: f.bg, borderBottom:`1px solid ${f.soft}`}}>
                <div style={{display:'flex', alignItems:'center', gap:12, marginBottom:8}}>
                  <div style={{width:42, height:42, borderRadius:'var(--hl-radius-md)', background:f.color, display:'flex', alignItems:'center', justifyContent:'center'}}>
                    <FacetGlyph kind={f.key}/>
                  </div>
                  <div>
                    <div style={{fontSize:11, color:f.color, letterSpacing:'0.1em', fontWeight:600}}>FACET · {f.short}</div>
                    <div style={{fontFamily:'var(--hl-font-heading)', fontSize:19, color:c.ink, fontWeight:500, marginTop:2}}>{f.label}</div>
                  </div>
                </div>
                <div style={{fontSize:12, color:c.inkSoft, lineHeight:1.6}}>
                  {{
                    marketing:'幫好鄰居把團的事講清楚、傳出去。',
                    admin:'把活動前後的雜事一次搞定。',
                    ai:'用 AI 把重複的事情自動化。',
                    emotional:'讓好鄰居自己也有人接住。',
                    peer:'讓彼此不再孤立開團。',
                    spirit:'讓服事的人，也被滋養。',
                  }[f.key]}
                </div>
              </div>

              {/* Resource list */}
              <div style={{padding:'12px 8px'}}>
                {items.slice(0, isOpen ? items.length : 3).map((r, i) => (
                  <div key={i} style={{
                    display:'flex', alignItems:'flex-start', gap:10,
                    padding:'10px 14px', borderRadius:'var(--hl-radius-md)',
                    cursor:'pointer',
                  }}
                  onMouseEnter={e=>e.currentTarget.style.background=c.bgAlt}
                  onMouseLeave={e=>e.currentTarget.style.background='transparent'}
                  >
                    <div style={{width:6, height:6, borderRadius:'50%', background:f.color, marginTop:7, flexShrink:0}}/>
                    <div style={{flex:1, minWidth:0}}>
                      <div style={{fontSize:13, fontWeight:600, color:c.ink, lineHeight:1.45}}>{r.title}</div>
                      <div style={{fontSize:11, color:c.inkMuted, marginTop:3}}>
                        <span style={{background:c.bgAlt, padding:'1px 7px', borderRadius:999, marginRight:6}}>{r.type}</span>
                        給 {r.audience}
                      </div>
                    </div>
                  </div>
                ))}
                {items.length > 3 && (
                  <button onClick={()=>setExpanded(isOpen ? null : f.key)} style={{
                    width:'100%', padding:'10px 14px', marginTop:4,
                    background:'transparent', border:'none', cursor:'pointer',
                    fontSize:12, color:f.color, fontWeight:600, fontFamily:'var(--hl-font-body)',
                    display:'flex', alignItems:'center', justifyContent:'center', gap:4,
                  }}>
                    {isOpen ? '收起' : `看完整 ${items.length} 項`} <IconChevronR size={11} style={{transform: isOpen ? 'rotate(90deg)' : 'none'}}/>
                  </button>
                )}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
};

const FacetGlyph = ({ kind }) => {
  const common = { fill:'none', stroke:'#fff', strokeWidth:1.8, strokeLinecap:'round', strokeLinejoin:'round' };
  const paths = {
    marketing: <><path {...common} d="M6 9v6l10 4V5L6 9z"/><path {...common} d="M6 9H4v6h2"/><path {...common} d="M16 8v8"/></>,
    admin:     <><rect x="7" y="4" width="10" height="16" rx="1.5" {...common}/><path {...common} d="M10 9h4M10 13h4M10 17h2"/></>,
    ai:        <><path {...common} d="M12 3v3M12 18v3M3 12h3M18 12h3M5.6 5.6l2.1 2.1M16.3 16.3l2.1 2.1M5.6 18.4l2.1-2.1M16.3 7.7l2.1-2.1"/><circle cx="12" cy="12" r="3" {...common}/></>,
    emotional: <><path {...common} d="M12 20s-6-4-6-9a3.5 3.5 0 0 1 6-2.3A3.5 3.5 0 0 1 18 11c0 5-6 9-6 9z"/></>,
    peer:      <><circle cx="9" cy="10" r="3" {...common}/><circle cx="16" cy="10" r="3" {...common}/><path {...common} d="M4 19c1-3 3-4 5-4M12 19c1-3 3-4 4-4"/></>,
    spirit:    <><path {...common} d="M12 4c-3 0-5 2-5 5s2 5 5 8c3-3 5-5 5-8s-2-5-5-5zM12 9v4M10 11h4"/></>,
  };
  return <svg width="22" height="22" viewBox="0 0 24 24">{paths[kind]}</svg>;
};

Object.assign(window, { AdminDashPage, AdminNeighborsPage, AdminTrainingPage, AdminSupportMapPage });
