import { useState, useEffect, useCallback, useRef } from 'react';
import './lolstats.css';

// ── Types ──

interface RegionInfo { code: string; label: string; }
interface TierInfo { tier: string | null; division: number | null; lp: number | null; tier_image_url?: string; }
interface LeagueStat { game_type: string; win: number | null; lose: number | null; is_hot_streak: boolean; tier_info: TierInfo; }
interface LadderRank { rank: number | null; total: number | null; }
interface ChampionStat { champion_name: string; id: number; play: number; win: number; lose: number; kill: number; death: number; assist: number; }
interface MostChampions { game_type: string; play: number; win: number; lose: number; champion_stats: ChampionStat[]; }
interface GameModeInfo { key: string; label: string; }
interface ChampionTierEntry {
  champion_id: number; champion_name: string; tier: number; rank: number;
  win_rate: number | null; pick_rate: number; ban_rate: number | null;
  kda: number | null; play: number;
  average_placement?: number; first_place_rate?: number;
}

interface SummonerProfile {
  game_name: string; tagline: string; level: number; profile_image_url: string;
  league_stats: LeagueStat[]; ladder_rank: LadderRank; most_champions: MostChampions;
  updated_at: string;
}

interface MatchParticipant {
  champion_name: string; champion_id: number; items: number[]; items_names: string[];
  position: string; team_key: string; spells: number[];
  stats: {
    kill: number; death: number; assist: number; minion_kill: number; neutral_minion_kill: number;
    gold_earned: number; total_damage_dealt_to_champions: number; total_damage_taken: number;
    ward_place: number; vision_wards_bought_in_game: number; champion_level: number;
    op_score: number; op_score_rank: number; result: string;
  };
  summoner: { game_name: string; tagline: string; };
}

interface TeamStat {
  key: string; banned_champions_names: string[];
  game_stat: { is_win: boolean; baron_kill: number; dragon_kill: number; tower_kill: number; champion_kill: number; gold_earned: number; };
}

interface MatchEntry {
  id: string; created_at: string; game_length_second: number; game_type: string; game_map: string;
  average_tier_info?: { tier: string; division: number };
  participants: MatchParticipant[]; teams: TeamStat[];
}

interface RecentSearch {
  game_name: string; tag_line: string; region: string;
  profile_image_url: string; level: number; tier?: string; rank?: string; timestamp: number;
}

// ── Constants ──

const TIER_COLORS: Record<string, string> = {
  IRON: '#6b6b6b', BRONZE: '#8c6239', SILVER: '#8c8c8c', GOLD: '#d4a017',
  PLATINUM: '#28b29e', EMERALD: '#1e9e5e', DIAMOND: '#576cce',
  MASTER: '#9d48e0', GRANDMASTER: '#e44c3e', CHALLENGER: '#f4c874',
};

const QUEUE_NAMES: Record<string, string> = {
  SOLORANKED: 'Ranked Solo', FLEXRANKED: 'Ranked Flex',
  NORMAL: 'Normal', ARAM: 'ARAM', ARENA: 'Arena', URF: 'URF',
  BOT: 'Co-op vs AI',
};

const DDRAGON = 'https://ddragon.leagueoflegends.com/cdn/15.5.1/img';

// ── Helpers ──

function champImg(name: string): string {
  return `${DDRAGON}/champion/${name}.png`;
}

function timeAgo(iso: string): string {
  const sec = Math.floor((Date.now() - new Date(iso).getTime()) / 1000);
  if (sec < 60) return `${sec}s`;
  if (sec < 3600) return `${Math.floor(sec / 60)}m`;
  if (sec < 86400) return `${Math.floor(sec / 3600)}h`;
  return `${Math.floor(sec / 86400)}d`;
}

function fmtDuration(secs: number): string {
  const m = Math.floor(secs / 60);
  const s = secs % 60;
  return `${m}:${String(s).padStart(2, '0')}`;
}

function kdaRatio(k: number, d: number, a: number): string {
  if (d === 0) return 'Perfect';
  return ((k + a) / d).toFixed(2);
}

function winRate(w: number, l: number): number {
  const total = w + l;
  return total > 0 ? Math.round((w / total) * 100) : 0;
}

function tierDisplay(tier: string | null, div: number | null): string {
  if (!tier) return 'Unranked';
  const roman = ['', 'I', 'II', 'III', 'IV'];
  return `${tier.charAt(0)}${tier.slice(1).toLowerCase()}${div ? ' ' + (roman[div] ?? div) : ''}`;
}

