// Page 2: Group List  + Page 3: Group Detail

const GroupsListPage = ({ onNav, initialCat }) => {
  const c = useTokens();
  const isMobile = useIsMobile();
  const D = window.HAOLIN_DATA;
  const [cat, setCat] = useState(initialCat || null);
  const [region, setRegion] = useState(null);
  const [form, setForm] = useState(null);
  const [fee, setFee] = useState(null);
  const [search, setSearch] = useState('');
  const [filtersOpen, setFiltersOpen] = useState(false);

  const filtered = D.groups.filter(g => {
    if (cat && g.cat !== cat) return false;
    if (region && !g.region.includes(region)) return false;
    if (form && !g.form.includes(form)) return false;
    if (fee === 'free' && g.fee !== '免費') return false;
    if (fee === 'paid' && g.fee === '免費') return false;
    if (search && !g.name.includes(search) && !g.tagline.includes(search)) return false;
    return true;
  });

  const clearAll = () => { setCat(null); setRegion(null); setForm(null); setFee(null); setSearch(''); };

  const filterCount = [cat, region, form, fee, search].filter(Boolean).length;

  return (
    <div style={{background: c.bg, minHeight:'100vh'}}>
      <div style={{maxWidth:1240, margin:'0 auto', padding: isMobile ? '24px 16px' : '48px 32px'}}>
        <div style={{marginBottom: isMobile ? 20 : 32}}>
          <h1 style={{fontFamily:'var(--hl-font-heading)', fontSize: isMobile ? 28 : 42, fontWeight:500, color:c.ink, margin:'0 0 10px'}}>找個好鄰居團</h1>
          <p style={{fontSize: isMobile ? 14 : 16, color:c.inkSoft, margin:0, lineHeight:1.7}}>目前有 {filtered.length} 個團體符合你的條件。不想自己找？<span style={{color:c.primary, cursor:'pointer', fontWeight:600}} onClick={()=>onNav('match')}>讓 AI 幫你媒合 →</span></p>
        </div>

        {isMobile && (
          <button onClick={()=>setFiltersOpen(o=>!o)} style={{
            width:'100%', padding:'12px 16px', marginBottom:16,
            background: c.paper, border:`1px solid ${c.line}`,
            borderRadius:'var(--hl-radius-md)',
            display:'flex', alignItems:'center', justifyContent:'space-between',
            fontSize:14, color:c.ink, cursor:'pointer',
            fontFamily:'var(--hl-font-body)', fontWeight:500,
          }}>
            <span>篩選條件{filterCount > 0 ? ` · ${filterCount} 項` : ''}</span>
            <span style={{color:c.inkMuted}}>{filtersOpen ? '收起 ▲' : '展開 ▼'}</span>
          </button>
        )}

        <div style={{display:'grid', gridTemplateColumns: isMobile ? '1fr' : '260px 1fr', gap: isMobile ? 16 : 32, alignItems:'flex-start'}}>
          {/* SIDEBAR FILTERS */}
          {(!isMobile || filtersOpen) && (
          <aside style={{position: isMobile ? 'static' : 'sticky', top: isMobile ? undefined : 80}}>
            <div style={{background:c.paper, border:`1px solid ${c.line}`, borderRadius:'var(--hl-radius-xl)', padding: isMobile ? '16px 16px 18px' : '20px 20px 24px'}}>
              <div style={{display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:16}}>
                <h3 style={{fontSize:15, fontWeight:600, color:c.ink, margin:0}}>篩選條件</h3>
                {(cat||region||form||fee||search) && <button onClick={clearAll} style={{fontSize:12, color:c.primary, background:'none', border:'none', cursor:'pointer'}}>清除</button>}
              </div>
              <Input placeholder="搜尋團名或描述" icon={<IconSearch size={16}/>} value={search} onChange={e=>setSearch(e.target.value)} containerStyle={{marginBottom:20}}/>
              <FilterGroup title="主題">
                {D.categories.map(ct => (
                  <FilterChip key={ct.key} active={cat===ct.key} onClick={()=>setCat(cat===ct.key?null:ct.key)}>{ct.label}</FilterChip>
                ))}
              </FilterGroup>
              <FilterGroup title="地區">
                {['台北市','新北市','桃園市','宜蘭縣','線上'].map(r => (
                  <FilterChip key={r} active={region===r} onClick={()=>setRegion(region===r?null:r)}>{r}</FilterChip>
                ))}
              </FilterGroup>
              <FilterGroup title="形式">
                {['實體','線上'].map(f => (
                  <FilterChip key={f} active={form===f} onClick={()=>setForm(form===f?null:f)}>{f}</FilterChip>
                ))}
              </FilterGroup>
              <FilterGroup title="費用">
                <FilterChip active={fee==='free'} onClick={()=>setFee(fee==='free'?null:'free')}>免費</FilterChip>
                <FilterChip active={fee==='paid'} onClick={()=>setFee(fee==='paid'?null:'paid')}>付費</FilterChip>
              </FilterGroup>
            </div>
          </aside>
          )}

          {/* GRID */}
          <div>
            {filtered.length === 0 ? (
              <div style={{textAlign:'center', padding:'80px 20px', background:c.paper, borderRadius:'var(--hl-radius-xl)', border:`1px solid ${c.line}`}}>
                <EmptyIllustration size={140}/>
                <h3 style={{fontFamily:'var(--hl-font-heading)', fontSize:20, margin:'16px 0 8px', color:c.ink}}>沒有符合的團體</h3>
                <p style={{color:c.inkSoft, margin:'0 0 20px', fontSize:14}}>試試 AI 媒合，描述你要什麼，讓系統幫你找。</p>
                <Button onClick={()=>onNav('match')}>讓 AI 幫我找</Button>
              </div>
            ) : (
              <div style={{display:'grid', gridTemplateColumns:'repeat(auto-fill, minmax(280px, 1fr))', gap:20}}>
                {filtered.map(g => <GroupCard key={g.id} group={g} onClick={()=>onNav('group-detail', g.id)}/>)}
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
};

const FilterGroup = ({ title, children }) => {
  const c = useTokens();
  return (
    <div style={{marginBottom:16}}>
      <div style={{fontSize:12, fontWeight:600, color:c.inkMuted, marginBottom:8, letterSpacing:'0.08em'}}>{title}</div>
      <div style={{display:'flex', flexWrap:'wrap', gap:6}}>{children}</div>
    </div>
  );
};

const FilterChip = ({ children, active, onClick }) => {
  const c = useTokens();
  return (
    <button onClick={onClick} style={{
      padding:'5px 12px', borderRadius:'999px',
      background: active ? c.primary : c.bgAlt,
      color: active ? '#fff' : c.inkSoft,
      fontSize:13, border:'none', cursor:'pointer',
      fontFamily:'var(--hl-font-body)', fontWeight: active ? 600 : 500,
      whiteSpace:'nowrap', flexShrink:0,
      transition:'all 140ms ease',
    }}>{children}</button>
  );
};

// === GROUP DETAIL ===
const GroupDetailPage = ({ onNav, groupId }) => {
  const c = useTokens();
  const isMobile = useIsMobile();
  const D = window.HAOLIN_DATA;
  const g = D.groups.find(x => x.id === groupId) || D.groups[0];
  const cat = D.categories.find(x => x.key === g.cat);
  const related = D.groups.filter(x => x.cat === g.cat && x.id !== g.id).slice(0, 3);

  return (
    <div style={{background: c.bg, minHeight:'100vh', paddingBottom: isMobile ? 60 : 120}}>
      {/* COVER */}
      <div style={{height: isMobile ? 200 : 320, position:'relative', background: cat.color + '30'}}>
        <PhotoPlaceholder width={1400} height={isMobile ? 200 : 320} label={`${g.name} 活動照片`} src={g.cover}/>
        <div style={{position:'absolute', inset:0, background: `linear-gradient(180deg, transparent 40%, ${c.bg})`}}/>
      </div>

      <div style={{maxWidth:1100, margin: isMobile ? '-50px auto 0' : '-80px auto 0', padding: isMobile ? '0 16px' : '0 32px', position:'relative'}}>
        <div style={{
          background:c.paper, borderRadius:'var(--hl-radius-2xl)',
          padding: isMobile ? '20px 22px' : '32px 40px',
          border:`1px solid ${c.line}`,
          boxShadow:'0 16px 40px rgba(80,50,25,0.08)',
          display:'flex',
          flexDirection: isMobile ? 'column' : 'row',
          gap: isMobile ? 14 : 24,
          alignItems: isMobile ? 'flex-start' : 'flex-start',
        }}>
          <AvatarGeo size={isMobile ? 56 : 72} seed={g.id.charCodeAt(1)}/>
          <div style={{flex:1, minWidth:0, width:'100%'}}>
            <div style={{display:'flex', gap:8, marginBottom:10, flexWrap:'wrap'}}>
              <Tag tone="primary">{cat.label}</Tag>
              {g.tags.map(t => <Tag key={t}>{t}</Tag>)}
            </div>
            <h1 style={{fontFamily:'var(--hl-font-heading)', fontSize: isMobile ? 24 : 34, fontWeight:500, color:c.ink, margin:'0 0 8px', lineHeight:1.3}}>{g.name}</h1>
            <p style={{fontSize: isMobile ? 14 : 16, color:c.inkSoft, margin:0, lineHeight:1.7}}>{g.tagline}</p>
            <div style={{display:'flex', gap: isMobile ? 12 : 20, marginTop:14, fontSize:13, color:c.inkMuted, flexWrap:'wrap'}}>
              <span style={{display:'inline-flex', gap:4, alignItems:'center'}}><IconUser size={14}/> 主揪 {g.host.name}</span>
              <span style={{display:'inline-flex', gap:4, alignItems:'center'}}><IconPin size={14}/> {g.region}</span>
              <span style={{display:'inline-flex', gap:4, alignItems:'center'}}><IconClock size={14}/> 自 {g.stats.since}</span>
            </div>
          </div>
          <Button onClick={()=>{}} size={isMobile ? 'sm' : 'md'} style={isMobile ? {alignSelf:'stretch'} : {}}><IconHeart size={16}/> 收藏</Button>
        </div>

        <div style={{display:'grid', gridTemplateColumns: isMobile ? '1fr' : '1.5fr 1fr', gap: isMobile ? 20 : 32, marginTop: isMobile ? 24 : 40}}>
          {/* LEFT: about */}
          <div style={{display:'flex', flexDirection:'column', gap:28}}>
            <Card>
              <h3 style={{fontFamily:'var(--hl-font-heading)', fontSize:20, color:c.ink, margin:'0 0 14px', fontWeight:500}}>關於這個團</h3>
              <p style={{fontSize:15, lineHeight:1.85, color:c.inkSoft, margin:0}}>
                {g.name}是一個由{g.host.name}帶著的{cat.label}團。{g.host.bio}
                每次聚會都是 8~12 人的規模，沒有報到、沒有簽名，就是一群住得不遠的人願意每週（或每個月）在同一個時間出現。
              </p>
              <p style={{fontSize:15, lineHeight:1.85, color:c.inkSoft, margin:'12px 0 0'}}>
                我們不是一個「課程」，比較像一個會自己長的小社群。願意一起出現就好，不會要求你做什麼。
              </p>
            </Card>

            <Card>
              <h3 style={{fontFamily:'var(--hl-font-heading)', fontSize:20, color:c.ink, margin:'0 0 16px', fontWeight:500}}>近期活動</h3>
              <div style={{display:'flex', flexDirection:'column', gap:0}}>
                {['溪邊植物散步 第 43 次','清明連假親子小旅行','三月家長共讀：〈小王子〉','二月植樹活動'].map((t, i) => (
                  <div key={i} style={{display:'flex', gap:16, padding:'14px 0', borderBottom: i<3 ? `1px dashed ${c.line}` : 'none'}}>
                    <div style={{width:64, textAlign:'right', fontSize:13, color:c.inkMuted, paddingTop:2}}>{['4/19','4/5','3/22','3/8'][i]}</div>
                    <div style={{width:1, background:c.line, position:'relative'}}>
                      <div style={{position:'absolute', left:-4, top:6, width:9, height:9, borderRadius:'50%', background:c.primary}}/>
                    </div>
                    <div style={{flex:1}}>
                      <div style={{fontSize:15, fontWeight:600, color:c.ink}}>{t}</div>
                      <div style={{fontSize:13, color:c.inkSoft, marginTop:2}}>{[12,8,10,15][i]} 人參加 · 特派員已報導</div>
                    </div>
                  </div>
                ))}
              </div>
            </Card>

            <Card>
              <h3 style={{fontFamily:'var(--hl-font-heading)', fontSize:20, color:c.ink, margin:'0 0 14px', fontWeight:500}}>相關報導</h3>
              <div style={{display:'flex', flexDirection:'column', gap:12}}>
                {D.articles.filter(a => a.group === g.name || a.cat === cat.label).slice(0,2).map(a => (
                  <div key={a.id} onClick={()=>onNav('article', a.id)} style={{padding:14, background:c.bgAlt, borderRadius:'var(--hl-radius-md)', cursor:'pointer', display:'flex', gap:14, alignItems:'center'}}>
                    <div style={{width:60, height:60, borderRadius:'var(--hl-radius-sm)', overflow:'hidden', flexShrink:0}}>
                      <PhotoPlaceholder width={60} height={60} label=""/>
                    </div>
                    <div style={{flex:1}}>
                      <div style={{fontSize:14, fontWeight:600, color:c.ink}}>{a.title}</div>
                      <div style={{fontSize:12, color:c.inkMuted, marginTop:4}}>{a.date} · {a.read}</div>
                    </div>
                    <IconArrow size={16} stroke={c.inkMuted}/>
                  </div>
                ))}
              </div>
            </Card>
          </div>

          {/* RIGHT: info panel */}
          <div style={{display:'flex', flexDirection:'column', gap:20, position: isMobile ? 'static' : 'sticky', top: isMobile ? undefined : 80, alignSelf:'flex-start'}}>
            <Card>
              <div style={{display:'flex', flexDirection:'column', gap:14}}>
                <InfoRow icon={<IconCalendar size={16}/>} label="活動時段" value={g.schedule}/>
                <InfoRow icon={<IconClock size={16}/>} label="下次活動" value={g.next}/>
                <InfoRow icon={<IconHeartHands size={16}/>} label="費用" value={g.fee}/>
                <InfoRow icon={<IconPin size={16}/>} label="地點" value={g.region}/>
                <InfoRow icon={<IconUsers size={16}/>} label="規模" value={`${g.stats.members} 人・${g.stats.events} 次活動`}/>
              </div>
            </Card>

            <Card style={{background: c.ink, color:'#fff', border:'none'}}>
              <h4 style={{fontFamily:'var(--hl-font-heading)', fontSize:18, margin:'0 0 8px', fontWeight:500, color:'#fff'}}>主揪 {g.host.name}</h4>
              <p style={{fontSize:13, color:'#C8B9A8', lineHeight:1.7, margin:'0 0 16px'}}>{g.host.bio}</p>
              <Button variant="primary" style={{width:'100%'}} icon={<IconChat size={16}/>}>聯絡主揪</Button>
              <Button variant="ghost" style={{width:'100%', color:'#C8B9A8', marginTop:8}} onClick={()=>onNav('groups')}>找類似的團體</Button>
            </Card>
          </div>
        </div>

        {/* RELATED */}
        {related.length > 0 && <div style={{marginTop: isMobile ? 32 : 56}}>
          <h3 style={{fontFamily:'var(--hl-font-heading)', fontSize: isMobile ? 19 : 22, color:c.ink, marginBottom: isMobile ? 14 : 20, fontWeight:500}}>類似的團體</h3>
          <div style={{display:'grid', gridTemplateColumns: isMobile ? '1fr' : 'repeat(3, 1fr)', gap: isMobile ? 14 : 20}}>
            {related.map(r => <GroupCard key={r.id} group={r} onClick={()=>onNav('group-detail', r.id)}/>)}
          </div>
        </div>}
      </div>
    </div>
  );
};

const InfoRow = ({ icon, label, value }) => {
  const c = useTokens();
  return (
    <div style={{display:'flex', gap:12, alignItems:'flex-start'}}>
      <span style={{color:c.primary, paddingTop:2}}>{icon}</span>
      <div style={{flex:1}}>
        <div style={{fontSize:12, color:c.inkMuted}}>{label}</div>
        <div style={{fontSize:14, color:c.ink, fontWeight:500, marginTop:2}}>{value}</div>
      </div>
    </div>
  );
};

Object.assign(window, { GroupsListPage, GroupDetailPage });
