/* match-room.jsx — Party room detail (with Discord invite handoff) + Start-a-team (发车) */
const DR = window.DM;

/* ============================================================ DISCORD INVITE HANDOFF CARD
   Answers the user's question: the in-client "Game Invitation" embed is Discord-only,
   but Match mirrors it — a room can post the same join card + the in-game lobby code,
   and (when the Deman bot is wired) drop the real Discord invite straight into the channel. */
function DiscordHandoff({ p, en }){
  const g = DR.GAMES[p.game];
  return (
    <div className="card" style={{ overflow:'hidden' }}>
      <div style={{ padding:'13px 16px', display:'flex', alignItems:'center', gap:9, borderBottom:'1px solid var(--line-soft)' }}>
        <Discord w={18} />
        <span style={{ fontFamily:'var(--hud)', fontWeight:700, fontSize:13 }}>{en?'Discord handoff':'Discord 互通'}</span>
        <span className="status online" style={{ marginLeft:'auto' }}><span className="dot"/>{en?'Synced':'已同步'}</span>
      </div>
      {/* mirrors the native Discord game-invitation embed */}
      <div style={{ padding:16 }}>
        <div style={{ borderRadius:'var(--r-sm)', overflow:'hidden', border:'1px solid var(--line)' }}>
          <div style={{ height:96, background:g.grad, position:'relative' }}>
            <div className="gridfx" style={{ opacity:.4, mask:'none' }} />
            <span style={{ position:'absolute', left:12, bottom:10, fontFamily:'var(--display)', fontStyle:'italic', fontWeight:900, fontSize:30, color:'#fff', letterSpacing:'-.03em', textShadow:'0 2px 12px rgba(0,0,0,.4)' }}>{g.short}</span>
          </div>
          <div style={{ padding:'12px 14px', display:'flex', alignItems:'center', gap:12 }}>
            <div style={{ flex:1, minWidth:0 }}>
              <div style={{ fontFamily:'var(--mono)', fontSize:10, color:'var(--text-mute)', letterSpacing:'.1em', textTransform:'uppercase' }}>{en?'Game Invitation':'游戏邀请'}</div>
              <div style={{ fontFamily:'var(--cn)', fontWeight:800, fontSize:15, marginTop:2 }}>{DR.gName(p.game)}</div>
              <div style={{ fontFamily:'var(--mono)', fontSize:11, color:'var(--text-dim)', marginTop:3 }}>{DR.modeName(p.game,p.mode)} · {teamLabel(p)} {en?'playing':'在房'}</div>
            </div>
            <button className="btn btn-go btn-sm" onClick={()=>window.dmToast && window.dmToast(en?'Joining the Discord voice channel…':'正在加入 Discord 语音频道…')}>{en?'Join':'加入'}</button>
          </div>
        </div>
        <div style={{ display:'flex', gap:8, marginTop:12, flexWrap:'wrap' }}>
          <button className="chip" style={{ cursor:'pointer' }} onClick={()=>window.dmToast && window.dmToast(en?'In-game lobby code copied · DEMAN-'+p.id.toUpperCase():'游戏房间码已复制 · DEMAN-'+p.id.toUpperCase())}>
            <Ic k="link" w={13}/> {en?'Copy lobby code':'复制游戏房间码'}
          </button>
          <button className="chip" style={{ cursor:'pointer' }} onClick={()=>window.dmToast && window.dmToast(en?'Discord invite link copied':'Discord 邀请链接已复制')}>
            <Discord w={13}/> {en?'Discord invite':'Discord 邀请链接'}
          </button>
        </div>
        <p style={{ fontFamily:'var(--cn)', fontSize:11.5, color:'var(--text-mute)', marginTop:12, lineHeight:1.6 }}>
          {en?'The same join card posts to your Discord channel automatically — web and Discord members land in one voice room.'
             :'同一张上车卡片会自动发到你绑定的 Discord 频道,网页和频道里的人进同一个语音房间。'}
        </p>
      </div>
    </div>
  );
}

