import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { api, formatCredits } from '../api';

const PODIUM_META = {
  1: {
    label: 'Champion',
    bonus: 'Crown of the Forge',
    placeClass: 'lb-place-1',
  },
  2: {
    label: 'Challenger',
    bonus: 'Silver Crest',
    placeClass: 'lb-place-2',
  },
  3: {
    label: 'Contender',
    bonus: 'Bronze Mark',
    placeClass: 'lb-place-3',
  },
};

function PlayerAvatar({ username, avatarUrl, size = 'md' }) {
  const initials = (username || '?').slice(0, 2).toUpperCase();
  return (
    <div className={`lb-avatar lb-avatar-${size}`} aria-hidden>
      {avatarUrl ? <img src={avatarUrl} alt="" /> : <span>{initials}</span>}
    </div>
  );
}

function WealthBreakdown({ balance, inventoryValue, totalWealth, compact }) {
  if (compact) {
    return (
      <div className="lb-wealth-compact">
        <strong>{formatCredits(totalWealth)} cr</strong>
      </div>
    );
  }
  return (
    <div className="lb-wealth">
      <div className="lb-wealth-total">
        <span className="lb-wealth-label">Total</span>
        <strong>{formatCredits(totalWealth)} cr</strong>
      </div>
      <div className="lb-wealth-parts">
        <span>
          Balance <em>{formatCredits(balance)}</em>
        </span>
        <span>
          Inventory <em>{formatCredits(inventoryValue)}</em>
        </span>
      </div>
    </div>
  );
}

export default function Leaderboard() {
  const navigate = useNavigate();
  const [rows, setRows] = useState([]);
  const [error, setError] = useState('');

  const openPlayer = (username) => {
    navigate(`/player/${encodeURIComponent(username)}`);
  };

  useEffect(() => {
    let cancelled = false;
    (async () => {
      try {
        const data = await api.leaderboard();
        if (!cancelled) setRows(data.leaderboard);
      } catch (err) {
        if (!cancelled) setError(err.message);
      }
    })();
    return () => {
      cancelled = true;
    };
  }, []);

  const top3 = rows.slice(0, 3);
  const rest = rows.slice(3);
  // Podium visual order: 2nd | 1st | 3rd
  const podiumOrder = [top3[1], top3[0], top3[2]].filter(Boolean);

  return (
    <div className="lb-page">
      <div className="section-head">
        <div>
          <h1>Leaderboard</h1>
        </div>
      </div>

      {error && <div className="error">{error}</div>}

      {rows.length === 0 && !error ? (
        <div className="empty">No players yet.</div>
      ) : (
        <>
          {top3.length > 0 && (
            <section className="lb-podium" aria-label="Top three">
              {podiumOrder.map((row) => {
                const meta = PODIUM_META[row.rank];
                return (
                  <button
                    key={row.id}
                    type="button"
                    className={`lb-podium-card ${meta.placeClass}`}
                    onClick={() => openPlayer(row.username)}
                    aria-label={`View ${row.username}'s profile, rank ${row.rank}`}
                  >
                    {row.rank === 1 && (
                      <span className="lb-fire" aria-hidden>
                        <span className="lb-fire-ring" />
                      </span>
                    )}
                    <div className="lb-podium-rank" aria-hidden>
                      #{row.rank}
                    </div>
                    <div className="lb-podium-frame">
                      <PlayerAvatar
                        username={row.username}
                        avatarUrl={row.avatarUrl}
                        size={row.rank === 1 ? 'xl' : 'lg'}
                      />
                    </div>
                    <div className="lb-podium-title">{meta.label}</div>
                    <div className="lb-podium-name">@{row.username}</div>
                    <div className="lb-podium-bonus">{meta.bonus}</div>
                    <WealthBreakdown
                      balance={row.balance}
                      inventoryValue={row.inventoryValue}
                      totalWealth={row.totalWealth}
                    />
                  </button>
                );
              })}
            </section>
          )}

          {rest.length > 0 && (
            <section className="lb-list" aria-label="Rankings">
              <div className="lb-list-head" aria-hidden>
                <span>Rank</span>
                <span>Player</span>
                <span className="lb-list-head-wealth">Total</span>
              </div>
              <ul className="lb-list-rows">
                {rest.map((row) => (
                  <li key={row.id}>
                    <button
                      type="button"
                      className="lb-row"
                      onClick={() => openPlayer(row.username)}
                      aria-label={`View ${row.username}'s profile, rank ${row.rank}`}
                    >
                      <span className="lb-row-rank">{row.rank}</span>
                      <PlayerAvatar
                        username={row.username}
                        avatarUrl={row.avatarUrl}
                        size="sm"
                      />
                      <span className="lb-row-name">@{row.username}</span>
                      <span className="lb-row-meta muted">
                        {row.itemCount} item{row.itemCount === 1 ? '' : 's'}
                      </span>
                      <WealthBreakdown
                        balance={row.balance}
                        inventoryValue={row.inventoryValue}
                        totalWealth={row.totalWealth}
                        compact
                      />
                    </button>
                  </li>
                ))}
              </ul>
            </section>
          )}
        </>
      )}
    </div>
  );
}
