// =============================================================================
// LIVE TEAM LEADERBOARD — hero screen
// =============================================================================

function LiveLeaderboard({ activeWeek, onTeamClick, view, onViewChange }) {
  const { teams, scoresByWeek, loading } = useLiveSeasonData();

  // Cumulative through a given week (inclusive) — includes per-week bonuses for weeks summed
  const cumThrough = (team, weekId) => {
    let total = 0;
    for (const w of RVL_WEEKS) {
      total += rvlTeamWeekTotalLive(team, scoresByWeek[w.id] || {});
      total += rvlTeamWeekBonusTotal(team, w.id);
      if (w.id === weekId) break;
    }
    return total;
  };

  // All unlocked weeks combined
  const cumAll = (team) => {
    let total = 0;
    for (const w of RVL_WEEKS.filter(w => rvlIsWeekUnlocked(w.id))) {
      total += rvlTeamWeekTotalLive(team, scoresByWeek[w.id] || {});
      total += rvlTeamWeekBonusTotal(team, w.id);
    }
    return total;
  };

  const ranked = useMemo(() => {
    if (teams.length === 0) return [];
    const idx = RVL_WEEKS.findIndex(w => w.id === activeWeek);
    const prevWeekId = idx > 0 ? RVL_WEEKS[idx - 1].id : null;
    const rows = teams.map(team => ({
      team,
      weekPts: rvlTeamWeekTotalLive(team, scoresByWeek[activeWeek] || {}) + rvlTeamWeekBonusTotal(team, activeWeek),
      cumPts:  cumAll(team),
      prevCumPts: prevWeekId ? cumThrough(team, prevWeekId) : 0,
    }));
    rows.sort((a, b) => (view === "week" ? b.weekPts - a.weekPts : b.cumPts - a.cumPts));
    // Dense ranking: tied scores share rank, next rank is consecutive (1,2,3,3,4,…).
    const assignRanks = (sortedRows, scoreOf) => {
      const ranks = {};
      let lastScore = null, lastRank = 0;
      sortedRows.forEach((r) => {
        const s = scoreOf(r);
        if (s === lastScore) { ranks[r.team?.id ?? r.id] = lastRank; }
        else { lastRank = lastRank + 1; lastScore = s; ranks[r.team?.id ?? r.id] = lastRank; }
      });
      return ranks;
    };
    const curScoreFn = view === "week" ? (r => r.weekPts) : (r => r.cumPts);
    const curRanks = assignRanks(rows, curScoreFn);
    const prevSorted = teams.map(t => ({ id: t.id, p: prevWeekId ? cumThrough(t, prevWeekId) : 0 }))
      .sort((a, b) => b.p - a.p);
    const prevRank = assignRanks(prevSorted, r => r.p);
    rows.forEach(r => {
      r.rank = curRanks[r.team.id];
      r.prevRank = prevRank[r.team.id];
      r.delta = (r.prevRank || r.rank) - r.rank;
    });
    return rows;
  }, [teams, scoresByWeek, activeWeek, view]);

  const [cms, setCms] = useState({});
  useEffect(() => { RvlApi.publicSiteSettings().then(d => d && setCms(d)).catch(() => {}); }, []);

  const [page, setPage] = useState(1);
  const [perPage, setPerPage] = useState(25);
  useEffect(() => { setPage(1); }, [activeWeek, view]);

  if (!rvlIsWeekUnlocked(activeWeek)) return <WeekLocked weekId={activeWeek} title={`Leaderboard for ${(RVL_WEEKS.find(w => w.id === activeWeek) || {}).label || "this week"} is locked`}/>;
  if (loading || ranked.length === 0) return <PageLoader label="Loading leaderboard…"/>;

  const top = ranked[0];
  const fallbackFocus = RVL_WEEKLY_FOCUS[activeWeek] || {};
  const focus = {
    emoji:    cms[`focus_${activeWeek}_emoji`]    || fallbackFocus.emoji,
    activity: cms[`focus_${activeWeek}_activity`] || fallbackFocus.activity,
    note:     cms[`focus_${activeWeek}_note`]     || fallbackFocus.note,
  };
  const weekObj = RVL_WEEKS.find(w => w.id === activeWeek);
  const cumIdx = RVL_WEEKS.findIndex(w => w.id === activeWeek);
  const cumCount = cumIdx + 1;
  const unlockedCount = RVL_WEEKS.filter(w => rvlIsWeekUnlocked(w.id)).length;
  const cumLabel = `Season cumulative · ${unlockedCount === 1 ? "Week 1 only" : `${unlockedCount} weeks combined`}`;

  return (
    <div className="rise">
      {/* Hero strip */}
      <div style={{
        position: "relative", overflow: "hidden",
        borderRadius: 18, marginBottom: 24,
        background: "var(--hero-bg)",
        border: "1px solid var(--hero-border)",
        padding: "28px 32px",
        display: "grid", gridTemplateColumns: "minmax(0, 1.6fr) minmax(280px, 1fr)", gap: 28,
        boxShadow: "var(--shadow-card)",
        color: "var(--hero-ink)",
      }} className="hero-strip">
        {(view === "week" ? top.weekPts : top.cumPts) === 0 ? (
          <div style={{ position: "relative", zIndex: 1, gridColumn: "1 / -1", display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", gap: 8, padding: "24px 0", textAlign: "center" }}>
            <div style={{ fontSize: 36, opacity: 0.3 }}>🏆</div>
            <div style={{ fontSize: 15, fontWeight: 700, color: "var(--hero-ink)" }}>No points logged yet</div>
            <div style={{ fontSize: 12, color: "var(--hero-ink-dim)" }}>Leaderboard will update once entries are in for {weekObj?.label}</div>
          </div>
        ) : (
          <>
            <div style={{ position: "relative", zIndex: 1, minWidth: 0 }}>
              <div style={{ display: "flex", gap: 10, alignItems: "center", marginBottom: 14, flexWrap: "wrap" }}>
                <div className="tag-pill crimson"><span style={{ width: 6, height: 6, borderRadius: "50%", background: "var(--crimson)", animation: "rvl-pulse-glow 2s infinite" }} /> LIVE</div>
                <div className="tag-pill gold">★ Top of the table</div>
                <div className="kicker" style={{ color: "var(--hero-ink-dim)" }}>{weekObj.label} · {weekObj.range}</div>
              </div>
              <div style={{ display: "flex", alignItems: "center", gap: 22, minWidth: 0 }}>
                <TeamCrest team={top.team} size={120} />
                <div style={{ minWidth: 0, flex: 1 }}>
                  <div className="display" style={{
                    fontSize: "clamp(32px, 4.5vw, 64px)",
                    color: "var(--hero-ink)", marginBottom: 6, lineHeight: 0.98,
                    textWrap: "balance",
                  }}>{top.team.name}</div>
                  {(() => {
                    const weeksToCount = view === "week" ? [activeWeek] : RVL_WEEKS.filter(w => rvlIsWeekUnlocked(w.id)).map(w => w.id);
                    let inducted = 0;
                    for (const wk of weeksToCount) {
                      const wkScores = scoresByWeek[wk] || {};
                      for (const m of top.team.members) {
                        for (const v of ((wkScores[m.id] || {}).visitors || [])) {
                          if (v.category === "induction") inducted++;
                        }
                      }
                    }
                    return (
                      <div style={{ display: "flex", alignItems: "center", gap: 12, color: "var(--hero-ink-dim)", fontSize: 13, flexWrap: "wrap" }}>
                        <span style={{ whiteSpace: "nowrap" }}>Captain · <strong style={{ color: "var(--hero-ink)" }}>{top.team.captain?.name || "—"}</strong></span>
                        <span style={{ width: 4, height: 4, borderRadius: "50%", background: "var(--hero-ink-dim)", opacity: 0.5 }} />
                        <span style={{ whiteSpace: "nowrap" }}>{top.team.members.length} members</span>
                        {inducted > 0 && <>
                          <span style={{ width: 4, height: 4, borderRadius: "50%", background: "var(--hero-ink-dim)", opacity: 0.5 }} />
                          <span style={{
                            display: "inline-flex", alignItems: "center", gap: 4,
                            background: "linear-gradient(135deg, var(--gold-light), var(--gold))",
                            color: "#2a1c00", fontWeight: 700, fontSize: 11,
                            padding: "2px 10px", borderRadius: 999,
                            letterSpacing: "0.05em", whiteSpace: "nowrap",
                            boxShadow: "0 2px 8px rgba(180,140,0,.25)",
                          }}>★ {inducted} inducted</span>
                        </>}
                      </div>
                    );
                  })()}
                </div>
              </div>
            </div>

            <div style={{ position: "relative", zIndex: 1, display: "flex", flexDirection: "column", justifyContent: "center", gap: 14, minWidth: 0 }}>
              <div style={{ display: "flex", alignItems: "baseline", gap: 16, flexWrap: "wrap" }}>
                <div className="display" style={{ fontSize: "clamp(56px, 8vw, 88px)", color: "var(--crimson)", lineHeight: 1 }}>
                  <Counter value={view === "week" ? top.weekPts : top.cumPts} duration={900}/>
                </div>
                <div style={{ color: "var(--hero-ink-dim)", fontSize: 12, letterSpacing: "0.1em", textTransform: "uppercase", fontWeight: 700 }}>
                  {view === "week" ? "Points this week" : "Season cumulative"}
                </div>
              </div>
              <div style={{
                background: "var(--bg-card)", border: "1px solid var(--line)",
                borderRadius: 12, padding: "12px 14px",
                display: "flex", alignItems: "center", gap: 12,
              }}>
                <div style={{
                  width: 36, height: 36, borderRadius: 8, background: "rgba(212,168,71,.16)",
                  display: "grid", placeItems: "center", fontSize: 18,
                }}>{focus.emoji}</div>
                <div style={{ minWidth: 0 }}>
                  <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: "0.14em", textTransform: "uppercase", color: "var(--ink-mute)" }}>This week&apos;s focus · {focus.activity}</div>
                  <div style={{ fontSize: 13, color: "var(--ink-dim)" }}>{focus.note}</div>
                </div>
              </div>
            </div>
          </>
        )}
      </div>

      {/* View toggle + label */}
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 16 }}>
        <div>
          <div className="kicker" style={{ marginBottom: 4 }}>Standings</div>
          <h2 style={{ fontSize: 24 }}>{view === "cumulative" ? cumLabel : view === "weekly" ? "Weekly Breakdown" : `Week of ${weekObj.range}`}</h2>
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          <CustomSelect
            value={view}
            onChange={onViewChange}
            width="160px"
            options={[
              { value: "week", label: "This Week" },
              { value: "weekly", label: "Weekly" },
              { value: "cumulative", label: "Cumulative" },
            ]}
          />
          <button onClick={() => {
            const el = document.querySelector(".leaderboard-print-root");
            if (!el) return;
            const win = window.open("", "_blank", "width=1200,height=900");
            win.document.write(`<!DOCTYPE html><html><head><meta charset="utf-8">
              <style>
                * { box-sizing: border-box; margin: 0; padding: 0; -webkit-print-color-adjust: exact; print-color-adjust: exact; }
                @page { size: 297mm 297mm; margin: 0; }
                body { background: #fff; font-family: Inter, system-ui, sans-serif; }
                .print-page { width: 297mm; height: 297mm; padding: 10mm 12mm; background: #fff; overflow: hidden; break-after: page; display: flex; flex-direction: column; justify-content: space-between; }
                .print-page:last-child { break-after: auto; }
              </style>
            </head><body>${el.innerHTML}</body></html>`);
            const today = new Date();
            const dateStr = today.toLocaleDateString("en-GB", { day: "2-digit", month: "short", year: "numeric" });
            win.document.title = `Rachhit Visitor League · BNI Pune East · ${dateStr}`;
            win.document.close();
            win.focus();
            setTimeout(() => { win.print(); win.close(); }, 400);
          }} className="btn btn-primary btn-sm no-print">⬇ Download PDF</button>
          <button onClick={async () => {
            const { default: html2canvas } = await import("html2canvas");
            const { default: JSZip } = await import("jszip");
            const el = document.querySelector(".leaderboard-print-root");
            if (!el) return;
            const today = new Date();
            const dateStr = today.toLocaleDateString("en-GB", { day: "2-digit", month: "short", year: "numeric" });
            const baseName = `Rachhit Visitor League · BNI Pune East · ${dateStr}`;

            // Render into a clean window to avoid app CSS gradient conflicts
            const win = window.open("", "_blank", "width=1400,height=900");
            win.document.write(`<!DOCTYPE html><html><head><meta charset="utf-8">
              <style>
                * { box-sizing: border-box; margin: 0; padding: 0; -webkit-print-color-adjust: exact; print-color-adjust: exact; }
                body { background: #fff; font-family: Inter, system-ui, sans-serif; }
                .print-page { width: 1300px; height: 1300px; padding: 44px 52px; background: #fff; overflow: hidden; display: flex; flex-direction: column; justify-content: space-between; }
              </style>
            </head><body>${el.innerHTML}</body></html>`);
            win.document.close();
            await new Promise(r => setTimeout(r, 600));

            const winPages = win.document.querySelectorAll(".print-page");
            const canvases = [];
            for (const page of winPages) {
              const c = await html2canvas(page, { scale: 2, backgroundColor: "#ffffff", logging: false, windowWidth: 1300, windowHeight: 1300 });
              canvases.push(c);
            }
            win.close();

            if (canvases.length === 1) {
              const a = document.createElement("a");
              a.href = canvases[0].toDataURL("image/jpeg", 0.95);
              a.download = `${baseName}.jpg`;
              a.click();
            } else {
              const zip = new JSZip();
              for (let i = 0; i < canvases.length; i++) {
                const blob = await new Promise(res => canvases[i].toBlob(res, "image/jpeg", 0.95));
                zip.file(`Page ${i + 1}.jpg`, blob);
              }
              const zipBlob = await zip.generateAsync({ type: "blob" });
              const a = document.createElement("a");
              a.href = URL.createObjectURL(zipBlob);
              a.download = `${baseName}.zip`;
              a.click();
              URL.revokeObjectURL(a.href);
            }
          }} className="btn btn-sm no-print" style={{ background: "var(--bg-card)", border: "1.5px solid var(--line-bright)", fontSize: 12, fontWeight: 600, color: "var(--ink)", display: "inline-flex", alignItems: "center", gap: 6, padding: "6px 14px", borderRadius: 8, boxShadow: "0 1px 4px rgba(0,0,0,.08)", transition: "background .15s, border-color .15s, box-shadow .15s" }}
            onMouseEnter={e => { e.currentTarget.style.background = "var(--bg-card-2)"; e.currentTarget.style.borderColor = "var(--gold)"; e.currentTarget.style.boxShadow = "0 2px 8px rgba(0,0,0,.14)"; }}
            onMouseLeave={e => { e.currentTarget.style.background = "var(--bg-card)"; e.currentTarget.style.borderColor = "var(--line-bright)"; e.currentTarget.style.boxShadow = "0 1px 4px rgba(0,0,0,.08)"; }}
          >⬇ Download JPG</button>
        </div>
      </div>

      {/* Weekly breakdown table */}
      {view === "weekly" && (() => {
        const unlockedWeeks = RVL_WEEKS.filter(w => rvlIsWeekUnlocked(w.id));
        const weeklyRanked = [...ranked].sort((a, b) => b.cumPts - a.cumPts);
        const gridCols = `60px minmax(220px,1fr) ${unlockedWeeks.map(() => "110px").join(" ")} 130px`;
        const hStyle = { fontSize: 11, fontWeight: 900, letterSpacing: "0.12em", textTransform: "uppercase", color: "var(--ink)", textAlign: "center" };
        return (
          <div className="card" style={{ padding: 0, overflow: "clip", marginBottom: 16 }}>
            <div style={{ overflowX: "auto" }}>
              <div style={{ minWidth: 500 }}>
                <div style={{ display: "grid", gridTemplateColumns: gridCols, gap: 4, padding: "12px 16px", background: "var(--bg-card-2)", borderBottom: "1px solid var(--line)" }}>
                  <div style={hStyle}>#</div>
                  <div style={{ ...hStyle, textAlign: "left" }}>Team</div>
                  {unlockedWeeks.map(w => <div key={w.id} style={hStyle}>{w.label}</div>)}
                  <div style={{ ...hStyle, color: "var(--gold)" }}>Season</div>
                </div>
                {weeklyRanked.map((r, idx) => {
                  const hasInducted = (() => { for (const w of unlockedWeeks) { const ws = scoresByWeek[w.id] || {}; for (const m of r.team.members) { if ((ws[m.id]?.visitors || []).some(v => v.category === "induction")) return true; } } return false; })();
                  return (
                    <div key={r.team.id} onClick={() => onTeamClick(r.team.id)} style={{ display: "grid", gridTemplateColumns: gridCols, gap: 4, padding: "14px 16px", alignItems: "center", borderBottom: idx < weeklyRanked.length - 1 ? "1px solid var(--line)" : 0, cursor: "pointer", background: hasInducted ? "rgba(178,30,46,.10)" : "transparent", borderLeft: hasInducted ? "3px solid var(--crimson)" : "3px solid transparent", transition: "background .15s" }}
                      onMouseEnter={e => e.currentTarget.style.background = hasInducted ? "rgba(178,30,46,.18)" : "var(--bg-card-2)"}
                      onMouseLeave={e => e.currentTarget.style.background = hasInducted ? "rgba(178,30,46,.10)" : "transparent"}>
                      <div style={{ textAlign: "center" }}><RankBadge rank={idx + 1} size={36}/></div>
                      <div style={{ display: "flex", alignItems: "center", gap: 14, minWidth: 0 }}>
                        <TeamCrest team={r.team} size={42}/>
                        <div style={{ minWidth: 0 }}>
                          <div className="display" style={{ fontSize: 22, color: "var(--ink)", lineHeight: 1 }}>{r.team.name}</div>
                          <div style={{ fontSize: 12, color: "var(--ink-mute)", marginTop: 3 }}>{r.team.captain?.name} · {r.team.members.length} members</div>
                        </div>
                      </div>
                      {unlockedWeeks.map(w => {
                        const pts = rvlTeamWeekTotalLive(r.team, scoresByWeek[w.id] || {}) + rvlTeamWeekBonusTotal(r.team, w.id);
                        return <div key={w.id} style={{ textAlign: "center", fontFamily: "Inter, system-ui, sans-serif", fontFeatureSettings: "'tnum'", fontSize: 16, fontWeight: 800, color: pts > 0 ? "var(--ink)" : "var(--ink-mute)" }}>{pts || "—"}</div>;
                      })}
                      <div style={{ textAlign: "center" }}>
                        <div className="display" style={{ fontSize: 28, color: r.cumPts > 0 ? "var(--gold-light)" : "var(--ink)", lineHeight: 1 }}>{r.cumPts.toLocaleString()}</div>
                        <div style={{ fontSize: 10, color: "var(--ink-mute)", letterSpacing: "0.1em", textTransform: "uppercase" }}>pts</div>
                      </div>
                    </div>
                  );
                })}
              </div>
            </div>
          </div>
        );
      })()}

      {/* Leaderboard table */}
      {view !== "weekly" && (() => {
        const totalPages = Math.ceil(ranked.length / perPage);
        const paginated = ranked.slice((page - 1) * perPage, page * perPage);
        return (
          <div className="card" style={{ padding: 0, overflow: "clip" }}>
            <div style={{ overflowX: "auto" }}>
            <div style={{ minWidth: 1100 }}>
            {/* Header */}
            <div style={{
              display: "grid",
              gridTemplateColumns: "50px minmax(180px,1fr) 70px 70px 70px 70px 70px 80px 80px 80px 80px 90px 60px",
              gap: 4, padding: "12px 16px",
              background: "var(--bg-card-2)", borderBottom: "1px solid var(--line)",
              fontSize: 12, letterSpacing: "0.12em", textTransform: "uppercase", color: "var(--ink)", fontWeight: 900,
            }} className="lb-header">
              <div>#</div><div>Team</div>
              {["Attn","Vist"].map(h => <div key={h} style={{ textAlign: "center" }}>{h}</div>)}
              <div style={{ textAlign: "center", color: "var(--gold)", fontWeight: 900, fontSize: 13 }}>Ind.</div>
              {["121s","Ref","MCM","TYFCB","Mem","Sub"].map(h => <div key={h} style={{ textAlign: "center" }}>{h}</div>)}
              <div style={{ textAlign: "center" }}>{view === "cumulative" ? "Total" : "Week"}</div>
              <div style={{ textAlign: "center" }}>Δ</div>
            </div>

            {/* Rows */}
            {paginated.map((r, idx) => (
              <LeaderboardRow key={r.team.id} row={r} idx={(page - 1) * perPage + idx} view={view} weekId={activeWeek}
                scoresByWeek={scoresByWeek} onClick={() => onTeamClick(r.team.id)} />
            ))}

            </div>{/* end minWidth wrapper */}
            </div>{/* end overflowX scroll wrapper */}

            {/* Pagination footer */}
            <div style={{
              display: "flex", alignItems: "center", justifyContent: "space-between",
              padding: "12px 22px", borderTop: "1px solid var(--line)",
              background: "var(--bg-card-2)", flexWrap: "wrap", gap: 10,
            }}>
              <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                <span style={{ fontSize: 12, color: "var(--ink-mute)" }}>Rows per page</span>
                <CustomSelect
                  value={perPage === Infinity ? "all" : String(perPage)}
                  onChange={v => { setPerPage(v === "all" ? Infinity : Number(v)); setPage(1); }}
                  size="sm" width="64px"
                  options={[25,50,75,100,150].map(n => ({ value: String(n), label: String(n) })).concat([{ value: "all", label: "All" }])}
                />
                <span style={{ fontSize: 12, color: "var(--ink-mute)" }}>
                  {(page - 1) * perPage + 1}–{Math.min(page * perPage, ranked.length)} of {ranked.length}
                </span>
              </div>
              <div style={{ display: "flex", alignItems: "center", gap: 3 }}>
                {/* First / Prev */}
                {[
                  { icon: "⟪", title: "First", onClick: () => setPage(1), disabled: page === 1 },
                  { icon: "⟨", title: "Previous", onClick: () => setPage(p => p - 1), disabled: page === 1 },
                ].map(b => (
                  <button key={b.title} title={b.title} onClick={b.onClick} disabled={b.disabled} style={{
                    width: 32, height: 32, display: "grid", placeItems: "center", borderRadius: 6,
                    border: "1px solid var(--line)", background: "var(--bg-card)",
                    color: "var(--ink-dim)", fontSize: 14, cursor: b.disabled ? "default" : "pointer",
                    opacity: b.disabled ? 0.3 : 1, transition: "opacity .15s",
                  }}>{b.icon}</button>
                ))}
                {/* Page numbers with ellipsis */}
                {(() => {
                  const pages = [];
                  const delta = 1;
                  const left = page - delta, right = page + delta;
                  let last = 0;
                  for (let p = 1; p <= totalPages; p++) {
                    if (p === 1 || p === totalPages || (p >= left && p <= right)) {
                      if (last && p - last > 1) pages.push("…");
                      pages.push(p);
                      last = p;
                    }
                  }
                  return pages.map((p, i) =>
                    p === "…" ? (
                      <span key={`e${i}`} style={{ width: 32, textAlign: "center", color: "var(--ink-mute)", fontSize: 13 }}>…</span>
                    ) : (
                      <button key={p} onClick={() => setPage(p)} style={{
                        width: 32, height: 32, display: "grid", placeItems: "center", borderRadius: 6,
                        border: `1px solid ${p === page ? "var(--crimson)" : "var(--line)"}`,
                        background: p === page ? "var(--crimson)" : "var(--bg-card)",
                        color: p === page ? "#fff" : "var(--ink-dim)",
                        fontWeight: p === page ? 700 : 400, fontSize: 13, cursor: "pointer",
                        transition: "background .15s",
                      }}>{p}</button>
                    )
                  );
                })()}
                {/* Next / Last */}
                {[
                  { icon: "⟩", title: "Next", onClick: () => setPage(p => p + 1), disabled: page === totalPages },
                  { icon: "⟫", title: "Last", onClick: () => setPage(totalPages), disabled: page === totalPages },
                ].map(b => (
                  <button key={b.title} title={b.title} onClick={b.onClick} disabled={b.disabled} style={{
                    width: 32, height: 32, display: "grid", placeItems: "center", borderRadius: 6,
                    border: "1px solid var(--line)", background: "var(--bg-card)",
                    color: "var(--ink-dim)", fontSize: 14, cursor: b.disabled ? "default" : "pointer",
                    opacity: b.disabled ? 0.3 : 1, transition: "opacity .15s",
                  }}>{b.icon}</button>
                ))}
              </div>
            </div>
          </div>
        );
      })()}

      <PrintLeaderboard ranked={ranked} view={view} weekId={activeWeek} scoresByWeek={scoresByWeek} weekObj={weekObj} top={top} focus={focus}/>
    </div>
  );
}

