/* page-community.jsx — 社区活动集合页 (all AI communities' events) */

function CommunityPage() {
  const db = useKataDB();
  const D = KSITE.community, M = KSITE.pageMeta.community;
  const allEvents = db.events('c');
  const crawled = window.CRAWLED_EVENTS || null;
  /* 城市/类型筛选：有爬取数据时用真实字段；否则用 KSITE 默认列表 */
  const cities = (crawled && crawled.cities && crawled.cities.length) ? crawled.cities : D.cities;
  const types = (crawled && crawled.types && crawled.types.length) ? crawled.types : D.types;
  const [city, setCity] = React.useState('全部');
  const [type, setType] = React.useState('全部');
  const [qy, setQy] = React.useState('');

  /* 解析活动时间用于排序：优先用 ISO / start_date 字段，回退到 e.date 文本 */
  const eventTime = (e) => {
    const raw = e.start_date || e.startDate || e.iso || e.datetime || e.date || '';
    const t = Date.parse(String(raw).replace(/年|月/g, '-').replace(/日/g, '').replace(/\./g, '-'));
    return isNaN(t) ? Infinity : t;
  };

  const list = allEvents.filter((e) =>
    (city === '全部' || e.city === city) &&
    (type === '全部' || e.tag === type) &&
    (qy === '' || (e.title + e.org + (e.desc || '') + (e.location || '')).toLowerCase().includes(qy.toLowerCase())))
    /* 活动日历按活动时间从近到远排序 */
    .sort((a, b) => eventTime(a) - eventTime(b));

  /* 热门策略：从全部活动中随机选若干条标为热门（每次加载固定一次）*/
  const HOT_COUNT = 6;
  const hotSet = React.useMemo(() => {
    const pool = allEvents.map((e, i) => e.id || ('c' + i));
    for (let i = pool.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [pool[i], pool[j]] = [pool[j], pool[i]];
    }
    return new Set(pool.slice(0, HOT_COUNT));
  }, [allEvents.length]);
  const isHot = (e, i) => hotSet.has(e.id || ('c' + i));
  const hotEvents = allEvents.filter((e, i) => isHot(e, i)).slice(0, 5);

  return (
    <React.Fragment>
      <div className="ka-stage">
        <Backdrop particles={5} />
        <div className="kc">
          <header className="pb">
            <span className="eyebrow"><span className="pulse" /> {M.kicker}</span>
            <h1>发现值得参加的<span className="ac">AI 社区活动</span></h1>
            <p>{M.desc}</p>
            <div className="ka-search nm-sink" style={{ marginTop: 30 }}>
              <IcSearch /><input placeholder="搜索活动、社区或主题…" value={qy} onChange={(e) => setQy(e.target.value)} />
            </div>
          </header>
        </div>
      </div>

      <div className="kc">
        <div className="list-head">
          <div className="flt">
            <span className="lbl">城市</span>
            {cities.map((c) => <button key={c} className={'fchip nm-rise-sm' + (city === c ? ' on' : '')} onClick={() => setCity(c)}>{c}</button>)}
          </div>
        </div>
        <div className="flt" style={{ marginBottom: 30 }}>
          <span className="lbl">形式</span>
          {types.map((tp) => <button key={tp} className={'fchip nm-rise-sm' + (type === tp ? ' on' : '')} onClick={() => setType(tp)}>{tp}</button>)}
        </div>
        {crawled && crawled.generated_at && (
          <div className="muted" style={{ margin: '-12px 0 22px', fontSize: 13 }}>
            更新于 {String(crawled.generated_at).slice(0, 19).replace('T', ' ')}
          </div>
        )}

        <div className="ka-cols ka-cols--side-left">
          <div style={{ order: 2 }}>
            <div className="list-head" style={{ marginTop: 0 }}>
              <h2 className="sec-title" style={{ fontSize: 22 }}>活动日历</h2>
              <span className="count">{list.length ? '共 ' + list.length + ' 场 · 按时间排序' : '暂无匹配'}</span>
            </div>
            <div className="elist">
              {list.map((e, i) => (
                <Reveal key={e.id || e.title} delay={i * 60}>
                  <a className="erow nm-rise nm-press" href={'#event/c' + allEvents.indexOf(e)}>
                    <span className="d">{e.date}<span>{e.day} · {e.time}</span></span>
                    <div className="mid">
                      <h3>{e.title}{isHot(e, allEvents.indexOf(e)) && <span className="hot-dot"><span className="pulse" />热门</span>}</h3>
                      <div className="sub">
                        <span className="tbadge nm-sink-sm">{e.tag}</span>
                        <span>{e.org}</span>
                        <span className="mono">{e.mode === '线上' ? '线上' : e.city}</span>
                      </div>
                    </div>
                    <div className="end">
                      <span className="join-link">报名 <Arrow size={13} /></span>
                    </div>
                  </a>
                </Reveal>
              ))}
              {list.length === 0 && <div className="nm-sink" style={{ borderRadius: 20, padding: 40, textAlign: 'center', color: 'var(--ink-faint)' }}>没有符合条件的活动，换个筛选试试～</div>}
            </div>
          </div>

          <aside className="ka-side" style={{ order: 1 }}>
            <div className="side-card nm-rise">
              <h4><span style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}><span className="pulse" />热门活动</span></h4>
              {hotEvents.length === 0 && <div className="muted" style={{ fontSize: 13 }}>暂无热门活动</div>}
              {hotEvents.map((o) => (
                <a key={o.id || o.title} className="org" href={'#event/c' + allEvents.indexOf(o)}>
                  <span className="ava nm-sink-sm">{(o.org || o.title).charAt(0)}</span>
                  <span className="meta"><div className="n">{o.title}</div><div className="s">{o.date} · {o.mode === '线上' ? '线上' : o.city}</div></span>
                  <span className="arrow-dot"><Arrow /></span>
                </a>
              ))}
            </div>
            <div className="side-card nm-rise" style={{ textAlign: 'center' }}>
              <h4 style={{ justifyContent: 'center' }}>提交社区活动</h4>
              <p className="muted" style={{ fontSize: 13.5, lineHeight: 1.6, margin: '0 0 18px' }}>如果你在组织 Meetup、分享会、工作坊或黑客松，欢迎提交到咔嗒Lab，让更多相关的人看见。</p>
              <a href="#submit_event" className="btn btn-accent" style={{ width: '100%', justifyContent: 'center' }}>提交活动 <Arrow /></a>
            </div>
          </aside>
        </div>
      </div>
    </React.Fragment>
  );
}

(window.__KATA_PAGES = window.__KATA_PAGES || {}).community = { Comp: CommunityPage, active: 'community' };
if (!window.__KATA_SPA) {
  ReactDOM.createRoot(document.getElementById('root')).render(
    <KataPage active="community"><CommunityPage /></KataPage>
  );
}
