// Trophy Cabinet
// Replaces old Achievements screen. Tabs: Up Next | Teams | Nations | Leagues | General

function AchievementsScreen() {
  const T = window.T;
  const [unlocked, setUnlocked] = React.useState(null);
  const [sessions, setSessions] = React.useState(null);
  const [loading, setLoading] = React.useState(true);
  const [tab, setTab] = React.useState('upnext');
  const [detailGroup, setDetailGroup] = React.useState(null);

  React.useEffect(() => {
    let mounted = true;
    (async () => {
      try {
        // First load existing data
        const [ua, sess] = await Promise.all([
          window.fetchMyAchievements(),
          window.fetchMySessions(),
        ]);
        if (!mounted) return;

        // Auto-check: see if user has earned any trophies based on their session history
        // that aren't already unlocked. This catches up users after migrations.
        if (sess && sess.length > 0 && window.checkAchievements) {
          try {
            const newly = await window.checkAchievements(sess);
            if (newly.length > 0) {
              // Re-fetch to include new unlocks
              const refreshed = await window.fetchMyAchievements();
              if (mounted) {
                const set = {};
                refreshed.forEach(a => { set[a.achievement_id] = a.unlocked_at; });
                setUnlocked(set);
                setSessions(sess);
                setLoading(false);
                return;
              }
            }
          } catch (e) {
            console.error('Trophy auto-check failed:', e);
          }
        }

        const unlockedSet = {};
        ua.forEach(a => { unlockedSet[a.achievement_id] = a.unlocked_at; });
        setUnlocked(unlockedSet);
        setSessions(sess || []);
      } finally {
        if (mounted) setLoading(false);
      }
    })();
    return () => { mounted = false; };
  }, []);

  const trophies = window.TROPHY_DEFS || [];

  // Group all trophies by their "badge key" — i.e. team/nation/league/general identifier
  // Each badge has 4 tiers (bronze/silver/gold/diamond)
  // Show the highest earned tier per badge, with progress shown for next
  const badgeGroups = React.useMemo(() => {
    if (!unlocked) return null;
    const groups = {};
    trophies.forEach(t => {
      // Group key: category + name
      const key = `${t.category}__${t.name}`;
      if (!groups[key]) {
        groups[key] = {
          category: t.category,
          name: t.name,
          icon: t.icon,
          tiers: {},
          highestEarned: null,
          nextTier: null,
        };
      }
      groups[key].tiers[t.tier] = {
        ...t,
        isUnlocked: !!unlocked[t.id],
      };
    });
    // Determine highest earned tier per badge (gold > silver > bronze, diamond is highest)
    const TIER_ORDER = ['diamond', 'gold', 'silver', 'bronze'];
    Object.values(groups).forEach(g => {
      for (const tier of TIER_ORDER) {
        if (g.tiers[tier]?.isUnlocked) {
          g.highestEarned = tier;
          break;
        }
      }
      // Next tier to earn
      if (g.highestEarned === 'diamond') g.nextTier = null;
      else if (g.highestEarned === 'gold') g.nextTier = 'diamond';
      else if (g.highestEarned === 'silver') g.nextTier = 'gold';
      else if (g.highestEarned === 'bronze') g.nextTier = 'silver';
      else g.nextTier = 'bronze';
    });
    return groups;
  }, [unlocked, trophies]);

  const totalUnlocked = unlocked ? Object.keys(unlocked).length : 0;
  const totalPossible = trophies.length;

  if (loading) {
    return (
      <Content>
        <AppHeader left={<PageWordmark text="TROPHIES"/>}/>
        <div style={{textAlign:'center', padding:'40px 0', color:T.textSec}}>Loading…</div>
      </Content>
    );
  }

  const groups = Object.values(badgeGroups || {});

  // Categorize
  const byCategory = {
    teams: groups.filter(g => g.category === 'teams'),
    nations: groups.filter(g => g.category === 'nations'),
    leagues: groups.filter(g => g.category === 'leagues'),
    general: groups.filter(g => g.category === 'general'),
  };

  // "Up Next" — closest to next-tier completion based on current progress
  // For now, just show: any group where they earned bronze but not silver yet,
  // or silver but not gold. Surfaces the natural next step.
  const upNext = groups
    .filter(g => g.nextTier && g.highestEarned) // already earned at least bronze, can earn next
    .slice(0, 6);
  // Plus a few unstarted groups to suggest where to begin
  const fresh = groups.filter(g => !g.highestEarned).slice(0, 6);

  return (
    <Content>
      <AppHeader left={<PageWordmark text="TROPHIES"/>}/>

      {/* Header summary */}
      <div style={{
        background:T.card, borderRadius:16, padding:'14px 18px', marginBottom:14,
      }}>
        <div style={{
          display:'flex', alignItems:'baseline', gap:8,
          fontFamily:'Bakbak One, sans-serif',
        }}>
          <span style={{fontSize:30, color:T.gold400, letterSpacing:'0.02em', lineHeight:1}}>
            {totalUnlocked}
          </span>
          <span style={{fontSize:16, color:T.textMute}}>/ {totalPossible}</span>
        </div>
        <div style={{fontSize:12, color:T.textSec, fontFamily:'DM Sans', marginTop:4}}>
          Trophies in your cabinet
        </div>
        <div style={{height:3, background:T.border, borderRadius:100, overflow:'hidden', marginTop:10}}>
          <div style={{
            width:`${totalPossible > 0 ? (totalUnlocked/totalPossible)*100 : 0}%`,
            height:'100%', background:`linear-gradient(90deg, ${T.gold600}, ${T.gold400})`,
            transition:'width 600ms cubic-bezier(0.2,0.9,0.3,1)',
          }}/>
        </div>
      </div>

      {/* Category tabs */}
      <div className="no-scrollbar" style={{display:'flex', gap:8, marginBottom:18, overflowX:'auto', paddingBottom:4}}>
        {[
          { id:'upnext',  label:'Up Next' },
          { id:'teams',   label:`Teams (${byCategory.teams.filter(g => g.highestEarned === 'diamond').length}/${byCategory.teams.length})` },
          { id:'nations', label:`Nations (${byCategory.nations.filter(g => g.highestEarned === 'diamond').length}/${byCategory.nations.length})` },
          { id:'leagues', label:`Leagues (${byCategory.leagues.filter(g => g.highestEarned === 'diamond').length}/${byCategory.leagues.length})` },
          { id:'general', label:`General (${byCategory.general.filter(g => g.highestEarned === 'diamond').length}/${byCategory.general.length})` },
        ].map(t => (
          <button key={t.id} onClick={() => setTab(t.id)} style={{
            background: tab === t.id ? 'rgba(232,184,32,0.15)' : T.card,
            border:`1px solid ${tab === t.id ? T.gold600 : T.border}`,
            borderRadius:100, padding:'7px 14px',
            fontSize:11, fontWeight:600,
            color: tab === t.id ? T.gold400 : T.textSec,
            whiteSpace:'nowrap', cursor:'pointer', fontFamily:'DM Sans', flexShrink:0,
          }}>{t.label}</button>
        ))}
      </div>

      {/* Content per tab */}
      {tab === 'upnext' && (
        <UpNextPanel inProgress={upNext} fresh={fresh} onCardTap={setDetailGroup}/>
      )}
      {tab === 'teams' && (
        <TrophyGrid groups={byCategory.teams} onCardTap={setDetailGroup}/>
      )}
      {tab === 'nations' && (
        <TrophyGrid groups={byCategory.nations} onCardTap={setDetailGroup}/>
      )}
      {tab === 'leagues' && (
        <TrophyGrid groups={byCategory.leagues} onCardTap={setDetailGroup}/>
      )}
      {tab === 'general' && (
        <TrophyGrid groups={byCategory.general} onCardTap={setDetailGroup}/>
      )}

      {detailGroup && (
        <TrophyDetailModal group={detailGroup} sessions={sessions} onClose={() => setDetailGroup(null)}/>
      )}
    </Content>
  );
}