function computeRowStats(team, view, weekId, scoresByWeek) {
  let attCount = 0, visitorCount = 0, inductedCount = 0, oneToOneCount = 0, refCount = 0, teamAttBonus = 0;
  const weeksToSum = view === "cumulative"
    ? RVL_WEEKS.filter(w => rvlIsWeekUnlocked(w.id))
    : [{ id: weekId }];
  for (const w of weeksToSum) {
    const wkScores = scoresByWeek[w.id] || {};
    let allPresent = team.members.length > 0;
    let allPresentOrSub = team.members.length > 0;
    for (const m of team.members) {
      const s = wkScores[m.id] || {};
      if (s.present) attCount++;
      if (!s.present) allPresent = false;
      if (!s.present && !s.sub) allPresentOrSub = false;
      for (const v of (s.visitors || [])) {
        if (v.category === "induction") inductedCount++;
        else visitorCount++;
      }
      oneToOneCount += Math.min((s.one_to_ones || []).length, 2);
      refCount += (s.referrals || []).length;
    }
    if (allPresent) teamAttBonus += 100;
    else if (allPresentOrSub) teamAttBonus += 50;
  }
  return { attCount, visitorCount, inductedCount, oneToOneCount, refCount, teamAttBonus };
}

// A4 landscape @96dpi = 1123 × 794px. With 40px top+bottom padding = 714px usable.
// Hero (~190px) + heading (~56px) + table-header (~36px) = ~282px → ~432px left → ~6 rows @ 68px
// Subsequent pages: 714px / 68px ≈ 10 rows
const PRINT_FIRST_ROWS = 11;
const PRINT_OTHER_ROWS = 14;

