/* match-me.jsx — Profile + rank/history + Notifications + Discord sync */
const DME = window.DM;

function StatTile({ v, label }){
  return (
    <div style={{ background:'var(--surface-2)', border:'1px solid var(--line-soft)', borderRadius:'var(--r-sm)', padding:'14px 16px', textAlign:'center' }}>
      <div style={{ fontFamily:'var(--display)', fontStyle:'italic', fontWeight:800, fontSize:28, color:'var(--v-bright)', lineHeight:1 }}>{v}</div>
      <div style={{ fontFamily:'var(--mono)', fontSize:10, letterSpacing:'.08em', textTransform:'uppercase', color:'var(--text-mute)', marginTop:6 }}>{label}</div>
    </div>
  );
}

function ProfilePanel({ en }){
  const me = DME.ME;
  return (
    <div style={{ display:'flex', flexDirection:'column', gap:20 }}>
      {/* identity */}
      <div className="card" style={{ overflow:'hidden' }}>
        <div style={{ height:84, background:'linear-gradient(120deg,var(--v-deep),var(--rk-master))', position:'relative' }}><div className="gridfx" style={{ opacity:.4, mask:'none' }}/></div>
        <div style={{ padding:'0 22px 20px', marginTop:-30, display:'flex', alignItems:'flex-end', gap:16, flexWrap:'wrap' }}>
          <Av name={me.name} size={72} ring="var(--surface)" />
          <div style={{ paddingBottom:4 }}>
            <div style={{ fontFamily:'var(--cn)', fontWeight:900, fontSize:22, display:'flex', alignItems:'center', gap:9 }}>
              {me.name}
              {me.discordBound && <span className="chip" style={{ fontSize:10.5, color:'var(--v-bright)', borderColor:'color-mix(in oklab,var(--v-bright) 35%,transparent)' }}><Discord w={12}/>{en?'Linked':'已绑定'}</span>}
            </div>
            <div style={{ fontFamily:'var(--mono)', fontSize:12, color:'var(--text-mute)', marginTop:3 }}>{me.handle} · NA</div>
          </div>
          <button className="btn btn-ghost btn-sm" style={{ marginLeft:'auto', alignSelf:'center' }}>{en?'Edit profile':'编辑资料'}</button>
        </div>
        <div style={{ padding:'0 22px 22px', display:'grid', gridTemplateColumns:'repeat(4,1fr)', gap:12 }}>
          <StatTile v={me.stats.matched} label={en?'Matched':'匹配次数'} />
          <StatTile v={me.stats.winRate+'%'} label={en?'Win rate':'胜率'} />
          <StatTile v={me.stats.avgWait} label={en?'Avg wait':'平均等待'} />
          <StatTile v={me.stats.played.toLocaleString()} label={en?'Games':'总场次'} />
        </div>
      </div>

      {/* ranks per game */}
      <div className="card" style={{ padding:20 }}>
        <div style={{ fontFamily:'var(--mono)', fontSize:11, letterSpacing:'.1em', textTransform:'uppercase', color:'var(--text-mute)', marginBottom:14 }}>{en?'My ranks':'我的段位'}</div>
        <div style={{ display:'flex', gap:12, flexWrap:'wrap' }}>
          {me.games.map(k=>{
            const g = DME.GAMES[k] || DME.GAMES.lol;
            const isLol = k==='lol' || k==='tft';
            const game = k==='tft'?'lol':k;
            const rk = me.ranks[k];
            return (
              <div key={k} style={{ display:'flex', alignItems:'center', gap:12, background:'var(--surface-2)', border:'1px solid var(--line-soft)', borderRadius:'var(--r-sm)', padding:'12px 16px', minWidth:180 }}>
                <GameGlyph game={game} size={38} />
                <div>
                  <div style={{ fontFamily:'var(--cn)', fontWeight:700, fontSize:13.5 }}>{k==='tft'?(en?'TFT':'云顶之弈'):DME.gName(game)}</div>
                  <div style={{ marginTop:5 }}><RankTag game={game} rank={rk} /></div>
                </div>
              </div>
            );
          })}
        </div>
      </div>

      {/* history */}
      <div className="card" style={{ padding:20 }}>
        <div style={{ fontFamily:'var(--mono)', fontSize:11, letterSpacing:'.1em', textTransform:'uppercase', color:'var(--text-mute)', marginBottom:14 }}>{en?'Recent matches':'最近开黑'}</div>
        <div style={{ display:'flex', flexDirection:'column' }}>
          {me.history.map((h,i)=>(
            <div key={i} style={{ display:'flex', alignItems:'center', gap:14, padding:'12px 0', borderBottom: i<me.history.length-1?'1px solid var(--line-soft)':'none' }}>
              <span style={{ width:6, height:34, borderRadius:3, background: h.result==='win'?'var(--q-lime)':'var(--q-coral)', flex:'none' }} />
              <GameGlyph game={h.game} size={32} r="7px" />
              <div style={{ flex:1, minWidth:0 }}>
                <div style={{ fontFamily:'var(--hud)', fontWeight:700, fontSize:13.5, display:'flex', alignItems:'center', gap:7 }}>
                  {DME.modeName(h.game,h.mode)} <RankTag game={h.game} rank={h.rank} sm />
                  <span style={{ fontFamily:'var(--display)', fontStyle:'italic', fontWeight:800, fontSize:13, color: h.result==='win'?'var(--q-lime)':'var(--q-coral)' }}>{h.result==='win'?(en?'WIN':'胜'):(en?'LOSS':'负')}</span>
                </div>
                <div style={{ fontFamily:'var(--mono)', fontSize:11, color:'var(--text-mute)', marginTop:3 }}>{en?'with ':'和 '}{h.with.join(' · ')}</div>
              </div>
              <span style={{ fontFamily:'var(--mono)', fontSize:11, color:'var(--text-mute)' }}>{en?h.agoEn:h.ago}</span>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

function NotifPanel({ en, onOpen }){
  const notifs = [
    { type:'found', icon:'bolt', color:'var(--q-lime)', title:en?'Match found — a Diamond Flex car needs your Mid':'匹配成功 —— 有辆钻石flex车缺你的中单', sub:en?'4=1 · pinged you 12s ago':'4=1 · 12 秒前提醒你', party:DME.PARTIES[0], fresh:true },
    { type:'apply', icon:'users', color:'var(--v-bright)', title:en?'Kira applied to your team':'Kira 申请上你的车', sub:en?'VALORANT Comp · Sentinel':'无畏契约竞技 · 哨兵', fresh:true },
    { type:'urgent', icon:'fire', color:'var(--q-coral)', title:en?'A Master car is down to its last seat':'有辆大师车只剩最后一个位置', sub:en?'Support · matches your queue':'辅助 · 符合你的排队条件', party:DME.PARTIES[4] },
    { type:'discord', icon:null, color:'var(--v-bright)', title:en?'晚风 joined the Discord voice channel':'晚风 加入了 Discord 语音频道', sub:en?'#lol-na-ranked · synced':'#lol-na-ranked · 已同步' },
    { type:'win', icon:'trophy', color:'var(--rk-chal)', title:en?'GG — your Flex car won. +18 LP':'GG —— 你的flex车赢了。+18 LP', sub:en?'2h ago':'2 小时前' }
  ];
  return (
    <div className="card" style={{ overflow:'hidden' }}>
      <div style={{ padding:'16px 20px', borderBottom:'1px solid var(--line-soft)', display:'flex', alignItems:'center', gap:9 }}>
        <Ic k="bell" w={16}/><span style={{ fontFamily:'var(--hud)', fontWeight:700, fontSize:14 }}>{en?'Notifications':'通知与提醒'}</span>
        <span className="chip" style={{ marginLeft:'auto', fontSize:10.5, color:'var(--q-coral)', borderColor:'color-mix(in oklab,var(--q-coral) 40%,transparent)' }}>2 {en?'new':'条新'}</span>
      </div>
      {notifs.map((n,i)=>(
        <div key={i} onClick={()=> n.party && onOpen(n.party)} style={{ padding:'14px 20px', display:'flex', gap:13, alignItems:'center', borderBottom: i<notifs.length-1?'1px solid var(--line-soft)':'none',
          cursor: n.party?'pointer':'default', background: n.fresh?'color-mix(in oklab,'+n.color+' 7%,transparent)':'transparent', transition:'.15s' }}
          onMouseEnter={e=>{ if(n.party) e.currentTarget.style.background='var(--surface-2)'; }}
          onMouseLeave={e=>{ e.currentTarget.style.background = n.fresh?'color-mix(in oklab,'+n.color+' 7%,transparent)':'transparent'; }}>
          <span style={{ width:38, height:38, borderRadius:'var(--r-xs)', flex:'none', display:'grid', placeItems:'center', color:n.color,
            background:`color-mix(in oklab,${n.color} 14%,transparent)`, border:`1px solid color-mix(in oklab,${n.color} 30%,transparent)` }}>
            {n.icon ? <Ic k={n.icon} w={17}/> : <Discord w={17}/>}
          </span>
          <div style={{ flex:1, minWidth:0 }}>
            <div style={{ fontFamily:'var(--cn)', fontWeight:600, fontSize:13.5, color:'var(--text)' }}>{n.title}</div>
            <div style={{ fontFamily:'var(--mono)', fontSize:11, color:'var(--text-mute)', marginTop:3 }}>{n.sub}</div>
          </div>
          {n.party && <button className="btn btn-sm btn-go" onClick={e=>{e.stopPropagation();onOpen(n.party);}}><Ic k="bolt" w={13}/>{en?'Join':'上车'}</button>}
          {n.fresh && !n.party && <span style={{ width:8, height:8, borderRadius:'50%', background:n.color, flex:'none' }} />}
        </div>
      ))}
    </div>
  );
}

function DiscordPanel({ en }){
  const rows = [
    { k:en?'Account':'账号', v:'晚风#4012', ok:true },
    { k:en?'Server':'服务器', v:'Deman Esports NA', ok:true },
    { k:en?'Synced channels':'同步频道', v:'#lol-na · #val-na · #apex-na', ok:true },
    { k:en?'Rank roles':'段位身份组', v:en?'Diamond · Master · synced':'钻石 · 大师 · 已同步', ok:true },
    { k:en?'Push pings to DM':'匹配提醒推送到私信', v:en?'On':'已开启', ok:true }
  ];
  return (
    <div style={{ display:'flex', flexDirection:'column', gap:18 }}>
      <div className="card" style={{ padding:22 }}>
        <div style={{ display:'flex', alignItems:'center', gap:13, marginBottom:18 }}>
          <span style={{ width:48, height:48, borderRadius:'var(--r-sm)', background:'#5865F2', display:'grid', placeItems:'center', color:'#fff', flex:'none' }}><Discord w={26}/></span>
          <div>
            <div style={{ fontFamily:'var(--cn)', fontWeight:800, fontSize:16 }}>{en?'Discord — two-way synced':'Discord —— 双向互通'}</div>
            <div style={{ fontFamily:'var(--mono)', fontSize:11.5, color:'var(--text-mute)', marginTop:3 }}>{en?'Web and channel share one live state':'网页和频道共享同一份实时状态'}</div>
          </div>
          <span className="status online" style={{ marginLeft:'auto' }}><span className="dot"/>{en?'Live':'在线'}</span>
        </div>
        <div style={{ display:'flex', flexDirection:'column' }}>
          {rows.map((r,i)=>(
            <div key={i} style={{ display:'flex', alignItems:'center', gap:10, padding:'11px 0', borderBottom: i<rows.length-1?'1px solid var(--line-soft)':'none' }}>
              <span style={{ fontFamily:'var(--cn)', fontSize:13, color:'var(--text-mute)', width:150, flex:'none' }}>{r.k}</span>
              <span style={{ fontFamily:'var(--mono)', fontSize:12.5, color:'var(--text-dim)', flex:1 }}>{r.v}</span>
              {r.ok && <Ic k="check" w={15} style={{ color:'var(--q-lime)' }}/>}
            </div>
          ))}
        </div>
      </div>
      <div className="card" style={{ padding:20, display:'flex', gap:14, alignItems:'flex-start' }}>
        <Ic k="link" w={20} style={{ color:'var(--v-bright)', flex:'none', marginTop:2 }}/>
        <div>
          <div style={{ fontFamily:'var(--cn)', fontWeight:700, fontSize:14, marginBottom:6 }}>{en?'About game-invite links':'关于游戏邀请链接'}</div>
          <p style={{ fontFamily:'var(--cn)', fontSize:13, color:'var(--text-dim)', lineHeight:1.65 }}>
            {en?'Discord’s in-client “Join” embed is Discord-only — but Match mirrors it: a room posts the same join card to your channel and shares the in-game lobby code, so web + Discord members land in one voice room.'
               :'Discord 客户端里那个原生“Join”邀请卡片是 Discord 独有的 —— 但 Match 会镜像它:上车房间会把同样的加入卡片发到你的频道,并共享游戏内房间码,网页和 Discord 的人最终进同一个语音房间。'}
          </p>
        </div>
      </div>
    </div>
  );
}

function MeView({ en, tab, setTab, onOpen }){
  const tabs = [['profile', en?'Profile':'我的资料'],['notif', en?'Notifications':'通知'],['discord', en?'Discord':'Discord 互通']];
  return (
    <div className="wrap" style={{ padding:'26px 26px 70px', maxWidth:820 }}>
      <div style={{ display:'flex', gap:6, marginBottom:24, borderBottom:'1.5px solid var(--line)', paddingBottom:0 }}>
        {tabs.map(([k,lbl])=>(
          <button key={k} onClick={()=>setTab(k)} style={{ fontFamily:'var(--hud)', fontWeight:700, fontSize:14, padding:'11px 16px', border:'none', background:'none', cursor:'pointer',
            color: tab===k?'var(--text)':'var(--text-mute)', borderBottom:'2px solid '+(tab===k?'var(--v-bright)':'transparent'), marginBottom:-1.5 }}>{lbl}</button>
        ))}
      </div>
      {tab==='profile' && <ProfilePanel en={en} />}
      {tab==='notif' && <NotifPanel en={en} onOpen={onOpen} />}
      {tab==='discord' && <DiscordPanel en={en} />}
    </div>
  );
}

window.MeView = MeView;
