// Primus IQ — Leaderboard Screen

const ScreenLeaderboard = ({ currentUser }) => {
  const [entries, setEntries] = React.useState([]);
  const [loading, setLoading] = React.useState(false);
  const [myRank, setMyRank] = React.useState("—");
  const [myScore, setMyScore] = React.useState(0);

  React.useEffect(() => {
    setLoading(true);

    PrimusAPI.getLeaderboard(20)
      .then(data => {
        setEntries(data?.entries || []);
        setMyRank(data?.your_rank ?? "—");
        setMyScore(data?.your_score ?? 0);
      })
      .catch(() => {
        setEntries([]);
        setMyRank("—");
        setMyScore(0);
      })
      .finally(() => {
        setLoading(false);
      });
  }, []);

  const board = entries.map((entry, index) => ({
    rank: entry.rank || index + 1,
    userId: entry.user_id,
    name: entry.full_name || 'Unknown user',
    designation: entry.designation || 'Primus Partners',
    uploads: entry.total_uploads || 0,
    score: entry.score || 0,
    isCurrentUser: currentUser && (entry.user_id === currentUser.id || entry.full_name === currentUser.full_name),
  }));
  const currentEntry = board.find(entry => entry.isCurrentUser);

  return (
    <div style={contentArea}>
      <div className="mobile-p-16" style={{ padding: '40px 48px 48px', maxWidth: 980, margin: '0 auto' }}>
        <div className="mobile-stack" style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 24, marginBottom: 24 }}>
          <div>
            <div className="t-eyebrow" style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 8 }}>
              <PIcon name="trophy" size={13} color="var(--maroon)" /> Contributions
            </div>
            <h1 className="serif" style={{ fontSize: 28, fontWeight: 500, margin: 0, letterSpacing: '-0.02em' }}>Leaderboard</h1>
            <p style={{ fontSize: 13, color: 'var(--mute)', margin: '6px 0 0' }}>
              Scores come from artifacts added to projects and the firm library.
            </p>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 130px)', gap: 10 }}>
            <LeaderboardMetric label="Your rank" value={myRank ? `#${myRank}` : "-"}/>
            <LeaderboardMetric label="Your score" value={myScore}/>
          </div>
        </div>

        {loading ? (
          <LeaderboardEmpty text="Loading leaderboard..." />
        ) : board.length === 0 ? (
          <LeaderboardEmpty text="No scores yet. Add artifacts to start the leaderboard." />
        ) : (
          <div style={{ background: 'white', border: '1px solid var(--line)', borderRadius: 14, overflow: 'hidden', boxShadow: 'var(--shadow-xs)' }}>
            <div className="leaderboard-grid-row" style={{
              padding: '12px 18px', borderBottom: '1px solid var(--line)',
              fontSize: 10, fontWeight: 700, color: 'var(--mute)', letterSpacing: '0.08em', textTransform: 'uppercase',
            }}>
              <span>Rank</span>
              <span>Person</span>
              <span style={{ textAlign: 'center' }}>Uploads</span>
              <span style={{ textAlign: 'center' }}>Score
              </span>
            </div>
            {board.map((entry, index) => {
              const initials = entry.name.split(' ').filter(Boolean).map(w => w[0].toUpperCase()).slice(0, 2).join('') || '?';
              return (
                <div key={entry.userId} className="leaderboard-grid-row" style={{
                  alignItems: 'center', gap: 0, padding: '14px 18px',
                  borderBottom: index === board.length - 1 ? 'none' : '1px solid var(--line)',
                  background: entry.isCurrentUser ? 'var(--maroon-06)' : 'white',
                }}>
                  <div style={{ fontSize: 18, fontWeight: 700, color: entry.isCurrentUser ? 'var(--maroon)' : 'var(--mute)' }}>
                    #{entry.rank}
                  </div>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 12, minWidth: 0 }}>
                    <div className="avatar" style={{ width: 34, height: 34, fontSize: 12, borderColor: entry.isCurrentUser ? 'var(--maroon-10)' : 'var(--bg-card)' }}>{initials}</div>
                    <div style={{ minWidth: 0 }}>
                      <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--ink)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                        {entry.name}
                        {entry.isCurrentUser && <span style={{ marginLeft: 8, fontSize: 10, color: 'var(--maroon)', fontWeight: 700, letterSpacing: '0.06em', textTransform: 'uppercase' }}>You</span>}
                      </div>
                      <div className="mobile-hide" style={{ fontSize: 11, color: 'var(--mute)', marginTop: 2, textTransform: 'capitalize' }}>{entry.designation}</div>
                    </div>
                  </div>
                  <div style={{ fontSize: 13, color: 'var(--ink-2)',  textAlign: 'center', display: 'flex', justifyContent: 'center', alignItems: 'center', }}>
                    {entry.uploads}
                    <span className="mobile-hide">&nbsp;files</span>
                  </div>
                  <div style={{ fontSize: 15, fontWeight: 700, color: 'var(--ink)', textAlign: 'center' }}>{entry.score}</div>
                </div>
              );
            })}
          </div>
        )}
      </div>
    </div>
  );
};

const LeaderboardMetric = ({ label, value }) => (
  <div style={{ background: 'white', border: '1px solid var(--line)', borderRadius: 12, padding: '12px 14px' }}>
    <div className="t-eyebrow" style={{ fontSize: 9 }}>{label}</div>
    <div style={{ fontSize: 22, fontWeight: 700, color: 'var(--maroon)', marginTop: 4 }}>{value}</div>
  </div>
);

const LeaderboardEmpty = ({ text }) => (
  <div style={{ padding: 56, borderRadius: 14, background: 'white', border: '1px dashed var(--line-2)', textAlign: 'center', fontSize: 13, color: 'var(--mute)' }}>
    {text}
  </div>
);

Object.assign(window, {
  ScreenLeaderboard,
  LeaderboardMetric,
  LeaderboardEmpty,
});