function UpNextPanel({ inProgress, fresh, onCardTap }) {
  const T = window.T;
  return (
    <>
      {inProgress.length > 0 && (
        <>
          <div style={{
            fontFamily:'DM Sans', fontSize:11, fontWeight:600,
            color:T.textMute, marginBottom:10, letterSpacing:'0.02em',
          }}>Closest to next tier</div>
          <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:10, marginBottom:24}}>
            {inProgress.map(g => <BadgeCard key={`${g.category}-${g.name}`} group={g} large onTap={() => onCardTap(g)}/>)}
          </div>
        </>
      )}
      {fresh.length > 0 && (
        <>
          <div style={{
            fontFamily:'DM Sans', fontSize:11, fontWeight:600,
            color:T.textMute, marginBottom:10, letterSpacing:'0.02em',
          }}>Try these next</div>
          <div style={{display:'grid', gridTemplateColumns:'1fr 1fr 1fr', gap:8}}>
            {fresh.map(g => <BadgeCard key={`${g.category}-${g.name}`} group={g} onTap={() => onCardTap(g)}/>)}
          </div>
        </>
      )}
      {inProgress.length === 0 && fresh.length === 0 && (
        <div style={{textAlign:'center', padding:'40px 20px', background:T.card, borderRadius:18}}>
          <div style={{fontSize:40, marginBottom:12, opacity:0.6}}>🏆</div>
          <div style={{fontSize:13, color:T.textSec}}>All trophies unlocked. Legendary status.</div>
        </div>
      )}
    </>
  );
}