function paginatePrintRows(rows) {
  const pages = [];
  let i = 0;
  pages.push(rows.slice(0, PRINT_FIRST_ROWS));
  i += PRINT_FIRST_ROWS;
  while (i < rows.length) {
    pages.push(rows.slice(i, i + PRINT_OTHER_ROWS));
    i += PRINT_OTHER_ROWS;
  }
  return pages;
}

function PrintLeaderboard({ ranked, view, weekId, scoresByWeek, weekObj, top, focus }) {
  // Brand palette — mirrors :root in styles.css (light theme)
  const C = {
    page:        "#ffffff",
    card:        "#ffffff",
    card2:       "#f8f8f6",
    line:        "#e6dfce",
    lineBright:  "#d3c8ac",
    ink:         "#1c1611",
    inkDim:      "#4a3f33",
    inkMute:     "#8c7f6c",
    crimson:     "#b21e2e",
    crimsonDeep: "#7b0d1a",
    gold:        "#b08526",
    goldLight:   "#d4a847",
    goldTintBg:  "rgba(212,168,71,.12)",
    good:        "#1f7a3a",
    bad:         "#a01b1b",
  };

  const unlockedWeeksPrint = RVL_WEEKS.filter(w => rvlIsWeekUnlocked(w.id));
  const topPts = view === "week" ? top.weekPts : top.cumPts;
  const topInducted = (() => {
    let count = 0;
    const weeksToCount = view === "cumulative" ? unlockedWeeksPrint : [{ id: weekId }];
    for (const w of weeksToCount) {
      const ws = scoresByWeek[w.id] || {};
      for (const m of top.team.members) {
        for (const v of (ws[m.id]?.visitors || [])) {
          if (v.category === "induction") count++;
        }
      }
    }
    return count;
  })();
  const cumLabelLocal = view === "week"
    ? `Week of ${weekObj.range}`
    : view === "weekly"
      ? "Weekly Breakdown"
      : `Season cumulative · ${unlockedWeeksPrint.length === 1 ? "Week 1 only" : `${unlockedWeeksPrint.length} weeks combined`}`;

  const pill = {
    display: "inline-flex", alignItems: "center", gap: 6,
    padding: "4px 11px", borderRadius: 999,
    fontSize: 10, fontWeight: 800, letterSpacing: "0.12em", textTransform: "uppercase",
  };

  const th = {
    textAlign: "center", padding: "10px 4px",
    background: C.card2, color: C.inkMute,
    fontSize: 12, fontWeight: 800, letterSpacing: "0.14em", textTransform: "uppercase",
    borderBottom: `1px solid ${C.line}`,
  };
  const thLeft = { ...th, textAlign: "left" };

  const tdBase = { padding: "12px 4px", borderBottom: `1px solid ${C.line}`, fontSize: 15, fontWeight: 700, color: C.ink, fontFamily: "monospace", textAlign: "center", verticalAlign: "middle" };
  const tdLeft = { ...tdBase, fontFamily: "Inter, system-ui, sans-serif", textAlign: "left" };

  const pages = paginatePrintRows(ranked);

  const renderTableRows = (rows) => rows.map((r, idx) => {
    const stats = computeRowStats(r.team, view, weekId, scoresByWeek);
    const weeksToSum = view === "week"
      ? [{ id: weekId }]
      : RVL_WEEKS.slice(0, RVL_WEEKS.findIndex(w => w.id === weekId) + 1);
    let mcm = 0, tyfcb = 0, mAtt = 0, sAtt = 0;
    for (const w of weeksToSum) {
      const wb = rvlTeamWeekBonus(r.team, w.id);
      mcm += wb.mcm; tyfcb += wb.tyfcb;
      if (wb.attendance === 100) mAtt += 100;
      else if (wb.attendance === 50) sAtt += 50;
    }
    const isTop = r.rank === 1;
    const rowBg = isTop ? "linear-gradient(90deg, rgba(212,168,71,.12), rgba(255,255,255,0) 60%)" : (idx % 2 === 0 ? C.card : C.card2);
    const totalPts = view === "week" ? r.weekPts : r.cumPts;
    return (
      <tr key={r.team.id} style={{ background: rowBg }}>
        <td style={{ ...tdLeft, paddingLeft: 22, fontWeight: 800 }}>
          <span style={{
            display: "inline-flex", alignItems: "center", justifyContent: "center",
            width: 32, height: 32, borderRadius: "50%",
            background: r.rank === 1 ? C.crimson : r.rank === 2 ? "#94a3b8" : r.rank === 3 ? "#b87333" : C.card2,
            color: r.rank <= 3 ? "#fff" : C.ink,
            border: r.rank === 1 ? `2px solid ${C.goldLight}` : r.rank === 2 ? `2px solid #cbd5e1` : r.rank === 3 ? `2px solid #d4956a` : `1px solid ${C.lineBright}`,
            fontSize: 13, fontWeight: 800,
          }}>{r.rank}</span>
        </td>
        <td style={{ ...tdLeft, paddingLeft: 8 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
            <TeamCrest team={r.team} size={42}/>
            <div style={{ minWidth: 0 }}>
              <div style={{ fontSize: 20, fontWeight: 800, color: C.ink, lineHeight: 1.05, letterSpacing: "-0.01em" }}>{r.team.name}</div>
              <div style={{ fontSize: 12, color: C.inkMute, marginTop: 3 }}>{r.team.captain?.name || "—"} · {r.team.members.length} members</div>
            </div>
          </div>
        </td>
        <td style={{ ...tdBase, color: C.inkDim, fontSize: 14 }}>{stats.attCount}</td>
        <td style={{ ...tdBase, color: C.inkDim, fontSize: 14 }}>{stats.visitorCount}</td>
        <td style={{ ...tdBase, fontSize: 14, fontWeight: 800, color: stats.inductedCount > 0 ? C.goldLight : C.inkMute }}>{stats.inductedCount || "—"}</td>
        <td style={{ ...tdBase, color: C.inkDim, fontSize: 14 }}>{stats.oneToOneCount}</td>
        <td style={{ ...tdBase, color: C.inkDim, fontSize: 14 }}>{stats.refCount}</td>
        <td style={{ ...tdBase, fontWeight: 700, color: mcm > 0 ? C.goldLight : C.inkMute }}>{mcm > 0 ? `+${mcm}` : "—"}</td>
        <td style={{ ...tdBase, fontWeight: 700, color: tyfcb > 0 ? C.goldLight : C.inkMute }}>{tyfcb > 0 ? `+${tyfcb}` : "—"}</td>
        <td style={{ ...tdBase, fontWeight: 700, color: mAtt > 0 ? C.goldLight : C.inkMute }}>{mAtt > 0 ? `+${mAtt}` : "—"}</td>
        <td style={{ ...tdBase, fontWeight: 700, color: sAtt > 0 ? C.goldLight : C.inkMute }}>{sAtt > 0 ? `+${sAtt}` : "—"}</td>
        <td style={{ ...tdBase, fontWeight: 800, fontSize: 20, color: isTop ? C.crimson : C.ink, paddingRight: 18 }}>{totalPts.toLocaleString()}</td>
      </tr>
    );
  });

  const tableHead = (
    <thead>
      <tr>
        <th style={{ ...th, textAlign: "left", paddingLeft: 22, width: 60 }}>#</th>
        <th style={{ ...thLeft, paddingLeft: 8 }}>Team</th>
        <th style={th}>Attn</th><th style={th}>Vist</th><th style={{ ...th, color: C.gold, fontWeight: 800 }}>Ind.</th><th style={th}>121s</th><th style={th}>Ref</th>
        <th style={th}>MCM</th><th style={th}>TYFCB</th><th style={th}>Mem</th><th style={th}>Sub</th>
        <th style={{ ...th, paddingRight: 18 }}>{view === "week" ? "Week" : "Total"}</th>
      </tr>
    </thead>
  );

  const firstPageContent = (
    <>
      <div style={{
        borderRadius: 14, marginBottom: 16,
        background: "linear-gradient(135deg, #ffffff 0%, #f5f5f3 100%)",
        border: `1px solid ${C.line}`, padding: "16px 20px",
        display: "grid", gridTemplateColumns: "1.6fr 1fr", gap: 20, alignItems: "center",
      }}>
        <div style={{ minWidth: 0 }}>
          <div style={{ display: "flex", gap: 8, alignItems: "center", marginBottom: 8 }}>
            <span style={{ ...pill, padding: "2px 8px", fontSize: 11, background: "rgba(178,30,46,.10)", color: C.crimson }}>
              <span style={{ width: 5, height: 5, borderRadius: "50%", background: C.crimson, display: "inline-block" }}/> Live
            </span>
            <span style={{ ...pill, padding: "2px 8px", fontSize: 11, background: C.goldTintBg, color: C.gold }}>★ Top of the table</span>
            <span style={{ fontSize: 11, fontWeight: 800, letterSpacing: "0.14em", textTransform: "uppercase", color: C.inkMute }}>{weekObj.label} · {weekObj.range}</span>
          </div>
          <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
            <TeamCrest team={top.team} size={68}/>
            <div>
              <div style={{ fontSize: 36, lineHeight: 1, color: C.ink, marginBottom: 4, fontWeight: 800, letterSpacing: "-0.01em" }}>{top.team.name}</div>
              <div style={{ display: "flex", alignItems: "center", gap: 8, flexWrap: "wrap" }}>
                <span style={{ color: C.inkDim, fontSize: 13 }}>Captain · <strong style={{ color: C.ink }}>{top.team.captain?.name || "—"}</strong> · {top.team.members.length} members</span>
                {topInducted > 0 && (
                  <span style={{
                    display: "inline-flex", alignItems: "center", gap: 4,
                    background: `linear-gradient(135deg, ${C.goldLight}, ${C.gold})`,
                    color: "#2a1c00", fontWeight: 700, fontSize: 11,
                    padding: "3px 10px", borderRadius: 999,
                    letterSpacing: "0.05em",
                  }}>★ {topInducted} inducted</span>
                )}
              </div>
            </div>
          </div>
        </div>
        <div style={{ display: "flex", flexDirection: "column", justifyContent: "center", gap: 8 }}>
          <div style={{ display: "flex", alignItems: "baseline", gap: 10 }}>
            <div style={{ fontSize: 52, color: C.crimson, lineHeight: 1, fontWeight: 800 }}>{topPts.toLocaleString()}</div>
            <div style={{ color: C.inkDim, fontSize: 12, letterSpacing: "0.1em", textTransform: "uppercase", fontWeight: 700 }}>{view === "week" ? "Points this week" : "Season cumulative"}</div>
          </div>
          {focus && (focus.activity || focus.note) && (
            <div style={{ background: C.card, border: `1px solid ${C.line}`, borderRadius: 10, padding: "8px 10px", display: "flex", alignItems: "center", gap: 10 }}>
              <div style={{ width: 26, height: 26, borderRadius: 6, background: C.goldTintBg, display: "flex", alignItems: "center", justifyContent: "center", fontSize: 14 }}>{focus.emoji || "★"}</div>
              <div>
                <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: "0.14em", textTransform: "uppercase", color: C.inkMute }}>This week’s focus · {focus.activity}</div>
                <div style={{ fontSize: 13, color: C.inkDim }}>{focus.note}</div>
              </div>
            </div>
          )}
        </div>
      </div>
      <div style={{ marginBottom: 12 }}>
        <div style={{ fontSize: 13, fontWeight: 800, letterSpacing: "0.16em", textTransform: "uppercase", color: C.crimson, marginBottom: 4 }}>Standings</div>
        <div style={{ fontSize: 26, fontWeight: 800, color: C.ink }}>{cumLabelLocal}</div>
      </div>
      {view !== "weekly" && (
        <div style={{ background: C.card, border: `1px solid ${C.line}`, borderRadius: 14, overflow: "hidden" }}>
          <table style={{ width: "100%", borderCollapse: "collapse" }}>
            {tableHead}
            <tbody>{renderTableRows(pages[0])}</tbody>
          </table>
        </div>
      )}
    </>
  );

  const weeklyTableHead = (
    <thead>
      <tr>
        <th style={{ ...th, textAlign: "left", paddingLeft: 22, width: 60 }}>#</th>
        <th style={{ ...thLeft, paddingLeft: 8 }}>Team</th>
        {unlockedWeeksPrint.map(w => <th key={w.id} style={th}>{w.label}</th>)}
        <th style={{ ...th, color: C.gold, paddingRight: 18 }}>Season</th>
      </tr>
    </thead>
  );

  const weeklyRankedSorted = [...ranked].sort((a, b) => b.cumPts - a.cumPts);

  const renderWeeklyRows = (rows) => rows.map((r, idx) => {
    const isTop = r.rank === 1;
    const rowBg = isTop ? "linear-gradient(90deg, rgba(212,168,71,.12), rgba(255,255,255,0) 60%)" : (idx % 2 === 0 ? C.card : C.card2);
    return (
      <tr key={r.team.id} style={{ background: rowBg }}>
        <td style={{ ...tdLeft, paddingLeft: 22, fontWeight: 800 }}>
          <span style={{
            display: "inline-flex", alignItems: "center", justifyContent: "center",
            width: 32, height: 32, borderRadius: "50%",
            background: r.rank === 1 ? C.crimson : r.rank === 2 ? "#94a3b8" : r.rank === 3 ? "#b87333" : C.card2,
            color: r.rank <= 3 ? "#fff" : C.ink,
            border: r.rank === 1 ? `2px solid ${C.goldLight}` : r.rank === 2 ? `2px solid #cbd5e1` : r.rank === 3 ? `2px solid #d4956a` : `1px solid ${C.lineBright}`,
            fontSize: 13, fontWeight: 800,
          }}>{r.rank}</span>
        </td>
        <td style={{ ...tdLeft, paddingLeft: 8 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
            <TeamCrest team={r.team} size={42}/>
            <div style={{ minWidth: 0 }}>
              <div style={{ fontSize: 20, fontWeight: 800, color: C.ink, lineHeight: 1.05, letterSpacing: "-0.01em" }}>{r.team.name}</div>
              <div style={{ fontSize: 12, color: C.inkMute, marginTop: 3 }}>{r.team.captain?.name || "—"} · {r.team.members.length} members</div>
            </div>
          </div>
        </td>
        {unlockedWeeksPrint.map(w => {
          const pts = rvlTeamWeekTotalLive(r.team, scoresByWeek[w.id] || {}) + rvlTeamWeekBonusTotal(r.team, w.id);
          return <td key={w.id} style={{ ...tdBase, fontSize: 14, fontWeight: 800, color: pts > 0 ? C.ink : C.inkMute }}>{pts || "—"}</td>;
        })}
        <td style={{ ...tdBase, fontWeight: 800, fontSize: 20, color: isTop ? C.crimson : C.gold, paddingRight: 18 }}>{r.cumPts.toLocaleString()}</td>
      </tr>
    );
  });

  const weeklyPages = paginatePrintRows(weeklyRankedSorted);

  return (
    <div className="leaderboard-print-root print-only">
      {(view === "weekly" ? weeklyPages : pages).map((pageRows, pageIdx) => (
        <div key={pageIdx} className="print-page">
          <div>
            {view === "weekly" ? (
              <>
                {pageIdx === 0 && firstPageContent}
                <div style={{ background: C.card, border: `1px solid ${C.line}`, borderRadius: 14, overflow: "hidden" }}>
                  <table style={{ width: "100%", borderCollapse: "collapse" }}>
                    {weeklyTableHead}
                    <tbody>{renderWeeklyRows(pageRows)}</tbody>
                  </table>
                </div>
              </>
            ) : pageIdx === 0 ? firstPageContent : (
              <div style={{ background: C.card, border: `1px solid ${C.line}`, borderRadius: 14, overflow: "hidden" }}>
                <table style={{ width: "100%", borderCollapse: "collapse" }}>
                  {tableHead}
                  <tbody>{renderTableRows(pageRows)}</tbody>
                </table>
              </div>
            )}
          </div>
          <div style={{ marginTop: 16, paddingTop: 8, borderTop: `1px solid ${C.line}`, display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
              <img src="/applex-group.png" alt="Applex Group" style={{ height: 28, width: 28, objectFit: "contain", borderRadius: 4 }}/>
              <div style={{ fontSize: 10, color: C.inkMute, letterSpacing: "0.02em", lineHeight: 1.4 }}>
                Powered by <a href="https://applexgroup.com/" style={{ color: "#b08526", fontWeight: 800, textDecoration: "none" }}>Applex Group</a> · Member of BNI Racchit Pune East Region
              </div>
            </div>
            <div style={{ fontSize: 10, color: C.inkMute, letterSpacing: "0.04em" }}>
              Rachhit Visitor League · BNI Pune East
            </div>
          </div>
        </div>
      ))}
    </div>
  );
}

(function injectLeaderboardPrintStyles() {
  if (document.getElementById("leaderboard-print-styles")) return;
  const style = document.createElement("style");
  style.id = "leaderboard-print-styles";
  style.textContent = `
    .leaderboard-print-root { display: none; }
    @media print {
      .print-page {
        display: flex !important;
        flex-direction: column !important;
        justify-content: space-between !important;
      }
    }
  `;
  document.head.appendChild(style);
})();

function LeaderboardRow({ row, idx, view, weekId, scoresByWeek, onClick }) {
  const { team, rank, weekPts, cumPts, delta } = row;
  let attCount = 0, visitorCount = 0, inductedCount = 0, oneToOneCount = 0, refCount = 0;
  let mcm = 0, tyfcb = 0, mAttSum = 0, sAttSum = 0;
  const weeksToSum = view === "cumulative"
    ? RVL_WEEKS.filter(w => rvlIsWeekUnlocked(w.id))
    : [{ id: weekId }];
  for (const w of weeksToSum) {
    const wkScores = scoresByWeek[w.id] || {};
    for (const m of team.members) {
      const s = wkScores[m.id] || {};
      if (s.present) attCount++;
      for (const v of (s.visitors || [])) {
        if (v.category === "induction") inductedCount++;
        else visitorCount++;
      }
      oneToOneCount += Math.min((s.one_to_ones || []).length, 2);
      refCount += (s.referrals || []).length;
    }
    const wb = rvlTeamWeekBonus(team, w.id);
    mcm += wb.mcm;
    tyfcb += wb.tyfcb;
    if (wb.attendance === 100) mAttSum += 100;
    else if (wb.attendance === 50) sAttSum += 50;
  }
  const teamBonusTotal = mcm + tyfcb + mAttSum + sAttSum;
  const isTop = rank === 1;
  const hasInducted = inductedCount > 0;

  return (
    <div
      onClick={onClick}
      style={{
        display: "grid",
        gridTemplateColumns: "50px minmax(180px,1fr) 70px 70px 70px 70px 70px 80px 80px 80px 80px 90px 60px",
        gap: 4,
        padding: "16px 16px",
        alignItems: "center",
        borderBottom: idx === 9 ? 0 : "1px solid var(--line)",
        cursor: "pointer",
        background: hasInducted ? "rgba(178,30,46,.14)" : "transparent",
        borderLeft: hasInducted ? "3px solid var(--crimson)" : "3px solid transparent",
        position: "relative",
        transition: "background .2s ease",
      }}
      className="lb-row"
      onMouseEnter={e => e.currentTarget.style.background = hasInducted ? "rgba(178,30,46,.22)" : "var(--bg-card-2)"}
      onMouseLeave={e => e.currentTarget.style.background = hasInducted ? "rgba(178,30,46,.14)" : "transparent"}
    >
      <div><RankBadge rank={rank} size={36}/></div>
      <div style={{ display: "flex", alignItems: "center", gap: 14, minWidth: 0 }}>
        <TeamCrest team={team} size={42}/>
        <div style={{ minWidth: 0 }}>
          <div className="display" style={{ fontSize: 22, color: "var(--ink)", lineHeight: 1 }}>{team.name}</div>
          <div style={{ fontSize: 12, color: "var(--ink-mute)", marginTop: 2 }}>{team.captain?.name || "—"} · {team.members.length} members</div>
        </div>
      </div>
      <div style={{ textAlign: "center", fontFamily: "Inter, system-ui, sans-serif", fontFeatureSettings: "'tnum'", fontSize: 16, fontWeight: 500, color: "var(--ink-dim)" }}>{attCount}</div>
      <div style={{ textAlign: "center", fontFamily: "Inter, system-ui, sans-serif", fontFeatureSettings: "'tnum'", fontSize: 16, fontWeight: 500, color: "var(--ink-dim)" }}>{visitorCount}</div>
      <div style={{ textAlign: "center", fontFamily: "Inter, system-ui, sans-serif", fontFeatureSettings: "'tnum'", fontSize: 16, fontWeight: 800, color: inductedCount > 0 ? "var(--gold-light)" : "var(--ink-dim)" }}>{inductedCount || "—"}</div>
      <div style={{ textAlign: "center", fontFamily: "Inter, system-ui, sans-serif", fontFeatureSettings: "'tnum'", fontSize: 16, fontWeight: 500, color: "var(--ink-dim)" }}>{oneToOneCount}</div>
      <div style={{ textAlign: "center", fontFamily: "Inter, system-ui, sans-serif", fontFeatureSettings: "'tnum'", fontSize: 16, fontWeight: 500, color: "var(--ink-dim)" }}>{refCount}</div>
      <div style={{ textAlign: "center", fontFamily: "Inter, system-ui, sans-serif", fontFeatureSettings: "'tnum'", fontSize: 15, fontWeight: 500, color: mcm > 0 ? "var(--gold-light)" : "var(--ink-dim)" }}>
        {mcm > 0 ? `+${mcm}` : "—"}
      </div>
      <div style={{ textAlign: "center", fontFamily: "Inter, system-ui, sans-serif", fontFeatureSettings: "'tnum'", fontSize: 15, fontWeight: 500, color: tyfcb > 0 ? "var(--gold-light)" : "var(--ink-dim)" }}>
        {tyfcb > 0 ? `+${tyfcb}` : "—"}
      </div>
      <div style={{ textAlign: "center", fontFamily: "Inter, system-ui, sans-serif", fontFeatureSettings: "'tnum'", fontSize: 15, fontWeight: 500, color: mAttSum > 0 ? "var(--gold-light)" : "var(--ink-dim)" }}>
        {mAttSum > 0 ? `+${mAttSum}` : "—"}
      </div>
      <div style={{ textAlign: "center", fontFamily: "Inter, system-ui, sans-serif", fontFeatureSettings: "'tnum'", fontSize: 15, fontWeight: 500, color: sAttSum > 0 ? "var(--gold-light)" : "var(--ink-dim)" }}>
        {sAttSum > 0 ? `+${sAttSum}` : "—"}
      </div>
      <div style={{ textAlign: "center" }}>
        <div className="display" style={{ fontSize: 28, color: hasInducted ? "var(--gold-light)" : "var(--ink)", lineHeight: 1 }}>
          {(view === "week" ? weekPts : cumPts).toLocaleString()}
        </div>
        <div style={{ fontSize: 10, color: "var(--ink-mute)", letterSpacing: "0.1em", textTransform: "uppercase" }}>pts</div>
      </div>
      <div style={{ textAlign: "center" }}>
        <DeltaPill delta={delta}/>
      </div>
    </div>
  );
}

function DeltaPill({ delta }) {
  if (delta === 0 || delta === undefined) return <span style={{ color: "var(--ink-mute)", fontSize: 13 }}>—</span>;
  const up = delta > 0;
  return (
    <span style={{
      display: "inline-flex", alignItems: "center", gap: 3,
      padding: "3px 8px",
      borderRadius: 999,
      background: up ? "rgba(34,197,94,.12)" : "rgba(239,68,68,.12)",
      color: up ? "#86efac" : "#fca5a5",
      fontWeight: 700, fontSize: 12,
      border: `1px solid ${up ? "rgba(34,197,94,.3)" : "rgba(239,68,68,.3)"}`,
    }}>
      {up ? "▲" : "▼"} {Math.abs(delta)}
    </span>
  );
}

window.LiveLeaderboard = LiveLeaderboard;