/* ============================================================ ROOM DETAIL */
function RoomView({ p, en, onBack, onApply, t }){
  const g = DR.GAMES[p.game];
  const urgent = p.urgent || needCount(p)===1;
  const host = p.members[0];
  return (
    <div className="wrap" style={{ padding:'24px 26px 70px', maxWidth:1080 }}>
      <button className="chip" style={{ cursor:'pointer', marginBottom:18 }} onClick={onBack}><Ic k="back" w={14}/> {en?'Back to wall':'返回车队墙'}</button>

      <div style={{ display:'grid', gridTemplateColumns:'1.6fr 1fr', gap:22, alignItems:'start' }}>
        {/* main */}
        <div style={{ display:'flex', flexDirection:'column', gap:18 }}>
          <div className="card" style={{ overflow:'hidden' }}>
            <div style={{ height:120, background:g.grad, position:'relative', display:'flex', alignItems:'flex-end', padding:18 }}>
              <div className="gridfx" style={{ opacity:.4, mask:'none' }} />
              <div style={{ position:'relative', display:'flex', alignItems:'center', gap:13 }}>
                <GameGlyph game={p.game} size={52} />
                <div>
                  <div style={{ fontFamily:'var(--cn)', fontWeight:900, fontSize:22, color:'#fff', letterSpacing:'-.02em', textShadow:'0 2px 12px rgba(0,0,0,.4)' }}>
                    {DR.gName(p.game)} · {DR.modeName(p.game,p.mode)}
                  </div>
                  <div style={{ display:'flex', gap:8, marginTop:7 }}>
                    <RankTag game={p.game} rank={p.rank} />
                    <VibeTag vibe={p.vibe} en={en} />
                  </div>
                </div>
                {urgent && <span className="chip" style={{ marginLeft:8, color:'var(--q-coral)', borderColor:'color-mix(in oklab,var(--q-coral) 45%,transparent)', background:'oklch(0 0 0 /.3)' }}><Ic k="fire" w={13}/>{en?'1 slot left':'就差一个'}</span>}
              </div>
            </div>
            <div style={{ padding:18 }}>
              <div style={{ display:'flex', alignItems:'center', gap:9, marginBottom:16 }}>
                <span style={{ fontFamily:'var(--mono)', fontSize:11, color:'var(--text-mute)' }}>{en?"HOST'S CALL":'车主原话'}</span>
                <span style={{ height:1, background:'var(--line-soft)', flex:1 }} />
              </div>
              <div style={{ fontFamily:'var(--cn)', fontSize:15, color:'var(--text)', background:'var(--surface-2)', border:'1px solid var(--line-soft)', borderRadius:'var(--r-sm)', padding:'12px 14px', display:'flex', gap:9, alignItems:'center' }}>
                <span style={{ fontFamily:'var(--mono)', color:'var(--text-mute)' }}>#</span>{p.note}
              </div>

              <div style={{ marginTop:20, fontFamily:'var(--mono)', fontSize:11, color:'var(--text-mute)', marginBottom:14 }}>
                {en?'ROSTER':'车队阵容'} · {teamLabel(p)}
              </div>
              <div style={{ display:'flex', flexWrap:'wrap', gap:18 }}>
                <SlotRow party={p} size={52} en={en} />
              </div>
            </div>
          </div>
        </div>

        {/* side */}
        <div style={{ display:'flex', flexDirection:'column', gap:18, position:'sticky', top:90 }}>
          <div className="card" style={{ padding:18 }}>
            <div style={{ display:'flex', alignItems:'center', gap:11, marginBottom:14 }}>
              <Av name={host.name} size={46} dot="online" />
              <div>
                <div style={{ fontFamily:'var(--cn)', fontWeight:800, fontSize:15, display:'flex', alignItems:'center', gap:6 }}>
                  {host.name} <Ic k="crown" w={14} style={{ color:'var(--rk-chal)' }} />
                </div>
                <div style={{ fontFamily:'var(--mono)', fontSize:11, color:'var(--text-mute)' }}>{en?'Host':'车主'} · {DR.rankName(p.game,host.rank)}</div>
              </div>
            </div>
            <div style={{ display:'flex', gap:8, marginBottom:14 }}>
              {p.voice ? <span className="chip" style={{ color:'var(--ok)', borderColor:'color-mix(in oklab,var(--ok) 35%,transparent)' }}><Ic k="mic" w={13}/>{en?'Mic on':'开麦'}</span>
                       : <span className="chip"><Ic k="micOff" w={13}/>{en?'No mic':'静音'}</span>}
              <span className="chip"><Ic k="clock" w={13}/>{ago(p.age,en)}</span>
            </div>
            <button className={'btn btn-block '+(urgent?'btn-coral':'btn-go')} onClick={()=>onApply(p)}>
              <Ic k="bolt" w={16}/> {needCount(p)===1?(en?'Take the last seat':'抢最后一个位置'):(en?'Apply to join':'申请上车')}
            </button>
            <p style={{ fontFamily:'var(--cn)', fontSize:11.5, color:'var(--text-mute)', marginTop:11, textAlign:'center', lineHeight:1.6 }}>
              {en?'Host gets pinged instantly. Avg accept: 18s.':'车主会立刻收到提醒,平均 18 秒内通过。'}
            </p>
          </div>

          <DiscordHandoff p={p} en={en} />
        </div>
      </div>
    </div>
  );
}