function TrophyGrid({ groups, onCardTap }) {
  const T = window.T;
  // Sort: highest tier earned first, then alphabetical
  const sorted = [...groups].sort((a, b) => {
    const tierOrder = (g) => {
      if (g.highestEarned === 'diamond') return 0;
      if (g.highestEarned === 'gold') return 1;
      if (g.highestEarned === 'silver') return 2;
      if (g.highestEarned === 'bronze') return 3;
      return 4;
    };
    const aOrder = tierOrder(a), bOrder = tierOrder(b);
    if (aOrder !== bOrder) return aOrder - bOrder;
    return a.name.localeCompare(b.name);
  });

  return (
    <div style={{display:'grid', gridTemplateColumns:'1fr 1fr 1fr', gap:8}}>
      {sorted.map(g => <BadgeCard key={`${g.category}-${g.name}`} group={g} onTap={() => onCardTap(g)}/>)}
    </div>
  );
}

function BadgeCard({ group, large = false, onTap }) {
  const T = window.T;
  const tierConfig = window.TIER_CONFIG;
  const TIERS = ['bronze', 'silver', 'gold', 'diamond'];
  const isLocked = !group.highestEarned;
  const cfg = group.highestEarned ? tierConfig[group.highestEarned] : null;
  const teamColors = group.category === 'teams' ? window.getTeamColors?.(group.name === 'Wolves' ? 'Wolverhampton Wanderers' : group.name === 'Man City' ? 'Manchester City' : group.name === 'Man Utd' ? 'Manchester United' : group.name === 'Tottenham' ? 'Tottenham Hotspur' : group.name === 'Dortmund' ? 'Borussia Dortmund' : group.name === 'Leverkusen' ? 'Bayer Leverkusen' : group.name === 'PSG' ? 'Paris Saint-Germain' : group.name) : null;

  const showTeamColor = group.category === 'teams' && teamColors && !isLocked;

  return (
    <div onClick={onTap} style={{
      background: isLocked ? 'rgba(255,255,255,0.03)' : (cfg.bg),
      border: `1px solid ${isLocked ? T.border : cfg.border}`,
      borderRadius: 14, padding: large ? '14px 12px' : '12px 10px',
      textAlign: 'center', position: 'relative',
      minHeight: large ? 130 : 110,
      cursor: 'pointer',
    }}>
      {/* Tier dots in top-right showing all 4 tiers earned */}
      <div style={{position:'absolute', top:7, right:7, display:'flex', gap:3}}>
        {TIERS.map(tier => {
          const earned = group.tiers[tier]?.isUnlocked;
          const dotCfg = tierConfig[tier];
          return (
            <div key={tier} style={{
              width:5, height:5, borderRadius:'50%',
              background: earned ? dotCfg.color : 'rgba(255,255,255,0.1)',
            }}/>
          );
        })}
      </div>

      {/* Icon — for teams, render colored circle with initial */}
      <div style={{
        fontSize: large ? 30 : 24, lineHeight: 1, marginBottom: 6,
        marginTop: 4,
      }}>
        {showTeamColor ? (
          <div style={{
            width: large ? 44 : 36, height: large ? 44 : 36, borderRadius:'50%',
            background: teamColors.primary,
            border: `2px solid ${teamColors.secondary}`,
            display:'flex', alignItems:'center', justifyContent:'center',
            margin:'0 auto',
            fontFamily:'Bakbak One, sans-serif', fontSize: large ? 18 : 15,
            color: /^#?[fF][a-fA-F0-9]{2}|^#?[fF][fF][fF]/.test(teamColors.primary) ? '#1A2236' : '#FFFFFF',
          }}>{group.name[0]}</div>
        ) : (
          <span style={{filter: isLocked ? 'grayscale(100%) brightness(35%)' : 'none'}}>{group.icon}</span>
        )}
      </div>

      {/* Name */}
      <div style={{
        fontFamily:'DM Sans', fontSize: large ? 11 : 10, fontWeight:700,
        color: isLocked ? T.textMute : T.text,
        lineHeight:1.25, minHeight:24,
        display:'flex', alignItems:'center', justifyContent:'center',
        whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis',
        padding:'0 4px',
      }}>{group.name}</div>

      {/* Current tier label — keep DM Sans since it's a "tag" style label */}
      {group.highestEarned && (
        <div style={{
          fontSize:8.5, fontFamily:'DM Sans', letterSpacing:'0.12em',
          textTransform:'uppercase', color:cfg.color, marginTop:4,
        }}>{group.highestEarned}</div>
      )}

      {/* Next tier requirement — DM Sans, more readable for actual sentences */}
      {group.nextTier && (
        <div style={{
          marginTop:6, fontSize:9, color:T.textMute, fontFamily:'DM Sans',
          fontWeight:500, lineHeight:1.3,
          overflow:'hidden', display:'-webkit-box',
          WebkitLineClamp:2, WebkitBoxOrient:'vertical',
        }}>{group.tiers[group.nextTier]?.label}</div>
      )}

      {/* Token reward for next tier — DM Sans for the number */}
      {group.nextTier && (
        <div style={{
          marginTop:6, display:'inline-flex', alignItems:'center', gap:2,
          padding:'2px 5px', borderRadius:100,
          background:'rgba(245,200,66,0.1)', border:`1px solid rgba(245,200,66,0.2)`,
        }}>
          <span style={{fontSize:7}}>⬡</span>
          <span style={{fontSize:9, fontFamily:'DM Sans', fontWeight:700, color:T.gold400}}>
            {window.TIER_TOKENS?.[group.nextTier] ?? '?'}
          </span>
        </div>
      )}

      {/* Done badge for diamond */}
      {!group.nextTier && group.highestEarned === 'diamond' && (
        <div style={{
          marginTop:6, fontSize:9, fontFamily:'DM Sans', fontWeight:700,
          color:tierConfig.diamond.color,
        }}>✓ Complete</div>
      )}
    </div>
  );
}

