/* screens/Leaderboard.jsx — group-stage + pop quiz leaderboards. window.LeaderboardScreen */
function LeaderboardRow({ row, isMe, mode }) {
  const label = row.name || ('Predictor #' + row.id.slice(-4).toUpperCase());
  return (
    <tr data-me={isMe ? 1 : undefined}>
      <td className="pos">{row.rank}</td>
      <td className="col-team">
        <b>{label}</b>{isMe && <span className="pill pill--gold" style={{ marginLeft: 8 }}>You</span>}
      </td>
      <td className="pts tnum">
        {row.correct}{mode === 'quiz' && <span className="muted" style={{ fontWeight: 400 }}> / {row.answered}</span>}
      </td>
    </tr>
  );
}

/* realScores: { [matchId]: { hs, as, o } } — played group-stage matches, from app.jsx's fetchRealScores */
function LeaderboardScreen({ store, realScores }) {
  const { useState, useEffect, useMemo, useRef } = React;
  const [preds, setPreds] = useState(null); // null = loading, else array of { id, name, results, quiz_log }
  const [tab, setTab] = useState('predictions'); // 'predictions' | 'quiz'
  const [confettiKey, setConfettiKey] = useState(0);
  const [showConfetti, setShowConfetti] = useState(false);
  const celebratedTabs = useRef(new Set());

  useEffect(() => {
    window.bwcpTrack?.('bwcp_leaderboard_viewed');
    const cfg = window.BWCP_CONFIG;
    const sb = (cfg && window.supabase)
      ? (window._bwcpSB || window.supabase.createClient(cfg.supabaseUrl, cfg.supabaseAnonKey))
      : null;
    if (!sb) { setPreds([]); return; }
    sb.from('predictions').select('id, name, results, quiz_log').then(({ data, error }) => {
      setPreds(error ? [] : (data || []));
    });
  }, []);

  // Recomputed whenever predictions land or realScores updates (app.jsx's poll/initial fetch)
  const predData = useMemo(() => (
    preds === null ? null : window.WCLogic.computeLeaderboard(preds, realScores)
  ), [preds, realScores]);

  const quizData = useMemo(() => (
    preds === null ? null : window.WCLogic.computeQuizLeaderboard(preds)
  ), [preds]);

  const data = tab === 'quiz' ? quizData : predData;
  const isEmpty = data && (tab === 'quiz' ? data.rows.every(r => r.answered === 0) : data.total === 0);
  const me = useMemo(() => (data ? data.rows.find(r => r.id === store.uuid) : null), [data, store.uuid]);

  // confetti once per tab per visit when you're sitting at #1
  useEffect(() => {
    if (!me || me.rank !== 1 || celebratedTabs.current.has(tab)) return;
    celebratedTabs.current.add(tab);
    setConfettiKey(k => k + 1);
    setShowConfetti(true);
    window.bwcpTrack?.('bwcp_rank1_confetti', { tab });
  }, [me, tab]);

  const switchTab = (next) => {
    if (next === tab) return;
    setTab(next);
    window.bwcpTrack?.('bwcp_leaderboard_tab_viewed', { tab: next });
  };

  return (
    <div className="page">
      <header className="phead">
        <div>
          <div className="eyebrow">{tab === 'quiz' ? 'Pop quiz' : 'Group stage'}</div>
          <h1 className="section-h">Leaderboard</h1>
          <p className="muted phead__sub">
            {tab === 'quiz'
              ? "Ranked by total pop quiz questions answered correctly, across every matchday."
              : 'Ranked by correct group-stage calls (W/D/L) against real results. Updates automatically as matches are played.'}
          </p>
        </div>
      </header>

      <div className="gfilter">
        <button className="chip" data-on={tab === 'predictions' ? 1 : 0} onClick={() => switchTab('predictions')}>Predictions</button>
        <button className="chip" data-on={tab === 'quiz' ? 1 : 0} onClick={() => switchTab('quiz')}>Quiz</button>
      </div>

      {!data && <p className="muted">Loading leaderboard…</p>}

      {data && isEmpty && (
        <div className="livehead" style={{ justifyContent: 'center', textAlign: 'center' }}>
          <div>
            <div className="livehead__sub">{tab === 'quiz' ? 'No quiz answers yet' : 'No matches finished yet'}</div>
            <p className="muted" style={{ marginTop: 4 }}>
              {tab === 'quiz' ? "Answer today's pop quiz to get on the board." : 'Check back once the first results are in — rankings update automatically.'}
            </p>
          </div>
        </div>
      )}

      {data && !isEmpty && (() => {
        const totalPredictors = data.rows.length;
        const top = data.rows.slice(0, 20);
        const meInTop = top.some(r => r.id === store.uuid);
        const topPct = me ? Math.max(1, Math.round((me.rank / totalPredictors) * 100)) : null;
        const level = topPct == null ? 'mid' : topPct <= 33 ? 'high' : topPct <= 66 ? 'mid' : 'low';
        return (
          <>
            {me && (
              <div className="livehead">
                <div className="livehead__main">
                  <div className="livehead__score display tnum">#{me.rank}<span className="livehead__slash">/{totalPredictors}</span></div>
                  <div className="livehead__sub">your rank · top {topPct}%</div>
                  <div className="livehead__bar"><i data-level={level} style={{ width: (100 - topPct) + '%' }} /></div>
                </div>
                <div className="livehead__stats">
                  <div className="lstat"><b className="tnum">{me.correct}</b><span>correct</span></div>
                  <div className="lstat"><b className="tnum">{tab === 'quiz' ? me.answered : data.total}</b><span>{tab === 'quiz' ? 'answered' : 'played'}</span></div>
                </div>
              </div>
            )}
            <table className="gtable">
              <thead><tr><th></th><th className="col-team">Predictor</th><th>Correct</th></tr></thead>
              <tbody>
                {top.map(r => <LeaderboardRow key={r.id} row={r} isMe={r.id === store.uuid} mode={tab} />)}
                {!meInTop && me && <>
                  <tr><td colSpan={3} className="muted" style={{ textAlign: 'center', padding: 'var(--sp-3)' }}>···</td></tr>
                  <LeaderboardRow row={me} isMe mode={tab} />
                </>}
              </tbody>
            </table>
          </>
        );
      })()}

      {showConfetti && <Confetti key={confettiKey} onDone={() => setShowConfetti(false)} />}
    </div>
  );
}
window.LeaderboardScreen = LeaderboardScreen;