// ── Component ──

export default function LolstatsTab({ data }: { data: any }) {
  const [searchText, setSearchText] = useState('');
  const [region, setRegion] = useState('EUW');
  const [regions, setRegions] = useState<RegionInfo[]>([]);

  const [profile, setProfile] = useState<SummonerProfile | null>(null);
  const [matches, setMatches] = useState<MatchEntry[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [recentSearches, setRecentSearches] = useState<RecentSearch[]>([]);
  const [expandedMatch, setExpandedMatch] = useState<string | null>(null);
  const [matchDetails, setMatchDetails] = useState<Record<string, MatchEntry>>({});
  const [loadingMore, setLoadingMore] = useState(false);
  const [renewing, setRenewing] = useState(false);
  const [lastUpdated, setLastUpdated] = useState<string | null>(null);

  // Tier list state
  const [tierMode, setTierMode] = useState('aram');
  const [tierRegion, setTierRegion] = useState('EUW');
  const [tierList, setTierList] = useState<ChampionTierEntry[]>([]);
  const [tierLoading, setTierLoading] = useState(false);
  const [tierError, setTierError] = useState<string | null>(null);
  const [gameModes, setGameModes] = useState<GameModeInfo[]>([]);
  const [tierSearch, setTierSearch] = useState('');
  const [showAllTiers, setShowAllTiers] = useState(false);

  const searchRef = useRef<HTMLInputElement>(null);
  const currentSearchRef = useRef<{ gameName: string; tagLine: string; region: string } | null>(null);

  // Load regions + modes
  useEffect(() => {
    fetch('/api/lolstats/regions').then(r => r.json()).then(setRegions).catch(() => {});
    fetch('/api/lolstats/recent').then(r => r.json()).then(setRecentSearches).catch(() => {});
    fetch('/api/lolstats/modes').then(r => r.json()).then(setGameModes).catch(() => {});
  }, []);

  // Load tier list when mode/region changes
  useEffect(() => {
    if (!tierMode) return;
    setTierLoading(true);
    setTierError(null);
    setShowAllTiers(false);
    fetch(`/api/lolstats/tierlist?mode=${tierMode}&region=${tierRegion}`)
      .then(r => {
        if (!r.ok) throw new Error(`HTTP ${r.status}`);
        return r.json();
      })
      .then(data => setTierList(data.champions ?? []))
      .catch(e => setTierError(e.message))
      .finally(() => setTierLoading(false));
  }, [tierMode, tierRegion]);

  // SSE data
  useEffect(() => {
    if (!data) return;
    if (data.recentSearches) setRecentSearches(data.recentSearches);
    if (data.regions && !regions.length) setRegions(data.regions);
  }, [data]);

  // ── Renewal ──
  const doRenew = useCallback(async (gameName: string, tagLine: string, searchRegion: string) => {
    setRenewing(true);
    try {
      const qs = `gameName=${encodeURIComponent(gameName)}&tagLine=${encodeURIComponent(tagLine)}&region=${searchRegion}`;
      const res = await fetch(`/api/lolstats/renew?${qs}`, { method: 'POST' });
      if (res.ok) {
        const data = await res.json();
        if (data.last_updated_at) setLastUpdated(data.last_updated_at);
        return data.renewed ?? false;
      }
    } catch {}
    setRenewing(false);
    return false;
  }, []);

  // ── Search ──
  const doSearch = useCallback(async (gn?: string, tl?: string, rg?: string, skipRenew = false) => {
    let gameName = gn ?? '';
    let tagLine = tl ?? '';
    const searchRegion = rg ?? region;

    if (!gameName) {
      // Parse from search text "Name#Tag"
      const parts = searchText.split('#');
      gameName = parts[0]?.trim() ?? '';
      tagLine = parts[1]?.trim() ?? '';
    }

    if (!gameName || !tagLine) {
      setError('Bitte im Format Name#Tag eingeben');
      return;
    }

    setLoading(true);
    setError(null);
    setProfile(null);
    setMatches([]);
    setExpandedMatch(null);
    setMatchDetails({});

    // Track current search for update button
    currentSearchRef.current = { gameName, tagLine, region: searchRegion };

    // Auto-renew on first search (trigger op.gg refresh in background)
    if (!skipRenew) {
      doRenew(gameName, tagLine, searchRegion).finally(() => setRenewing(false));
    }

    try {
      const qs = `gameName=${encodeURIComponent(gameName)}&tagLine=${encodeURIComponent(tagLine)}&region=${searchRegion}`;

      // Fetch profile and matches in parallel
      const [profileRes, matchesRes] = await Promise.all([
        fetch(`/api/lolstats/profile?${qs}`),
        fetch(`/api/lolstats/matches?${qs}&limit=10`),
      ]);

      if (!profileRes.ok) {
        const err = await profileRes.json();
        throw new Error(err.error ?? `Fehler ${profileRes.status}`);
      }

      const profileData = await profileRes.json();
      setProfile(profileData);
      if (profileData.updated_at) setLastUpdated(profileData.updated_at);

      if (matchesRes.ok) {
        const matchesData = await matchesRes.json();
        setMatches(Array.isArray(matchesData) ? matchesData : []);
      }
    } catch (e: any) {
      setError(e.message);
    }
    setLoading(false);
  }, [searchText, region, doRenew]);

  // ── Manual Update (renew + re-fetch) ──
  const doUpdate = useCallback(async () => {
    const cur = currentSearchRef.current;
    if (!cur || renewing) return;
    setRenewing(true);
    try {
      await doRenew(cur.gameName, cur.tagLine, cur.region);
      // Wait a moment for op.gg MCP to pick up the renewed data
      await new Promise(r => setTimeout(r, 1500));
      // Re-fetch
      await doSearch(cur.gameName, cur.tagLine, cur.region, true);
    } finally {
      setRenewing(false);
    }
  }, [doRenew, doSearch, renewing]);

  // ── Load more matches ──
  const loadMore = useCallback(async () => {
    if (!profile || loadingMore) return;
    setLoadingMore(true);
    try {
      const qs = `gameName=${encodeURIComponent(profile.game_name)}&tagLine=${encodeURIComponent(profile.tagline)}&region=${region}&limit=20`;
      const res = await fetch(`/api/lolstats/matches?${qs}`);
      if (res.ok) {
        const data = await res.json();
        setMatches(Array.isArray(data) ? data : []);
      }
    } catch {}
    setLoadingMore(false);
  }, [profile, region, loadingMore]);

  // ── Expand match detail ──
  const toggleMatch = useCallback(async (match: MatchEntry) => {
    if (expandedMatch === match.id) {
      setExpandedMatch(null);
      return;
    }
    setExpandedMatch(match.id);

    // If we already have full detail (10 participants), skip fetch
    if (match.participants?.length >= 10 || matchDetails[match.id]) return;

    try {
      const qs = `region=${region}&createdAt=${encodeURIComponent(match.created_at)}`;
      const res = await fetch(`/api/lolstats/match/${encodeURIComponent(match.id)}?${qs}`);
      if (res.ok) {
        const detail = await res.json();
        setMatchDetails(prev => ({ ...prev, [match.id]: detail }));
      }
    } catch {}
  }, [expandedMatch, matchDetails, region]);

  // Recent search click
  const onRecentClick = useCallback((r: RecentSearch) => {
    setSearchText(`${r.game_name}#${r.tag_line}`);
    setRegion(r.region);
    doSearch(r.game_name, r.tag_line, r.region);
  }, [doSearch]);

  // ── Find "me" in participants ──
  const findMe = useCallback((match: MatchEntry): MatchParticipant | null => {
    if (!profile) return match.participants?.[0] ?? null;
    const myName = profile.game_name.toLowerCase();
    return match.participants?.find(
      p => p.summoner?.game_name?.toLowerCase() === myName,
    ) ?? match.participants?.[0] ?? null;
  }, [profile]);

  // ── Render Match Row ──
  const renderMatch = (match: MatchEntry) => {
    const me = findMe(match);
    if (!me) return null;

    const isWin = me.stats?.result === 'WIN';
    const kda = kdaRatio(me.stats.kill, me.stats.death, me.stats.assist);
    const cs = (me.stats.minion_kill ?? 0) + (me.stats.neutral_minion_kill ?? 0);
    const csPerMin = match.game_length_second > 0 ? (cs / (match.game_length_second / 60)).toFixed(1) : '0';
    const isExpanded = expandedMatch === match.id;
    const detail = matchDetails[match.id] ?? (match.participants?.length >= 10 ? match : null);

    return (
      <div key={match.id}>
        <div
          className={`lol-match ${isWin ? 'win' : 'loss'}`}
          onClick={() => toggleMatch(match)}
        >
          <div className="lol-match-result">{isWin ? 'W' : 'L'}</div>

          <div className="lol-match-champ">
            <img src={champImg(me.champion_name)} alt={me.champion_name} title={me.champion_name} />
            <span className="lol-match-champ-level">{me.stats.champion_level}</span>
          </div>

          <div className="lol-match-kda">
            <div className="lol-match-kda-nums">{me.stats.kill}/{me.stats.death}/{me.stats.assist}</div>
            <div className={`lol-match-kda-ratio ${kda === 'Perfect' ? 'perfect' : Number(kda) >= 4 ? 'great' : ''}`}>
              {kda} KDA
            </div>
          </div>

          <div className="lol-match-stats">
            <span>{cs} CS ({csPerMin}/m)</span>
            <span>{me.stats.ward_place} wards</span>
          </div>

          <div className="lol-match-items">
            {(me.items_names ?? []).slice(0, 7).map((item, i) =>
              item ? (
                <img key={i} src={champImg('Aatrox')} alt={item} title={item}
                  style={{ background: 'var(--bg-deep)' }}
                  onError={e => { (e.target as HTMLImageElement).style.display = 'none'; }}
                />
              ) : <div key={i} className="lol-match-item-empty" />
            )}
          </div>

          <div className="lol-match-meta">
            <div className="lol-match-duration">{fmtDuration(match.game_length_second)}</div>
            <div className="lol-match-queue">{QUEUE_NAMES[match.game_type] ?? match.game_type}</div>
            <div className="lol-match-ago">{timeAgo(match.created_at)} ago</div>
          </div>
        </div>

        {/* Expanded detail */}
        {isExpanded && detail && (
          <div className="lol-match-detail">
            {renderMatchDetail(detail, me.summoner?.game_name)}
          </div>
        )}
      </div>
    );
  };

  // ── Render Match Detail (all 10 players) ──
  const renderMatchDetail = (match: MatchEntry, myName?: string) => {
    const blue = match.participants?.filter(p => p.team_key === 'BLUE') ?? [];
    const red = match.participants?.filter(p => p.team_key === 'RED') ?? [];
    const blueWin = match.teams?.find(t => t.key === 'BLUE')?.game_stat?.is_win;

    const renderTeam = (team: MatchParticipant[], isWin: boolean | undefined, label: string) => (
      <div className="lol-match-detail-team">
        <div className={`lol-match-detail-team-header ${isWin ? 'win' : 'loss'}`}>
          {label} — {isWin ? 'Victory' : 'Defeat'}
        </div>
        {team.map((p, i) => {
          const isMe = p.summoner?.game_name?.toLowerCase() === myName?.toLowerCase();
          const cs = (p.stats?.minion_kill ?? 0) + (p.stats?.neutral_minion_kill ?? 0);
          return (
            <div key={i} className={`lol-detail-row ${isMe ? 'me' : ''}`}>
              <img className="lol-detail-champ" src={champImg(p.champion_name)} alt={p.champion_name} />
              <span className="lol-detail-name" title={`${p.summoner?.game_name}#${p.summoner?.tagline}`}>
                {p.summoner?.game_name ?? p.champion_name}
              </span>
              <span className="lol-detail-kda">{p.stats?.kill}/{p.stats?.death}/{p.stats?.assist}</span>
              <span className="lol-detail-cs">{cs} CS</span>
              <span className="lol-detail-dmg">{((p.stats?.total_damage_dealt_to_champions ?? 0) / 1000).toFixed(1)}k</span>
              <span className="lol-detail-gold">{((p.stats?.gold_earned ?? 0) / 1000).toFixed(1)}k</span>
            </div>
          );
        })}
      </div>
    );

    return (
      <>
        {renderTeam(blue, blueWin, 'Blue Team')}
        {renderTeam(red, blueWin === undefined ? undefined : !blueWin, 'Red Team')}
      </>
    );
  };

  // ── Main Render ──
  return (
    <div className="lol-container">
      {/* Search */}
      <div className="lol-search">
        <input
          ref={searchRef}
          className="lol-search-input"
          placeholder="Summoner Name#Tag"
          value={searchText}
          onChange={e => setSearchText(e.target.value)}
          onKeyDown={e => e.key === 'Enter' && doSearch()}
        />
        <select className="lol-search-region" value={region} onChange={e => setRegion(e.target.value)}>
          {regions.map(r => <option key={r.code} value={r.code}>{r.code}</option>)}
        </select>
        <button className="lol-search-btn" onClick={() => doSearch()} disabled={loading}>
          {loading ? '...' : 'Search'}
        </button>
      </div>

      {/* Recent searches */}
      {recentSearches.length > 0 && (
        <div className="lol-recent">
          {recentSearches.map((r, i) => (
            <button key={i} className="lol-recent-chip" onClick={() => onRecentClick(r)}>
              {r.profile_image_url && <img src={r.profile_image_url} alt="" />}
              {r.game_name}#{r.tag_line}
              {r.tier && <span className="lol-recent-tier" style={{ color: TIER_COLORS[r.tier] }}>{r.tier}</span>}
            </button>
          ))}
        </div>
      )}

      {/* Error */}
      {error && <div className="lol-error">{error}</div>}

      {/* Loading */}
      {loading && (
        <div className="lol-loading">
          <div className="lol-spinner" />
          Lade Profil...
        </div>
      )}

      {/* Profile */}
      {profile && !loading && (
        <>
          <div className="lol-profile">
            <img className="lol-profile-icon" src={profile.profile_image_url} alt="" />
            <div className="lol-profile-info">
              <h2>{profile.game_name}<span>#{profile.tagline}</span></h2>
              <div className="lol-profile-level">Level {profile.level}</div>
              {profile.ladder_rank?.rank && (
                <div className="lol-profile-ladder">
                  Ladder Rank #{profile.ladder_rank.rank.toLocaleString()} / {profile.ladder_rank.total?.toLocaleString()}
                </div>
              )}
              {lastUpdated && (
                <div className="lol-profile-updated">Updated {timeAgo(lastUpdated)} ago</div>
              )}
            </div>
            <button
              className={`lol-update-btn ${renewing ? 'renewing' : ''}`}
              onClick={doUpdate}
              disabled={renewing}
              title="Refresh data from Riot servers"
            >
              <span className="lol-update-icon">{renewing ? '⟳' : '↻'}</span>
              {renewing ? 'Updating...' : 'Update'}
            </button>
          </div>

          {/* Ranked Cards */}
          <div className="lol-ranked-row">
            {(profile.league_stats ?? [])
              .filter(ls => ls.game_type === 'SOLORANKED' || ls.game_type === 'FLEXRANKED')
              .map(ls => {
                const t = ls.tier_info;
                const hasRank = !!t?.tier;
                const tierColor = TIER_COLORS[t?.tier ?? ''] ?? 'var(--text-normal)';
                return (
                  <div
                    key={ls.game_type}
                    className={`lol-ranked-card ${hasRank ? 'has-rank' : ''}`}
                    style={{ '--tier-color': tierColor } as React.CSSProperties}
                  >
                    <div className="lol-ranked-type">
                      {ls.game_type === 'SOLORANKED' ? 'Ranked Solo/Duo' : 'Ranked Flex'}
                    </div>
                    {hasRank ? (
                      <>
                        <div className="lol-ranked-tier" style={{ color: tierColor }}>
                          {tierDisplay(t.tier, t.division)}
                          <span className="lol-ranked-lp">{t.lp} LP</span>
                        </div>
                        <div className="lol-ranked-record">
                          {ls.win}W {ls.lose}L
                          <span className="lol-ranked-wr">({winRate(ls.win ?? 0, ls.lose ?? 0)}%)</span>
                          {ls.is_hot_streak && <span className="lol-ranked-streak">🔥</span>}
                        </div>
                      </>
                    ) : (
                      <div className="lol-ranked-tier">Unranked</div>
                    )}
                  </div>
                );
              })}
          </div>

          {/* Most Champions */}
          {profile.most_champions?.champion_stats?.length > 0 && (
            <>
              <div className="lol-section-title">Top Champions</div>
              <div className="lol-champs">
                {profile.most_champions.champion_stats.slice(0, 7).map(cs => {
                  const wr = winRate(cs.win, cs.lose);
                  const avgKda = cs.play > 0
                    ? kdaRatio(cs.kill / cs.play, cs.death / cs.play, cs.assist / cs.play)
                    : '0';
                  return (
                    <div key={cs.champion_name} className="lol-champ-card">
                      <img className="lol-champ-icon" src={champImg(cs.champion_name)} alt={cs.champion_name} />
                      <div>
                        <div className="lol-champ-name">{cs.champion_name}</div>
                        <div className="lol-champ-stats">{cs.play} games · {wr}% WR</div>
                        <div className="lol-champ-kda">{avgKda} KDA</div>
                      </div>
                    </div>
                  );
                })}
              </div>
            </>
          )}

          {/* Match History */}
          {matches.length > 0 && (
            <>
              <div className="lol-section-title">Match History</div>
              <div className="lol-matches">
                {matches.map(m => renderMatch(m))}
              </div>
              {matches.length < 20 && (
                <button className="lol-load-more" onClick={loadMore} disabled={loadingMore}>
                  {loadingMore ? 'Laden...' : 'Mehr laden'}
                </button>
              )}
            </>
          )}
        </>
      )}

      {/* Empty state */}
      {!profile && !loading && !error && (
        <div className="lol-empty">
          <div className="lol-empty-icon">⚔️</div>
          <h3>League of Legends Stats</h3>
          <p>Gib einen Summoner Name#Tag ein und wähle die Region</p>
        </div>
      )}

      {/* Champion Tier List — always visible */}
      <div className="lol-tier-section">
        <div className="lol-section-title">Champion Tier List</div>

        <div className="lol-tier-controls">
          <div className="lol-tier-modes">
            {gameModes.map(m => (
              <button
                key={m.key}
                className={`lol-tier-mode-btn ${tierMode === m.key ? 'active' : ''}`}
                onClick={() => setTierMode(m.key)}
              >
                {m.label}
              </button>
            ))}
          </div>
          <select
            className="lol-search-region"
            value={tierRegion}
            onChange={e => setTierRegion(e.target.value)}
          >
            {regions.map(r => <option key={r.code} value={r.code}>{r.code}</option>)}
          </select>
          <input
            className="lol-tier-filter"
            placeholder="Filter champion..."
            value={tierSearch}
            onChange={e => setTierSearch(e.target.value)}
          />
        </div>

        {tierLoading && (
          <div className="lol-loading">
            <div className="lol-spinner" />
            Lade Tier List...
          </div>
        )}
        {tierError && <div className="lol-error">{tierError}</div>}

        {!tierLoading && !tierError && tierList.length > 0 && (
          <>
            <div className="lol-tier-table">
              <div className="lol-tier-header">
                <span className="lol-tier-col-rank">#</span>
                <span className="lol-tier-col-champ">Champion</span>
                <span className="lol-tier-col-tier">Tier</span>
                <span className="lol-tier-col-wr">{tierMode === 'arena' ? 'Win' : 'Win %'}</span>
                <span className="lol-tier-col-pr">Pick %</span>
                {tierMode !== 'arena' && <span className="lol-tier-col-br">Ban %</span>}
                <span className="lol-tier-col-kda">{tierMode === 'arena' ? 'Avg Place' : 'KDA'}</span>
              </div>
              {tierList
                .filter(c => !tierSearch || c.champion_name.toLowerCase().includes(tierSearch.toLowerCase()))
                .slice(0, showAllTiers ? undefined : 50)
                .map(c => {
                  const tierLabels = ['OP', '1', '2', '3', '4', '5'];
                  return (
                    <div key={c.champion_id} className={`lol-tier-row tier-${c.tier}`}>
                      <span className="lol-tier-col-rank">{c.rank}</span>
                      <span className="lol-tier-col-champ">
                        <img src={champImg(c.champion_name)} alt={c.champion_name} />
                        {c.champion_name}
                      </span>
                      <span className={`lol-tier-col-tier tier-badge-${c.tier}`}>
                        {tierLabels[c.tier] ?? c.tier}
                      </span>
                      <span className="lol-tier-col-wr">
                        {c.win_rate != null ? `${(c.win_rate * 100).toFixed(1)}%` : '-'}
                      </span>
                      <span className="lol-tier-col-pr">
                        {(c.pick_rate * 100).toFixed(1)}%
                      </span>
                      {tierMode !== 'arena' && (
                        <span className="lol-tier-col-br">
                          {c.ban_rate != null ? `${(c.ban_rate * 100).toFixed(1)}%` : '-'}
                        </span>
                      )}
                      <span className="lol-tier-col-kda">
                        {tierMode === 'arena'
                          ? (c.average_placement?.toFixed(1) ?? '-')
                          : (c.kda?.toFixed(2) ?? '-')}
                      </span>
                    </div>
                  );
                })}
            </div>
            {!showAllTiers && tierList.length > 50 && (
              <button className="lol-load-more" onClick={() => setShowAllTiers(true)}>
                Alle {tierList.length} Champions anzeigen
              </button>
            )}
          </>
        )}
      </div>
    </div>
  );
}