// ─── Unlock celebration modal ─────────────────────────────────────
function UnlockModal({ unlocks, onClose }) {
  const T = window.T;
  const tierConfig = window.TIER_CONFIG;
  // Show the highest tier unlock if multiple
  const order = { diamond: 0, gold: 1, silver: 2, bronze: 3 };
  const topUnlock = [...unlocks].sort((a, b) => (order[a.tier] ?? 9) - (order[b.tier] ?? 9))[0];
  if (!topUnlock) return null;
  const cfg = tierConfig[topUnlock.tier];
  const totalTokens = unlocks.reduce((sum, u) => sum + (u.tokens || 0), 0);
  const [visible, setVisible] = React.useState(false);

  React.useEffect(() => {
    const t = setTimeout(() => setVisible(true), 30);
    return () => clearTimeout(t);
  }, []);

  return (
    <div onClick={onClose} style={{
      position:'fixed', inset:0, zIndex:200,
      background:'rgba(0,0,0,0.85)',
      display:'flex', alignItems:'flex-end', justifyContent:'center',
    }}>
      <div onClick={e => e.stopPropagation()} style={{
        width:'100%', maxWidth:500,
        background:T.navy900, borderRadius:'24px 24px 0 0',
        padding:'28px 24px 48px',
        border:`1px solid ${T.border}`, borderBottom:'none',
        transform: visible ? 'translateY(0)' : 'translateY(100%)',
        transition:'transform 400ms cubic-bezier(0.2,0.9,0.3,1)',
        textAlign:'center',
        paddingBottom:'max(48px, calc(48px + env(safe-area-inset-bottom)))',
      }}>
        <div style={{width:40, height:4, background:T.border, borderRadius:100, margin:'0 auto 24px', opacity:0.5}}/>

        <div style={{
          fontFamily:'DM Sans', fontSize:10, letterSpacing:'0.25em',
          textTransform:'uppercase', color:cfg.color, marginBottom:12,
        }}>Trophy Unlocked · {topUnlock.tier}</div>

        <div style={{
          width:100, height:100, borderRadius:'50%',
          background:cfg.bg, border:`3px solid ${cfg.color}`,
          margin:'0 auto 20px',
          display:'flex', alignItems:'center', justifyContent:'center',
          fontSize:48, boxShadow:`0 0 40px ${cfg.color}40`,
          animation:'badgePop 400ms cubic-bezier(0.34,1.56,0.64,1) 200ms both',
        }}>{topUnlock.icon}</div>

        <div style={{fontFamily:'Bakbak One, sans-serif', fontSize:26, letterSpacing:'0.04em', color:T.text, marginBottom:8}}>
          {topUnlock.name}
        </div>
        <div style={{fontSize:13, color:T.textSec, marginBottom:24, lineHeight:1.5, padding:'0 16px'}}>
          {topUnlock.label}
        </div>
        {unlocks.length > 1 && (
          <div style={{fontSize:12, color:T.textSec, marginBottom:16}}>
            +{unlocks.length - 1} more trophy{unlocks.length > 2 ? 's' : ''} unlocked!
          </div>
        )}

        <div style={{
          display:'inline-flex', alignItems:'center', gap:8,
          background:'rgba(232,184,32,0.12)', border:`1px solid ${T.gold600}`,
          borderRadius:100, padding:'10px 20px', marginBottom:24,
        }}>
          <HexIcon size={18}/>
          <span style={{fontFamily:'Bakbak One, sans-serif', fontSize:22, color:T.gold400}}>
            +{totalTokens} Tokens
          </span>
        </div>

        <button onClick={onClose} style={{
          width:'100%', padding:'14px', borderRadius:12,
          background:'linear-gradient(180deg, #F5C842, #C99A10)',
          color:'#1A1200', border:'none',
          fontFamily:'Bakbak One, sans-serif', fontSize:15, letterSpacing:'0.06em',
          cursor:'pointer',
        }}>NICE</button>
      </div>
      <style>{`
        @keyframes badgePop {
          from { transform: scale(0.4); opacity: 0; }
          to   { transform: scale(1);   opacity: 1; }
        }
      `}</style>
    </div>
  );
}

