// Groups screen — quick access to all groups of the current user
const { useState: useState_gs, useMemo: useMemo_gs } = React;

function GroupsScreen({ store, onOpenGroup, onCreateGroup }) {
  const { visibleGroups: groups, visiblePlayers: players, userById, can } = store;
  const [search, setSearch] = useState_gs("");

  const filtered = useMemo_gs(() => {
    if (!search.trim()) return groups;
    const q = search.trim().toLowerCase();
    return groups.filter(g =>
      g.name.toLowerCase().includes(q) ||
      (g.venue || "").toLowerCase().includes(q)
    );
  }, [groups, search]);

  // Split into active (has live matches) and others
  const active = filtered.filter(g => Object.values(g.active || {}).some(Boolean));
  const inactive = filtered.filter(g => !Object.values(g.active || {}).some(Boolean));

  return (
    <div className="page" data-screen-label="Groups">
      <div className="sec-head">
        <div>
          <h2 className="sec-title">ก๊วนของฉัน</h2>
          <div className="sec-sub">{groups.length} ก๊วน</div>
        </div>
        {can.manageGroups && (
          <button className="btn primary sm" onClick={onCreateGroup}>
            <Icon name="plus" size={14} stroke={2.2} /> สร้างก๊วนใหม่
          </button>
        )}
      </div>

      {/* Search */}
      {groups.length > 3 && (
        <div className="card" style={{padding: "10px 14px", marginBottom: 16, display:"flex", alignItems:"center", gap:8}}>
          <Icon name="search" size={15} style={{color:"var(--text-3)", flexShrink:0}} />
          <input
            className="input-inline"
            placeholder="ค้นหาชื่อก๊วน หรือสถานที่…"
            value={search}
            onChange={e => setSearch(e.target.value)}
            style={{flex:1, background:"none", border:"none", outline:"none", fontSize:14}}
          />
          {search && (
            <button className="btn icon" onClick={() => setSearch("")} style={{padding:2}}>
              <Icon name="x" size={13} />
            </button>
          )}
        </div>
      )}

      {/* Active groups */}
      {active.length > 0 && (
        <section>
          <div className="row gap-2 mb-2" style={{alignItems:"center"}}>
            <span style={{width:8, height:8, borderRadius:"50%", background:"var(--green)", display:"inline-block"}} />
            <div className="small" style={{fontWeight:600, color:"var(--text-2)"}}>กำลังเล่นอยู่ ({active.length})</div>
          </div>
          <div className="group-grid">
            {active.map(g => (
              <GroupCard key={g.id} group={g} players={players} userById={userById}
                showOwner={store.isSuper} onOpen={() => onOpenGroup(g.id)} />
            ))}
          </div>
        </section>
      )}

      {/* All other groups */}
      {inactive.length > 0 && (
        <section>
          {active.length > 0 && (
            <div className="row gap-2 mb-2 mt-2" style={{alignItems:"center"}}>
              <span style={{width:8, height:8, borderRadius:"50%", background:"var(--sep)", display:"inline-block"}} />
              <div className="small" style={{fontWeight:600, color:"var(--text-2)"}}>ก๊วนทั้งหมด ({inactive.length})</div>
            </div>
          )}
          <div className="group-grid">
            {inactive.map(g => (
              <GroupCard key={g.id} group={g} players={players} userById={userById}
                showOwner={store.isSuper} onOpen={() => onOpenGroup(g.id)} />
            ))}
          </div>
        </section>
      )}

      {/* Empty states */}
      {filtered.length === 0 && search && (
        <div className="empty">
          <div className="em">🔍</div>
          <div>ไม่พบก๊วนที่ตรงกับ "{search}"</div>
          <button className="btn sm mt-2" onClick={() => setSearch("")}>ล้างการค้นหา</button>
        </div>
      )}
      {groups.length === 0 && (
        <div className="empty">
          <div className="em">🏸</div>
          <div style={{fontWeight:600, marginBottom:6}}>ยังไม่มีก๊วน</div>
          <div className="muted small mb-3">สร้างก๊วนแรกของคุณเพื่อเริ่มจัดคู่</div>
          {can.manageGroups && (
            <button className="btn primary" onClick={onCreateGroup}>
              <Icon name="plus" size={14} stroke={2.2} /> สร้างก๊วนใหม่
            </button>
          )}
        </div>
      )}

      {/* Create card at bottom */}
      {groups.length > 0 && can.manageGroups && (
        <section>
          <button className="group-card" onClick={onCreateGroup}
            style={{display:"grid", placeItems:"center", minHeight:90, border:"1.5px dashed var(--sep)", background:"transparent", cursor:"pointer", borderRadius:"var(--r-lg)"}}>
            <div className="muted small row gap-2">
              <Icon name="plus" size={14} /> สร้างก๊วนใหม่
            </div>
          </button>
        </section>
      )}
    </div>
  );
}

Object.assign(window, { GroupsScreen });