/* ============================================================ START A TEAM (发车) */
function StartView({ en, onBack, onCreate }){
  const [game, setGame] = useState('lol');
  const g = DR.GAMES[game];
  const [mode, setMode] = useState('flex');
  const [rank, setRank] = useState(DR.ME.ranks[game] || 'gold');
  const [myLane, setMyLane] = useState('mid');
  const [have, setHave] = useState(2);
  const [needLanes, setNeedLanes] = useState(['fill','fill']);
  const [voice, setVoice] = useState(true);
  const [vibe, setVibe] = useState('comp');
  const [note, setNote] = useState('');

  useEffect(()=>{ setMode(g.modes[0].key); setRank(DR.ME.ranks[game]||'gold'); setMyLane(g.lanes[0].key); },[game]);

  const size = (DR.modeObj(game,mode)||{}).size || g.size || 5;
  const needN = Math.max(0, size - have);
  useEffect(()=>{ setNeedLanes(Array.from({length:needN}, (_,i)=> needLanes[i]||'fill')); },[have, mode]);

  // live slang preview
  const preview = DR.parseSlang(note);

  function setLane(i, v){ setNeedLanes(ls=> ls.map((x,j)=> j===i?v:x)); }
  function submit(){
    const members=[{ name:DR.ME.name.split(' ')[0], rank:DR.ME.ranks[game]||rank, lane:myLane, pres:'online' }];
    for(let i=1;i<have;i++) members.push(DR.mk(['Tom','Leo','小鱼','阿布','果冻'][i-1]||'Player', rank, g.lanes[Math.min(i,g.lanes.length-1)].key));
    onCreate({ id:'new'+Date.now(), game, mode, region:'na', rank, vibe, voice, age:0, note: note|| (DR.isEn()?'':`${DR.rankName(game,rank)}${DR.modeName(game,mode)} ${have}=${needN}`), members, needLanes, hot:true, mine:true });
  }

  const Field = ({ label, children }) => (
    <div style={{ display:'flex', flexDirection:'column', gap:9 }}>
      <label style={{ fontFamily:'var(--mono)', fontSize:11, letterSpacing:'.1em', textTransform:'uppercase', color:'var(--text-mute)' }}>{label}</label>
      {children}
    </div>
  );
  const Opt = ({ on, onClick, children }) => (
    <button onClick={onClick} className={'chip'+(on?' on':'')} style={{ cursor:'pointer', fontSize:13, padding:'8px 13px' }}>{children}</button>
  );

  return (
    <div className="wrap" style={{ padding:'24px 26px 70px', maxWidth:900 }}>
      <button className="chip" style={{ cursor:'pointer', marginBottom:18 }} onClick={onBack}><Ic k="back" w={14}/> {en?'Back':'返回'}</button>
      <span className="eyebrow">{en?'START A TEAM':'发车'}</span>
      <h2 className="h2" style={{ marginTop:10, marginBottom:6 }}>{en?'Open a car, let players come to you':'开一辆车,等人来上'}</h2>
      <p className="lede" style={{ fontSize:14, marginBottom:26 }}>{en?'Set it once. We push it to the wall, the smart queue, and your Discord channel at the same time.':'填一次,就同时挂上车队墙、智能匹配池、和你的 Discord 频道。'}</p>

      <div className="card" style={{ padding:24, display:'flex', flexDirection:'column', gap:22 }}>
        <Field label={en?'Game':'游戏'}>
          <div style={{ display:'flex', gap:8, flexWrap:'wrap' }}>
            {DR.GAME_ORDER.map(k=> <Opt key={k} on={k===game} onClick={()=>setGame(k)}><GameGlyph game={k} size={18} r="5px"/>{DR.gName(k)}</Opt>)}
          </div>
        </Field>

        <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:22 }}>
          <Field label={en?'Mode':'模式'}>
            <div style={{ display:'flex', gap:7, flexWrap:'wrap' }}>
              {g.modes.map(m=> <Opt key={m.key} on={m.key===mode} onClick={()=>setMode(m.key)}>{en?m.en:m.cn}</Opt>)}
            </div>
          </Field>
          <Field label={en?'Rank':'段位'}>
            <div style={{ display:'flex', gap:7, flexWrap:'wrap' }}>
              {g.tiers.map(rk=> <Opt key={rk} on={rk===rank} onClick={()=>setRank(rk)}>{DR.rankName(game,rk)}</Opt>)}
            </div>
          </Field>
        </div>

        <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:22 }}>
          <Field label={en?'Your position':'你打什么位置'}>
            <div style={{ display:'flex', gap:7, flexWrap:'wrap' }}>
              {g.lanes.map(l=> <Opt key={l.key} on={l.key===myLane} onClick={()=>setMyLane(l.key)}>{en?l.en:l.cn}</Opt>)}
            </div>
          </Field>
          <Field label={en?'Already in team':'车上已有几人'}>
            <div style={{ display:'flex', alignItems:'center', gap:14 }}>
              <button className="btn btn-ghost btn-sm" onClick={()=>setHave(h=>Math.max(1,h-1))} style={{ width:40 }}>−</button>
              <span style={{ fontFamily:'var(--display)', fontStyle:'italic', fontWeight:800, fontSize:30 }}>{have}<span style={{ fontSize:16, color:'var(--text-mute)' }}>/{size}</span></span>
              <button className="btn btn-ghost btn-sm" onClick={()=>setHave(h=>Math.min(size-1,h+1))} style={{ width:40 }}>+</button>
              <span style={{ fontFamily:'var(--mono)', fontSize:12, color:'var(--q-amber)', marginLeft:6 }}>{en?`need ${needN}`:`缺 ${needN}`}</span>
            </div>
          </Field>
        </div>

        {needN>0 && (
          <Field label={en?'Positions you need':'你缺哪些位置'}>
            <div style={{ display:'flex', flexDirection:'column', gap:10 }}>
              {needLanes.map((nl,i)=>(
                <div key={i} style={{ display:'flex', gap:7, flexWrap:'wrap', alignItems:'center' }}>
                  <span style={{ fontFamily:'var(--mono)', fontSize:11, color:'var(--text-mute)', width:46 }}>#{i+1}</span>
                  {g.lanes.map(l=> <Opt key={l.key} on={l.key===nl} onClick={()=>setLane(i,l.key)}>{en?l.en:l.cn}</Opt>)}
                </div>
              ))}
            </div>
          </Field>
        )}

        <div style={{ display:'flex', gap:22, flexWrap:'wrap' }}>
          <Field label={en?'Voice':'语音'}>
            <div style={{ display:'flex', gap:7 }}>
              <Opt on={voice} onClick={()=>setVoice(true)}><Ic k="mic" w={13}/>{en?'Mic on':'开麦'}</Opt>
              <Opt on={!voice} onClick={()=>setVoice(false)}><Ic k="micOff" w={13}/>{en?'No mic':'静音'}</Opt>
            </div>
          </Field>
          <Field label={en?'Vibe':'氛围'}>
            <div style={{ display:'flex', gap:7 }}>
              <Opt on={vibe==='comp'} onClick={()=>setVibe('comp')}>{en?'Ranked':'认真上分'}</Opt>
              <Opt on={vibe==='fun'} onClick={()=>setVibe('fun')}>{en?'For fun':'娱乐局'}</Opt>
            </div>
          </Field>
        </div>

        <Field label={en?'Quick note (old-school slang works)':'一句话招人(支持暗语速记)'}>
          <input value={note} onChange={e=>setNote(e.target.value)} placeholder={en?'e.g. diamond flex 4=1 mid mic':'例如:钻石flex 4=1 中单 开麦'}
            style={{ fontFamily:'var(--cn)', fontSize:14, padding:'12px 14px', borderRadius:'var(--r-sm)', border:'1.5px solid var(--line)', background:'var(--surface-2)', color:'var(--text)', outline:'none' }} />
          {preview.ok && (
            <div style={{ display:'flex', gap:7, flexWrap:'wrap', alignItems:'center', fontFamily:'var(--mono)', fontSize:11, color:'var(--text-mute)' }}>
              <Ic k="spark" w={13} style={{ color:'var(--q-lime)' }}/> {en?'parsed →':'解析为 →'}
              {preview.rank && <RankTag game={game} rank={preview.rank} sm />}
              {preview.mode && <span className="chip" style={{ padding:'3px 8px', fontSize:11 }}>{DR.modeName(game,preview.mode)}</span>}
              {preview.need!=null && <span className="chip" style={{ padding:'3px 8px', fontSize:11, color:'var(--q-amber)' }}>{en?`need ${preview.need}`:`缺 ${preview.need}`}</span>}
              {preview.lanes.map(l=> <span key={l} className="chip" style={{ padding:'3px 8px', fontSize:11 }}>{DR.laneName(game,l)}</span>)}
            </div>
          )}
        </Field>

        <button className="btn btn-go btn-lg" onClick={submit} style={{ alignSelf:'flex-start' }}>
          <Ic k="bolt" w={17}/> {en?'Open the car':'发车,开始招人'}
        </button>
      </div>
    </div>
  );
}

Object.assign(window, { RoomView, StartView });