window.AchievementsScreen = AchievementsScreen;
window.UnlockModal = UnlockModal;

// ─── Trophy Detail Modal ─────────────────────────────────────────
// Tap a card → see all 4 tiers, what's earned, what's needed for next
function TrophyDetailModal({ group, sessions, onClose }) {
  const T = window.T;
  const tierConfig = window.TIER_CONFIG;
  const TIERS = ['bronze', 'silver', 'gold', 'diamond'];
  const [visible, setVisible] = React.useState(false);

  React.useEffect(() => {
    const t = setTimeout(() => setVisible(true), 30);
    return () => clearTimeout(t);
  }, []);

  // Build display info per tier
  const teamColors = group.category === 'teams'
    ? window.getTeamColors?.(
        group.name === 'Wolves' ? 'Wolverhampton Wanderers' :
        group.name === 'Man City' ? 'Manchester City' :
        group.name === 'Man Utd' ? 'Manchester United' :
        group.name === 'Tottenham' ? 'Tottenham Hotspur' :
        group.name === 'Dortmund' ? 'Borussia Dortmund' :
        group.name === 'Leverkusen' ? 'Bayer Leverkusen' :
        group.name === 'PSG' ? 'Paris Saint-Germain' :
        group.name
      )
    : null;

  // Category description
  const catLabel = {
    teams: 'Team Trophy',
    nations: 'Nation Trophy',
    leagues: 'League Trophy',
    general: 'General Trophy',
  }[group.category] || 'Trophy';

  return (
    <div onClick={onClose} style={{
      position:'fixed', inset:0, zIndex:200,
      background:'rgba(0,0,0,0.8)',
      display:'flex', alignItems:'flex-end', justifyContent:'center',
    }}>
      <div onClick={e => e.stopPropagation()} className="no-scrollbar" style={{
        width:'100%', maxWidth:500, maxHeight:'90vh', overflowY:'auto',
        background:T.navy900, borderRadius:'24px 24px 0 0',
        padding:'24px 22px',
        paddingBottom:'max(32px, calc(32px + env(safe-area-inset-bottom)))',
        border:`1px solid ${T.border}`, borderBottom:'none',
        transform: visible ? 'translateY(0)' : 'translateY(100%)',
        transition:'transform 400ms cubic-bezier(0.2,0.9,0.3,1)',
      }}>
        <div style={{width:40, height:4, background:T.border, borderRadius:100, margin:'0 auto 22px', opacity:0.5}}/>

        {/* Header: icon + name + category */}
        <div style={{display:'flex', alignItems:'center', gap:14, marginBottom:22}}>
          {teamColors && group.highestEarned ? (
            <div style={{
              width: 56, height: 56, borderRadius:'50%',
              background: teamColors.primary,
              border: `2.5px solid ${teamColors.secondary}`,
              display:'flex', alignItems:'center', justifyContent:'center',
              flexShrink:0,
              fontFamily:'Bakbak One, sans-serif', fontSize: 22,
              color: /^#?[fF][a-fA-F0-9]{2}|^#?[fF][fF][fF]/.test(teamColors.primary) ? '#1A2236' : '#FFFFFF',
            }}>{group.name[0]}</div>
          ) : (
            <div style={{
              width:56, height:56, borderRadius:'50%',
              background:group.highestEarned ? tierConfig[group.highestEarned].bg : 'rgba(255,255,255,0.04)',
              border:`2px solid ${group.highestEarned ? tierConfig[group.highestEarned].border : T.border}`,
              display:'flex', alignItems:'center', justifyContent:'center',
              fontSize:28, flexShrink:0,
              filter: group.highestEarned ? 'none' : 'grayscale(100%) brightness(40%)',
            }}>{group.icon}</div>
          )}
          <div style={{flex:1, minWidth:0}}>
            <div style={{
              fontSize:11, color:T.textMute, fontFamily:'DM Sans', fontWeight:600,
              letterSpacing:'0.02em', marginBottom:2,
            }}>{catLabel}</div>
            <div style={{
              fontFamily:'Bakbak One, sans-serif', fontSize:24,
              color:T.text, letterSpacing:'0.03em', lineHeight:1.1,
              whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis',
            }}>{group.name}</div>
          </div>
        </div>

        {/* Progress summary */}
        <div style={{
          background:T.card, borderRadius:14, padding:'12px 14px', marginBottom:18,
          display:'flex', justifyContent:'space-between', alignItems:'center',
        }}>
          <div>
            <div style={{fontSize:11, color:T.textSec, fontFamily:'DM Sans', marginBottom:2}}>
              {group.highestEarned
                ? `Currently ${group.highestEarned.toUpperCase()}`
                : 'Not yet earned'}
            </div>
            <div style={{fontSize:13, color:T.text, fontFamily:'DM Sans', fontWeight:500}}>
              {group.nextTier
                ? `Next up: ${group.nextTier.charAt(0).toUpperCase() + group.nextTier.slice(1)}`
                : 'All tiers complete!'}
            </div>
          </div>
          <div style={{display:'flex', gap:5}}>
            {TIERS.map(tier => {
              const earned = group.tiers[tier]?.isUnlocked;
              const cfg = tierConfig[tier];
              return (
                <div key={tier} style={{
                  width:14, height:14, borderRadius:'50%',
                  background: earned ? cfg.color : 'rgba(255,255,255,0.08)',
                  border: earned ? `1.5px solid ${cfg.color}` : `1.5px solid rgba(255,255,255,0.15)`,
                  boxShadow: earned ? `0 0 8px ${cfg.color}80` : 'none',
                }}/>
              );
            })}
          </div>
        </div>

        {/* All tiers, listed */}
        <div style={{
          fontFamily:'DM Sans', fontSize:12, fontWeight:600,
          color:T.textMute, marginBottom:10,
        }}>All Tiers</div>

        <div style={{display:'flex', flexDirection:'column', gap:8}}>
          {TIERS.map(tier => {
            const isEarned = group.tiers[tier]?.isUnlocked;
            const isNext = group.nextTier === tier;
            const cfg = tierConfig[tier];
            const trophy = group.tiers[tier];
            return (
              <div key={tier} style={{
                background: isEarned ? cfg.bg : (isNext ? 'rgba(232,184,32,0.05)' : T.card),
                border: `1px solid ${isEarned ? cfg.border : (isNext ? 'rgba(232,184,32,0.3)' : T.border)}`,
                borderRadius:12, padding:'12px 14px',
                display:'flex', alignItems:'center', gap:12,
              }}>
                {/* Tier badge circle */}
                <div style={{
                  width:32, height:32, borderRadius:'50%',
                  background: isEarned ? cfg.color : 'rgba(255,255,255,0.06)',
                  display:'flex', alignItems:'center', justifyContent:'center',
                  flexShrink:0,
                  border: isEarned ? 'none' : `1px solid ${T.border}`,
                }}>
                  {isEarned ? (
                    <svg width="14" height="14" viewBox="0 0 24 24" fill={tier === 'gold' || tier === 'diamond' ? '#1A1200' : '#fff'}>
                      <path d="M9 16.2l-3.5-3.5a1 1 0 011.4-1.4L9 13.4l7.1-7.1a1 1 0 011.4 1.4L9 16.2z"/>
                    </svg>
                  ) : (
                    <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke={T.textMute} strokeWidth="2.5" strokeLinecap="round">
                      <rect x="5" y="11" width="14" height="10" rx="2"/>
                      <path d="M8 11V7a4 4 0 018 0v4"/>
                    </svg>
                  )}
                </div>

                {/* Tier name + requirement */}
                <div style={{flex:1, minWidth:0}}>
                  <div style={{
                    fontSize:12, fontFamily:'DM Sans', fontWeight:700,
                    color: isEarned ? cfg.color : T.text,
                    textTransform:'uppercase', letterSpacing:'0.05em', marginBottom:2,
                  }}>{tier}</div>
                  <div style={{
                    fontSize:12, fontFamily:'DM Sans', fontWeight:500,
                    color: isEarned ? T.text : T.textSec,
                    lineHeight:1.4,
                  }}>{trophy?.label || ''}</div>
                </div>

                {/* Token reward */}
                <div style={{
                  display:'flex', alignItems:'center', gap:4,
                  padding:'4px 8px', borderRadius:100,
                  background: isEarned ? 'rgba(245,200,66,0.15)' : 'rgba(255,255,255,0.04)',
                  border:`1px solid ${isEarned ? 'rgba(245,200,66,0.3)' : T.border}`,
                  flexShrink:0,
                }}>
                  <span style={{fontSize:9}}>⬡</span>
                  <span style={{
                    fontSize:11, fontFamily:'DM Sans', fontWeight:700,
                    color: isEarned ? T.gold400 : T.textMute,
                  }}>{window.TIER_TOKENS?.[tier] ?? '?'}</span>
                </div>
              </div>
            );
          })}
        </div>

        <button onClick={onClose} style={{
          width:'100%', marginTop:18, padding:'14px',
          background:T.card, border:`1px solid ${T.border}`, borderRadius:12,
          color:T.text, fontFamily:'DM Sans', fontSize:14, fontWeight:600,
          cursor:'pointer',
        }}>Close</button>
      </div>
    </div>
  );
}

window.TrophyDetailModal = TrophyDetailModal;
