/* ============ LEADERBOARD: in-group + global (all app users & groups) ============ */
(function(){
  const { useState, useEffect } = React;
  const { AvatarImg, GroupIcon, CONTAINERS } = window;
  const fmt=(n)=>n.toFixed(2);
  const MEDAL=['🥇','🥈','🥉'];

  function Leaderboard({group, uid, gid}){
    const [scope,setScope]=useState('group');   // group | global
    const [gmode,setGmode]=useState('users');    // users | groups  (within global)
    const [by,setBy]=useState('money');           // money | cans
    const [pubUsers,setPubUsers]=useState(null);
    const [pubGroups,setPubGroups]=useState(null);

    useEffect(()=>{
      if(scope!=='global') return;
      const db=window.fbDb; if(!db) return;
      const uref=db.ref('public/users'), gref=db.ref('public/groups');
      const uh=s=>setPubUsers(s.val()||{}), gh=s=>setPubGroups(s.val()||{});
      uref.on('value',uh); gref.on('value',gh);
      return ()=>{ uref.off('value',uh); gref.off('value',gh); };
    },[scope]);

    let rows=[]; let kind='user';
    if(scope==='group'){
      const counts=group.counts||{}, members=group.members||{};
      rows=Object.keys(members).map(u=>{ const c=counts[u]||{}; let money=0,cans=0; CONTAINERS.forEach(d=>{const n=c[d.id]||0; money+=n*d.rate; cans+=n;}); return {id:u, name:members[u].name||'משתתף', avatar:members[u].avatar||'fox', money, cans, me:u===uid}; });
    } else if(gmode==='users'){
      const pu=pubUsers||{};
      rows=Object.keys(pu).map(u=>{ const g=pu[u].groups||{}; let money=0,cans=0; Object.keys(g).forEach(k=>{money+=g[k].money||0; cans+=g[k].cans||0;}); return {id:u, name:pu[u].name||'משתתף', avatar:pu[u].avatar||'fox', money, cans, me:u===uid}; });
    } else {
      kind='group'; const pg=pubGroups||{};
      rows=Object.keys(pg).map(k=>({id:k, name:pg[k].name||'קבוצה', icon:pg[k].icon||'♻️', money:pg[k].money||0, cans:pg[k].cans||0, members:pg[k].members||0, me:k===gid}));
    }
    rows=rows.filter(r=>(r.money>0||r.cans>0));
    rows.sort((a,b)=> by==='money' ? b.money-a.money : b.cans-a.cans);
    const max=rows.length? (by==='money'? rows[0].money : rows[0].cans) : 0;
    const loading = scope==='global' && ((gmode==='users'&&pubUsers===null)||(gmode==='groups'&&pubGroups===null));

    return (
      <div>
        <div className="sec-title"><h2>🏆 טבלת האלופים</h2><div className="ln"></div></div>

        <div className="seg" style={{maxWidth:320,margin:'0 auto 10px'}}>
          <button className={scope==='group'?'on':''} onClick={()=>setScope('group')}>👪 בקבוצה</button>
          <button className={scope==='global'?'on':''} onClick={()=>setScope('global')}>🌍 כל המשתמשים</button>
        </div>

        {scope==='global' && (
          <div className="seg" style={{maxWidth:320,margin:'0 auto 10px'}}>
            <button className={gmode==='users'?'on':''} onClick={()=>setGmode('users')}>🙋 יחידים</button>
            <button className={gmode==='groups'?'on':''} onClick={()=>setGmode('groups')}>👥 קבוצות</button>
          </div>
        )}

        <div className="seg" style={{maxWidth:280,margin:'0 auto 16px'}}>
          <button className={by==='money'?'on':''} onClick={()=>setBy('money')}>💰 לפי כסף</button>
          <button className={by==='cans'?'on':''} onClick={()=>setBy('cans')}>🥤 לפי מכלים</button>
        </div>

        {loading && <div className="center-load" style={{minHeight:140}}><div className="spin"></div></div>}

        <div className="rows">
          {!loading && rows.length===0 && <p className="chat-empty">{scope==='global'?'אין עדיין נתונים לדירוג הכללי':'אין עדיין משתתפים'}</p>}
          {rows.map((r,i)=>{
            const val = by==='money' ? '₪'+fmt(r.money) : r.cans+' מכלים';
            const sub = kind==='group' ? (r.members+' חברים') : (by==='money' ? r.cans+' מכלים' : '₪'+fmt(r.money));
            const w = max>0 ? Math.max(6,((by==='money'?r.money:r.cans)/max)*100) : 0;
            return (
              <div className="row" key={r.id} style={r.me?{outline:'3px solid var(--cyan)',outlineOffset:'-1px'}:null}>
                <div style={{width:34,textAlign:'center',fontSize:i<3?'1.5rem':'1rem',fontWeight:900,color:'#7c8f84',flex:'none'}}>{i<3?MEDAL[i]:(i+1)}</div>
                {kind==='group' ? <GroupIcon value={r.icon} size={44} radius={13}/> : <AvatarImg value={r.avatar} size={44}/>}
                <div className="row-info">
                  <div className="nm">{r.name}{r.me && <span style={{color:'var(--cyan-dk)',fontSize:'.72rem',fontWeight:800}}> · {kind==='group'?'הקבוצה שלי':'אני'}</span>}</div>
                  <div className="progress-track" style={{height:10,marginTop:6}}>
                    <div className="progress-fill" style={{width:w+'%',animation:'none'}}></div>
                  </div>
                </div>
                <div style={{textAlign:'center',flex:'none',minWidth:64}}>
                  <div style={{fontWeight:900,color:'var(--ink)',direction:'ltr',fontSize:'1.05rem'}}>{val}</div>
                  <div style={{fontSize:'.66rem',color:'#7c8f84',fontWeight:700,direction:'ltr'}}>{sub}</div>
                </div>
              </div>
            );
          })}
        </div>

        <p className="muted" style={{textAlign:'center',marginTop:16,color:'#8fe6b6',lineHeight:1.6}}>
          {scope==='global'
            ? (gmode==='groups' ? 'דירוג כל הקבוצות באפליקציה לפי הפיקדון שנאסף 🌍' : 'דירוג כל המשתמשים באפליקציה — לפי מה שכל אחד אסף בכל הקבוצות 🌍')
            : 'הדירוג לפי מה שכל אחד אסף בפועל 👀 · כולם רואים את כולם'}
        </p>
      </div>
    );
  }

  Object.assign(window, { Leaderboard });
})();
