// Leaderboard — wired to PrimaAPI

const Leaderboard = ({ currentUser }) => {
  const [animated, setAnimated] = React.useState(false);
  const [entries, setEntries] = React.useState([]);
  const [loading, setLoading] = React.useState(true);

  React.useEffect(() => {
    PrimaAPI.getLeaderboard(20)
      .then(data => {
        // data = { entries: [...] }
        const list = (data && data.entries) || [];
        setEntries(list);
      })
      .catch(() => setEntries([]))
      .finally(() => setLoading(false));
  }, []);

  React.useEffect(() => {
    if (!loading && entries.length > 0) {
      const t = setTimeout(() => setAnimated(true), 120);
      return () => clearTimeout(t);
    }
  }, [loading, entries.length]);

  // Map API entries to display format
  const board = entries.map((e, i) => ({
    rank: e.rank || i + 1,
    name: e.full_name || "—",
    role: e.designation || "—",
    uploads: e.total_uploads || 0,
    score: e.score || 0,
    you: currentUser && e.user_id === currentUser.id,
  }));

  const max = board.length > 0 ? board[0].score : 1;

  // Derive current user stats from the board
  const myEntry = board.find(e => e.you);
  const myRank = myEntry ? myEntry.rank : "—";
  const myScore = myEntry ? myEntry.score : "—";

  return (
    <div className="page">
      <div className="page-head">
        <div>
          <div className="eyebrow"><Icon name="trophy" size={11} /> Contribution scores</div>
          <h1 className="page-title">Leader<em>board</em></h1>
          <p className="page-sub">Scores reward upload volume <em>and</em> file quality — manager-approved and best-in-class artifacts weight higher than raw uploads.</p>
        </div>
      </div>

      <div className="grid-3" style={{ marginBottom: 24 }}>
        <div className="metric">
          <div className="label">Your rank</div>
          <div className="value" style={{ display: "flex", alignItems: "baseline", gap: 6 }}>
            <span style={{ fontStyle: "italic", color: "var(--accent-deep)" }}>#{myRank}</span>
            <span style={{ fontSize: 14, color: "var(--fg-muted)", fontFamily: "var(--font-ui)", fontWeight: 400 }}>of {board.length}</span>
          </div>
          <div className="delta"><Icon name="trending-up" size={11} /> Based on current scores</div>
        </div>
        <div className="metric">
          <div className="label">Your score</div>
          <div className="value">{myScore}</div>
          <div className="delta">Lifetime contribution</div>
        </div>
        <div className="metric">
          <div className="label">Total uploads</div>
          <div className="value">{myEntry ? myEntry.uploads : "—"}</div>
          <div className="delta">Artifacts contributed</div>
        </div>
      </div>

      {loading ? (
        <div className="empty" style={{ marginTop: 24 }}>
          <div style={{ color: "var(--fg-muted)", fontFamily: "var(--font-mono)", fontSize: 13 }}>Loading…</div>
        </div>
      ) : board.length === 0 ? (
        <div className="empty" style={{ marginTop: 24 }}>
          <div className="icon"><Icon name="trophy" size={20} /></div>
          <h3>No scores yet</h3>
          <p>Upload artifacts to start building your contribution score.</p>
        </div>
      ) : (
        <div className="card">
          <div className="card-head">
            <h3 className="card-title">Contribution leaderboard</h3>
            <div className="pill-group">
              <button data-active="true">All</button>
              <button>Vertical</button>
              <button>My team</button>
            </div>
          </div>
          {board.map(r => {
            const pct = (r.score / max) * 100;
            return (
              <div key={r.rank} className={"lb-row" + (r.you ? " you" : "")}>
                <span className="lb-rank">{r.rank.toString().padStart(2, "0")}</span>
                <Avatar name={r.name} size={32} />
                <div>
                  <div style={{ fontWeight: 500, color: "var(--fg)", fontSize: 14 }}>{r.name}{r.you && <span style={{ marginLeft: 8, fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--accent-deep)", textTransform: "uppercase", letterSpacing: 0.1 }}>You</span>}</div>
                  <div style={{ fontFamily: "var(--font-mono)", fontSize: 10.5, color: "var(--fg-subtle)", textTransform: "uppercase", letterSpacing: 0.08, marginTop: 2 }}>
                    {r.role}
                  </div>
                </div>
                <div className="lb-bar">
                  <div className="lb-bar-fill" style={{ width: animated ? `${pct}%` : "0%" }} />
                </div>
                <div style={{ fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--fg-muted)", textAlign: "right" }}>
                  {r.uploads} files
                </div>
                <div className="lb-score">{r.score}</div>
              </div>
            );
          })}
        </div>
      )}

      <div className="card" style={{ marginTop: 20 }}>
        <div className="card-body" style={{ display: "flex", gap: 24, alignItems: "flex-start" }}>
          <div style={{ flex: 1 }}>
            <div className="eyebrow" style={{ marginBottom: 6 }}><Icon name="sparkles" size={11} /> How scoring works</div>
            <div style={{ fontSize: 13, color: "var(--fg-muted)", lineHeight: 1.55 }}>
              Each upload starts at 5 points. <strong style={{ color: "var(--fg)" }}>Manager-approved</strong> doubles the score. Items flagged <strong style={{ color: "var(--fg)" }}>Best-in-Class</strong> add another 50%. Filling all metadata fields adds a final completeness bonus.
            </div>
          </div>
          <div style={{ width: 220 }}>
            <div className="metric" style={{ background: "var(--bg-sunk)" }}>
              <div className="label">Score multipliers</div>
              <div style={{ display: "flex", flexDirection: "column", gap: 4, marginTop: 8 }}>
                <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12 }}><span>Manager Approved</span><span style={{ fontFamily: "var(--font-mono)" }}>×2.0</span></div>
                <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12 }}><span>Best-in-Class</span><span style={{ fontFamily: "var(--font-mono)" }}>×1.5</span></div>
                <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12 }}><span>Reusable</span><span style={{ fontFamily: "var(--font-mono)" }}>×1.2</span></div>
                <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12 }}><span>Full metadata</span><span style={{ fontFamily: "var(--font-mono)" }}>+10%</span></div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { Leaderboard });
