const { useState: useStateL, useMemo: useMemoL } = React;

function LeaderboardPage({ onOpenProfile }) {
  const [tab, setTab] = useStateL("all");

  const sorted = useMemoL(() => {
    const arr = [...DB.players];
    if (tab === "tarneeb") arr.sort((a,b) => b.tarneeb - a.tarneeb);
    else if (tab === "trix") arr.sort((a,b) => b.trix - a.trix);
    else arr.sort((a,b) => b.wins - a.wins);
    return arr;
  }, [tab, DB.players]);

  return (
    <div className="screen" data-screen-label="leaderboard">
      <header className="app-header">
        <div>
          <div className="app-title">لوحة السماور</div>
          <div className="app-sub">طرنيب · تركس · لا رحمة</div>
        </div>
        <div style={{ background: "#000", border: "2.5px solid var(--gold)", borderRadius: 12, padding: "6px 10px", textAlign: "center", minWidth: 70 }}>
          <div className="num" style={{ fontSize: 28, color: "var(--gold)", textShadow: "0 0 10px var(--gold)" }}>{DB.matches.length}</div>
          <div style={{ fontSize: 9, color: "var(--cream)", fontWeight: 800, letterSpacing: 1 }}>مباراة</div>
        </div>
      </header>

      <div className="tabs">
        {[{ id: "all", label: "الكل" }, { id: "tarneeb", label: "طرنيب" }, { id: "trix", label: "تركس" }].map(t => (
          <div key={t.id} className={`tab ${tab === t.id ? "active" : ""}`} onClick={() => setTab(t.id)}>{t.label}</div>
        ))}
      </div>

      <div className="players-grid">
        {sorted.map((p, i) => (
          <PlayerCard key={`${tab}-${p.id}`} player={p} rank={i} dealIndex={i} onClick={() => onOpenProfile(p.id)} />
        ))}
      </div>

      {DB.loading && (
        <div style={{ textAlign: "center", padding: 20, fontFamily: "Lalezar,serif", color: "var(--gold)", fontSize: 18 }}>جاري التحديث…</div>
      )}
    </div>
  );
}

Object.assign(window, { LeaderboardPage });