/* match-wall.jsx — Live team wall (3 layouts) + Room detail + Start-a-team */
const DW = window.DM;

/* ============================================================ FILTER BAR */
function WallFilters({ game, setGame, filters, setFilters, en, count, layout, setLayout }){
  const g = DW.GAMES[game];
  function toggle(grp, val){
    setFilters(f => {
      const cur = new Set(f[grp]); cur.has(val)?cur.delete(val):cur.add(val);
      return { ...f, [grp]:cur };
    });
  }
  return (
    <div style={{ display:'flex', flexDirection:'column', gap:14 }}>
      {/* game tabs */}
      <div style={{ display:'flex', gap:8, flexWrap:'wrap', alignItems:'center' }}>
        {DW.GAME_ORDER.map(k=>{
          const on = k===game;
          return (
            <button key={k} onClick={()=>setGame(k)} className="chip" style={{
              cursor:'pointer', padding:'7px 13px', gap:8,
              background: on?'color-mix(in oklab,'+DW.GAMES[k].accent+' 16%,transparent)':'var(--surface)',
              borderColor: on?'color-mix(in oklab,'+DW.GAMES[k].accent+' 50%,transparent)':'var(--line)',
              color: on?'var(--text)':'var(--text-dim)' }}>
              <GameGlyph game={k} size={20} r="5px" />
              {DW.gName(k)}
            </button>
          );
        })}
      </div>

      {/* mode + filters row */}
      <div style={{ display:'flex', gap:10, flexWrap:'wrap', alignItems:'center' }}>
        <div style={{ display:'flex', gap:6, flexWrap:'wrap' }}>
          {g.modes.map(m=>{
            const on = filters.mode.has(m.key);
            return <button key={m.key} onClick={()=>toggle('mode',m.key)} className={'chip'+(on?' on':'')}
              style={{ cursor:'pointer' }}>{en?m.en:m.cn}</button>;
          })}
        </div>
        <div style={{ width:1, height:22, background:'var(--line)', margin:'0 2px' }} />
        <button onClick={()=>setFilters(f=>({...f, voice:!f.voice}))} className={'chip'+(filters.voice?' on':'')} style={{ cursor:'pointer' }}>
          <Ic k="mic" w={13} /> {en?'Mic on':'开麦'}
        </button>
        <button onClick={()=>setFilters(f=>({...f, urgent:!f.urgent}))} className={'chip'+(filters.urgent?' on':'')} style={{ cursor:'pointer' }}>
          <Ic k="fire" w={13} /> {en?'1 slot left':'就差一个'}
        </button>
        <button onClick={()=>setFilters(f=>({...f, myrank:!f.myrank}))} className={'chip'+(filters.myrank?' on':'')} style={{ cursor:'pointer' }}>
          <Ic k="shield" w={13} /> {en?'My rank ±1':'我的段位 ±1'}
        </button>

        <div style={{ marginLeft:'auto', display:'flex', gap:10, alignItems:'center' }}>
          <span style={{ fontFamily:'var(--mono)', fontSize:12, color:'var(--text-mute)' }}>
            <b style={{ color:'var(--text)', fontSize:14 }}>{count}</b> {en?'live teams':'个车队在线'}
          </span>
          <div style={{ display:'inline-flex', border:'1.5px solid var(--line)', borderRadius:'var(--r-sm)', overflow:'hidden' }}>
            {[['cards','cards'],['rows','rows'],['lanes','lanes']].map(([k,icon])=>(
              <button key={k} onClick={()=>setLayout(k)} title={k} style={{
                width:34, height:32, display:'grid', placeItems:'center', border:'none', cursor:'pointer',
                background: layout===k?'var(--surface-3)':'transparent', color: layout===k?'var(--v-bright)':'var(--text-mute)' }}>
                <Ic k={icon} w={15} />
              </button>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

/* ============================================================ filtering logic */
function filterParties(parties, game, filters){
  const myRank = DW.ME.ranks[game];
  const tiers = DW.GAMES[game].tiers;
  const myIdx = tiers.indexOf(myRank);
  return parties.filter(p=>{
    if(p.game!==game) return false;
    if(filters.mode.size && !filters.mode.has(p.mode)) return false;
    if(filters.voice && !p.voice) return false;
    if(filters.urgent && !(p.urgent || needCount(p)===1)) return false;
    if(filters.myrank && myIdx>=0){ const pi=tiers.indexOf(p.rank); if(Math.abs(pi-myIdx)>1) return false; }
    return true;
  }).sort((a,b)=> (b.hot?1:0)-(a.hot?1:0) || a.age-b.age );
}

/* ============================================================ VARIATION 1 — CARD GRID */
function PartyCard({ p, en, onOpen, density }){
  const g = DW.GAMES[p.game];
  const urgent = p.urgent || needCount(p)===1;
  return (
    <div className="card" onClick={()=>onOpen(p)} style={{ overflow:'hidden', cursor:'pointer', display:'flex', flexDirection:'column',
      transition:'transform .18s, border-color .18s, box-shadow .18s', position:'relative' }}
      onMouseEnter={e=>{ e.currentTarget.style.transform='translateY(-4px)'; e.currentTarget.style.borderColor='color-mix(in oklab,'+g.accent+' 55%,transparent)'; e.currentTarget.style.boxShadow='var(--shadow)'; }}
      onMouseLeave={e=>{ e.currentTarget.style.transform=''; e.currentTarget.style.borderColor='var(--line)'; e.currentTarget.style.boxShadow=''; }}>
      {/* header band */}
      <div style={{ padding:'13px 16px', display:'flex', alignItems:'center', gap:11, borderBottom:'1px solid var(--line-soft)',
        background:'linear-gradient(180deg, color-mix(in oklab,'+g.accent+' 10%,transparent), transparent)' }}>
        <GameGlyph game={p.game} size={36} />
        <div style={{ minWidth:0, flex:1 }}>
          <div style={{ fontFamily:'var(--hud)', fontWeight:700, fontSize:14, display:'flex', alignItems:'center', gap:7 }}>
            {DW.modeName(p.game,p.mode)} <RankTag game={p.game} rank={p.rank} sm />
          </div>
          <div style={{ fontFamily:'var(--mono)', fontSize:10.5, color:'var(--text-mute)', marginTop:3, display:'flex', gap:8, alignItems:'center' }}>
            <span>{ago(p.age,en)}</span>
            {p.voice ? <span style={{ color:'var(--ok)', display:'inline-flex', alignItems:'center', gap:3 }}><Ic k="mic" w={11}/>{en?'mic':'开麦'}</span>
                     : <span style={{ display:'inline-flex', alignItems:'center', gap:3 }}><Ic k="micOff" w={11}/>{en?'no mic':'静音'}</span>}
          </div>
        </div>
        {p.hot && <span className="chip" style={{ padding:'3px 8px', fontSize:10, color:'var(--q-coral)', borderColor:'color-mix(in oklab,var(--q-coral) 40%,transparent)', background:'color-mix(in oklab,var(--q-coral) 12%,transparent)' }}><Ic k="fire" w={11}/>HOT</span>}
      </div>
      {/* body */}
      <div style={{ padding:'14px 16px', display:'flex', flexDirection:'column', gap:13, flex:1 }}>
        {density!=='compact' && (
          <div style={{ fontFamily:'var(--cn)', fontSize:13, color:'var(--text-dim)', display:'flex', alignItems:'center', gap:7,
            background:'var(--surface-2)', border:'1px solid var(--line-soft)', borderRadius:'var(--r-xs)', padding:'7px 10px' }}>
            <span style={{ fontFamily:'var(--mono)', fontSize:10, color:'var(--text-mute)', flex:'none' }}>#</span>
            <span style={{ overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>{p.note}</span>
          </div>
        )}
        <SlotRow party={p} size={density==='compact'?32:38} en={en} />
        <div style={{ display:'flex', alignItems:'center', gap:10, marginTop:'auto', paddingTop:12, borderTop:'1px solid var(--line-soft)' }}>
          <VibeTag vibe={p.vibe} en={en} />
          <span style={{ fontFamily:'var(--mono)', fontSize:11.5, color:'var(--text-mute)' }}>{teamLabel(p)} {en?'in team':'已组'}</span>
          <button className={'btn btn-sm '+(urgent?'btn-coral':'btn-primary')} style={{ marginLeft:'auto' }} onClick={e=>{ e.stopPropagation(); onOpen(p); }}>
            <Ic k="bolt" w={13}/> {en?'Join':'一键上车'}
          </button>
        </div>
      </div>
    </div>
  );
}

/* ============================================================ VARIATION 2 — CHANNEL ROWS */
function PartyRow({ p, en, onOpen }){
  const g = DW.GAMES[p.game];
  const urgent = p.urgent || needCount(p)===1;
  return (
    <div onClick={()=>onOpen(p)} style={{ display:'flex', alignItems:'center', gap:16, padding:'12px 16px', cursor:'pointer',
      borderBottom:'1px solid var(--line-soft)', transition:'background .15s', borderLeft:'3px solid '+(urgent?'var(--q-coral)':'transparent') }}
      onMouseEnter={e=>e.currentTarget.style.background='var(--surface-2)'}
      onMouseLeave={e=>e.currentTarget.style.background=''}>
      <GameGlyph game={p.game} size={34} r="7px" />
      <div style={{ width:128, flex:'none' }}>
        <div style={{ fontFamily:'var(--hud)', fontWeight:700, fontSize:13.5, display:'flex', alignItems:'center', gap:6 }}>{DW.modeName(p.game,p.mode)}</div>
        <div style={{ marginTop:4 }}><RankTag game={p.game} rank={p.rank} sm /></div>
      </div>
      <div style={{ flex:1, minWidth:0, fontFamily:'var(--mono)', fontSize:12, color:'var(--text-dim)', display:'flex', alignItems:'center', gap:8 }}>
        <span style={{ color:'var(--text-mute)' }}>#</span>
        <span style={{ overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>{p.note}</span>
      </div>
      <div style={{ flex:'none' }}><SlotRow party={p} size={28} showLane={false} en={en} /></div>
      <div style={{ width:70, flex:'none', textAlign:'right' }}><NeedBadge party={p} en={en} /></div>
      <div style={{ width:56, flex:'none', display:'flex', justifyContent:'flex-end', color:'var(--text-mute)' }}>
        {p.voice ? <Ic k="mic" w={15} style={{ color:'var(--ok)' }}/> : <Ic k="micOff" w={15}/>}
      </div>
      <span style={{ width:64, flex:'none', fontFamily:'var(--mono)', fontSize:10.5, color:'var(--text-mute)', textAlign:'right' }}>{ago(p.age,en)}</span>
      <button className={'btn btn-sm '+(urgent?'btn-coral':'btn-primary')} onClick={e=>{ e.stopPropagation(); onOpen(p); }}>{en?'Join':'上车'}</button>
    </div>
  );
}

/* ============================================================ VARIATION 3 — LANE BOARD (kanban by need-count) */
function LaneBoard({ parties, en, onOpen }){
  const cols = [
    { key:1, cn:'就差一个 · 1', en:'1 slot left' },
    { key:2, cn:'差两个 · 2', en:'2 slots' },
    { key:3, cn:'差三个+ · 3+', en:'3+ slots' }
  ];
  return (
    <div style={{ display:'grid', gridTemplateColumns:'repeat(3,1fr)', gap:16, alignItems:'start' }}>
      {cols.map(c=>{
        const list = parties.filter(p=> c.key===3 ? needCount(p)>=3 : needCount(p)===c.key);
        return (
          <div key={c.key} style={{ display:'flex', flexDirection:'column', gap:12 }}>
            <div style={{ display:'flex', alignItems:'center', gap:8, fontFamily:'var(--hud)', fontWeight:700, fontSize:13,
              color: c.key===1?'var(--q-coral)':'var(--text-dim)', padding:'2px 2px 8px', borderBottom:'2px solid '+(c.key===1?'var(--q-coral)':'var(--line)') }}>
              {c.key===1 && <Ic k="fire" w={14}/>}
              {en?c.en:c.cn}
              <span style={{ marginLeft:'auto', fontFamily:'var(--mono)', fontSize:11, color:'var(--text-mute)' }}>{list.length}</span>
            </div>
            {list.map(p=>{
              const g=DW.GAMES[p.game];
              return (
                <div key={p.id} className="card" onClick={()=>onOpen(p)} style={{ padding:12, cursor:'pointer', transition:'.15s' }}
                  onMouseEnter={e=>{ e.currentTarget.style.borderColor='color-mix(in oklab,'+g.accent+' 50%,transparent)'; }}
                  onMouseLeave={e=>{ e.currentTarget.style.borderColor='var(--line)'; }}>
                  <div style={{ display:'flex', alignItems:'center', gap:8, marginBottom:9 }}>
                    <GameGlyph game={p.game} size={26} r="6px" />
                    <span style={{ fontFamily:'var(--hud)', fontWeight:700, fontSize:12.5 }}>{DW.modeName(p.game,p.mode)}</span>
                    <RankTag game={p.game} rank={p.rank} sm />
                  </div>
                  <div style={{ fontFamily:'var(--mono)', fontSize:11, color:'var(--text-mute)', marginBottom:10, overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>{p.note}</div>
                  <SlotRow party={p} size={28} showLane={false} en={en} />
                </div>
              );
            })}
            {!list.length && <div style={{ fontFamily:'var(--mono)', fontSize:11, color:'var(--text-mute)', padding:14, textAlign:'center', border:'1px dashed var(--line)', borderRadius:'var(--r-sm)' }}>{en?'— empty —':'— 暂无 —'}</div>}
          </div>
        );
      })}
    </div>
  );
}

/* ============================================================ THE WALL */
function TeamWall({ en, onOpen, t }){
  const [game, setGame] = useState('lol');
  const [layout, setLayout] = useState(t.wallLayout || 'cards');
  const [filters, setFilters] = useState({ mode:new Set(), voice:false, urgent:false, myrank:false });
  useEffect(()=>{ setLayout(t.wallLayout||'cards'); },[t.wallLayout]);
  const list = useMemo(()=>filterParties(DW.PARTIES, game, filters), [game, filters]);

  return (
    <div className="wrap" style={{ padding:'30px 26px 70px' }}>
      <div style={{ display:'flex', alignItems:'flex-end', justifyContent:'space-between', gap:20, marginBottom:22, flexWrap:'wrap' }}>
        <div>
          <span className="eyebrow">LIVE · NA</span>
          <h2 className="h2" style={{ marginTop:10 }}>{en?'Team Wall':'实时车队墙'}</h2>
          <p className="lede" style={{ marginTop:6, fontSize:14 }}>{en?'Every open car in the channels — sortable, filterable, and you can see the empty seat before you ask.':'频道里所有正在招人的车,一眼看清缺哪个位置,看到就能上,不用再刷消息。'}</p>
        </div>
      </div>

      <WallFilters game={game} setGame={setGame} filters={filters} setFilters={setFilters} en={en} count={list.length} layout={layout} setLayout={setLayout} />

      <div style={{ marginTop:22 }}>
        {layout==='cards' && (
          <div style={{ display:'grid', gridTemplateColumns:'repeat(auto-fill,minmax(330px,1fr))', gap:16 }}>
            {list.map(p=> <PartyCard key={p.id} p={p} en={en} onOpen={onOpen} density={t.density} />)}
          </div>
        )}
        {layout==='rows' && (
          <div className="card" style={{ overflow:'hidden' }}>
            {list.map(p=> <PartyRow key={p.id} p={p} en={en} onOpen={onOpen} />)}
          </div>
        )}
        {layout==='lanes' && <LaneBoard parties={list} en={en} onOpen={onOpen} />}
        {!list.length && <div style={{ padding:60, textAlign:'center', color:'var(--text-mute)', fontFamily:'var(--mono)', fontSize:13 }}>{en?'No teams match — loosen the filters or start your own.':'没有符合的车队 — 放宽筛选,或自己发一辆车。'}</div>}
      </div>
    </div>
  );
}

window.TeamWall = TeamWall;
