/* global React */
// NEXT XI · UI Kit · components.jsx
// Atoms + small composites used across screens.
// Loaded after React + Babel, before screens.jsx.

const { useState, useEffect, useRef } = React;

// ───── ICONS — 24px, 1.75 stroke, currentColor ─────
const Ico = ({ name, size = 24, fill = 'none' }) => {
  const stroke = { fill: 'none', stroke: 'currentColor', strokeWidth: 1.75, strokeLinecap: 'round', strokeLinejoin: 'round' };
  const paths = {
    home:    <path {...stroke} d="M3 11 12 4l9 7v9a1 1 0 0 1-1 1h-5v-6h-6v6H4a1 1 0 0 1-1-1v-9Z"/>,
    pitch:   <g {...stroke}><circle cx="12" cy="12" r="9"/><path d="M12 3v18M3 12h18"/></g>,
    trophy:  <path {...stroke} d="M5 4h14v4a7 7 0 0 1-14 0V4ZM9 18h6v3H9zM12 15v3"/>,
    user:    <g {...stroke}><circle cx="12" cy="8" r="4"/><path d="M4 21a8 8 0 0 1 16 0"/></g>,
    bolt:    <path {...stroke} d="M13 2 4 14h6l-1 8 9-12h-6l1-8Z"/>,
    flame:   <path fill="currentColor" d="M12 2c1 4-2 5-2 9a4 4 0 0 0 8 0c0-3-3-3-3-7 3 1 5 4 5 8a8 8 0 0 1-16 0c0-5 5-7 8-10Z"/>,
    shield:  <path {...stroke} d="M12 3 4 6v6c0 5 3 8 8 9 5-1 8-4 8-9V6l-8-3Z"/>,
    ball:    <g {...stroke}><circle cx="12" cy="12" r="9"/><path d="m9 9 6 6M15 9l-6 6"/></g>,
    check:   <path {...stroke} d="m3 12 5 5L21 4"/>,
    chev:    <path {...stroke} d="m9 6 6 6-6 6"/>,
    chevDown:<path {...stroke} d="m6 9 6 6 6-6"/>,
    arrow:   <path {...stroke} d="M5 12h14m-6-6 6 6-6 6"/>,
    plus:    <path {...stroke} d="M12 5v14M5 12h14"/>,
    bell:    <g {...stroke}><path d="M6 9a6 6 0 1 1 12 0v4l2 3H4l2-3V9Z"/><path d="M10 19a2 2 0 0 0 4 0"/></g>,
    cog:     <g {...stroke}><circle cx="12" cy="12" r="3"/><path d="M19 12a7 7 0 0 0-.1-1.2l2-1.6-2-3.4-2.4.7a7 7 0 0 0-2-1.2L14 3h-4l-.5 2.3a7 7 0 0 0-2 1.2L5.1 5.8l-2 3.4 2 1.6A7 7 0 0 0 5 12a7 7 0 0 0 .1 1.2l-2 1.6 2 3.4 2.4-.7a7 7 0 0 0 2 1.2L10 21h4l.5-2.3a7 7 0 0 0 2-1.2l2.4.7 2-3.4-2-1.6Z"/></g>,
    settings:<g {...stroke}><circle cx="12" cy="12" r="3"/><path d="M19 12a7 7 0 0 0-.1-1.2l2-1.6-2-3.4-2.4.7a7 7 0 0 0-2-1.2L14 3h-4l-.5 2.3a7 7 0 0 0-2 1.2L5.1 5.8l-2 3.4 2 1.6A7 7 0 0 0 5 12a7 7 0 0 0 .1 1.2l-2 1.6 2 3.4 2.4-.7a7 7 0 0 0 2 1.2L10 21h4l.5-2.3a7 7 0 0 0 2-1.2l2.4.7 2-3.4-2-1.6Z"/></g>,
    play:    <path fill="currentColor" d="M7 4v16l13-8L7 4Z"/>,
    clock:   <g {...stroke}><circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/></g>,
    activity:<path {...stroke} d="M3 12h4l3-7 4 14 3-7h4"/>,
    whistle: <g {...stroke}><path d="M12 20a8 8 0 0 0 8-8 8 8 0 1 0-16 0c0 4 4 6 4 9l4-1Z"/><path d="M16 8 9 14"/></g>,
    lock:    <g {...stroke}><rect x="5" y="11" width="14" height="10" rx="2"/><path d="M8 11V7a4 4 0 0 1 8 0v4"/></g>,
    locale:   <g {...stroke}><circle cx="12" cy="12" r="9"/><path d="M3 12h18M12 3a14 14 0 0 1 0 18M12 3a14 14 0 0 0 0 18"/></g>,
    chart:    <path {...stroke} d="M3 3v18h18M8 15l3-4 3 4 5-7"/>,
    lightning:<path {...stroke} d="M13 2 4 14h6l-1 8 9-12h-6l1-8Z"/>,
    medal:    <g {...stroke}><circle cx="12" cy="9" r="5"/><path d="M8.21 13.89 7 23l5-3 5 3-1.21-9.12"/></g>,
    wave:     <path {...stroke} d="M2 12c2-4 4-4 6 0s4 4 6 0 4-4 6 0"/>,
    drop:     <path fill="currentColor" d="M12 2C8.5 7.5 5 11 5 15a7 7 0 0 0 14 0c0-4-3.5-7.5-7-13Z"/>,
    timer:    <g {...stroke}><circle cx="12" cy="13" r="7"/><path d="M12 10v3l2 2M9 3h6M12 3v3"/></g>,
    swimmer:  <g {...stroke}><circle cx="12" cy="5" r="2"/><path d="M5 18c2-2 5-3 7-1s5 1 7-1M7 10l2 4h6l2-4M9 14l1 4M15 14l-1 4"/></g>,
    lane:     <g {...stroke}><path d="M3 6h18M3 12h18M3 18h18"/><circle cx="6" cy="6" r="1" fill="currentColor"/><circle cx="6" cy="12" r="1" fill="currentColor"/><circle cx="6" cy="18" r="1" fill="currentColor"/></g>,
  };
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" style={{ display: 'block' }}>
      {paths[name]}
    </svg>
  );
};

// ───── OFFICIAL BRAND MARK ─────
const BrandMark = ({ size = 32, style = {} }) => (
  <img
    src="icons/athloryx_app_icon.svg"
    width={size}
    height={size}
    alt="ATHLORYX"
    aria-hidden="true"
    style={{ display:'block', flexShrink:0, ...style }}
  />
);

// ───── BUILT-IN PLAYER AVATARS — no uploads / no external storage ─────
const PLAYER_AVATARS = [
  { id:'football',   tr:'Futbol',     en:'Football',   ru:'Футбол',     color:'#00FF88', glow:'#00C46A' },
  { id:'jersey',     tr:'Forma',      en:'Jersey',     ru:'Форма',      color:'#00FF88', glow:'#4F8DFF' },
  { id:'star',       tr:'Yıldız',     en:'Star',       ru:'Звезда',     color:'#B26BFF', glow:'#4F8DFF' },
  { id:'shield',     tr:'Kalkan',     en:'Shield',     ru:'Щит',        color:'#4F8DFF', glow:'#00FF88' },
  { id:'goalkeeper', tr:'Kaleci',     en:'Goalkeeper', ru:'Вратарь',    color:'#FF6B6B', glow:'#4F8DFF' },
  { id:'striker',    tr:'Forvet',     en:'Striker',    ru:'Форвард',    color:'#00FF88', glow:'#FFB800' },
  { id:'captain',    tr:'Kaptan',     en:'Captain',    ru:'Капитан',    color:'#FFB800', glow:'#00FF88' },
  { id:'academy',    tr:'Akademi',    en:'Academy',    ru:'Академия',   color:'#B8B8B8', glow:'#00FF88' },
  { id:'coach',      tr:'Koç',        en:'Coach',      ru:'Тренер',     color:'#FFB800', glow:'#4F8DFF' },
  // Swimming avatars
  { id:'swimmer',    tr:'Yüzücü',     en:'Swimmer',    ru:'Пловец',      color:'#38E8FF', glow:'#1FC8DF' },
  { id:'wave',       tr:'Dalga',      en:'Wave',       ru:'Волна',       color:'#4FD1C5', glow:'#38E8FF' },
  { id:'lane',       tr:'Kulvar',     en:'Lane',       ru:'Дорожка',     color:'#2563EB', glow:'#38E8FF' },
  { id:'stopwatch',  tr:'Kronometre', en:'Stopwatch',  ru:'Секундомер',  color:'#FFC857', glow:'#FF6B4A' },
  { id:'drop',       tr:'Su damlası', en:'Water drop', ru:'Капля воды',  color:'#38E8FF', glow:'#1FC8DF' },
  { id:'medal',      tr:'Madalya',    en:'Medal',      ru:'Медаль',      color:'#A7FF2F', glow:'#8ED400' },
];

const PLAYER_AVATAR_CHOICES = [
  { id:'initials', tr:'Baş harfler', en:'Initials', ru:'Инициалы', color:'#B8B8B8' },
  ...PLAYER_AVATARS.filter(a => ['football','jersey','star','shield','goalkeeper','striker','captain'].includes(a.id)),
];

const getAvatarChoicesForSport = (sportType) => {
  if (sportType === 'swimming') return [
    { id:'initials', tr:'Baş harfler', en:'Initials', ru:'Инициалы', color:'#B8B8B8' },
    ...['wave','stopwatch','medal','drop','lane','swimmer','star'].map(id => PLAYER_AVATARS.find(a => a.id === id)).filter(Boolean),
  ];
  return PLAYER_AVATAR_CHOICES;
};

const getPlayerAvatar = (avatarId) => {
  if (!avatarId || avatarId === 'initials') return null;
  const safeId = avatarId === 'lightning' ? 'jersey' : avatarId;
  return PLAYER_AVATARS.find(a => a.id === safeId) || null;
};

const PlayerAvatarGlyph = ({ id, color, size }) => {
  const stroke = {
    fill:'none',
    stroke:'currentColor',
    strokeWidth:3.2,
    strokeLinecap:'round',
    strokeLinejoin:'round',
  };
  const text = {
    fontFamily:'Oswald, sans-serif',
    fontWeight:800,
    fill:'currentColor',
    textAnchor:'middle',
    dominantBaseline:'central',
  };
  const glyphs = {
    football: (
      <g>
        <circle cx="32" cy="32" r="15" {...stroke}/>
        <path {...stroke} d="m32 19 8 6-3 10H27l-3-10 8-6Z"/>
        <path {...stroke} d="M24 25 18 30m22-5 6 5M27 35l-5 8m15-8 5 8"/>
      </g>
    ),
    jersey: (
      <g>
        <path {...stroke} d="M20 22 29 15h6l9 7-5 8v18H25V30l-5-8Z"/>
        <path {...stroke} d="M29 15c1 4 5 4 6 0"/>
        <path {...stroke} d="M28 34h8"/>
      </g>
    ),
    star: <path {...stroke} d="m32 12 5.7 11.5 12.7 1.9-9.2 9 2.2 12.7L32 41.1 20.6 47l2.2-12.7-9.2-9 12.7-1.9L32 12Z"/>,
    shield: (
      <g>
        <path {...stroke} d="M32 11 17 17v13c0 11 6 18 15 22 9-4 15-11 15-22V17l-15-6Z"/>
        <path {...stroke} d="M24 31h16M32 22v18"/>
      </g>
    ),
    goalkeeper: (
      <g>
        <path {...stroke} d="M19 35V21c0-3 2-5 5-5s5 2 5 5v13"/>
        <path {...stroke} d="M35 35V21c0-3 2-5 5-5s5 2 5 5v14"/>
        <path {...stroke} d="M17 35h30l-3 12H20l-3-12Z"/>
        <path {...stroke} d="M29 24h6"/>
      </g>
    ),
    striker: (
      <g>
        <path {...stroke} d="M21 23 32 15l11 8-5 7v19H26V30l-5-7Z"/>
        <text x="32" y="35" fontSize="17" {...text}>9</text>
      </g>
    ),
    captain: (
      <g>
        <path {...stroke} d="M19 26h26v16H19z"/>
        <path {...stroke} d="M19 26 14 21m31 5 5-5"/>
        <text x="32" y="34.5" fontSize="18" {...text}>C</text>
      </g>
    ),
    academy: (
      <g>
        <path {...stroke} d="M32 11 47 18v14c0 10-6 17-15 21-9-4-15-11-15-21V18l15-7Z"/>
        <text x="32" y="33" fontSize="16" letterSpacing="1" {...text}>XI</text>
      </g>
    ),
    coach: (
      <g>
        <rect x="16" y="18" width="32" height="26" rx="4" {...stroke}/>
        <path {...stroke} d="M24 26h16M24 34h8m8 0h2M24 42h16"/>
        <path {...stroke} d="M42 13v9M46 15l-4-2-4 2"/>
      </g>
    ),
    swimmer: (
      <g>
        <circle cx="32" cy="14" r="5" {...stroke}/>
        <path {...stroke} d="M20 28c3-5 9-7 12-4s9 3 12-2"/>
        <path {...stroke} d="M18 38c3-3 7-4 10-2s8 2 11-2"/>
        <path {...stroke} d="M24 20l4 8M40 20l-4 8"/>
      </g>
    ),
    wave: (
      <g>
        <path {...stroke} d="M12 26c4-8 8-8 12 0s8 8 12 0"/>
        <path {...stroke} d="M8 38c4-8 8-8 12 0s8 8 12 0s4-4 6-6"/>
        <circle cx="32" cy="16" r="5" {...stroke}/>
      </g>
    ),
    lane: (
      <g>
        <rect x="14" y="14" width="36" height="36" rx="3" {...stroke}/>
        <path {...stroke} d="M14 26h36M14 38h36"/>
        <circle cx="32" cy="20" r="3" fill="currentColor"/>
        <path {...stroke} d="M26 32c2-3 4-3 6 0s4 3 6 0"/>
        <path {...stroke} d="M26 44c2-3 4-3 6 0s4 3 6 0"/>
      </g>
    ),
    stopwatch: (
      <g>
        <circle cx="32" cy="34" r="16" {...stroke}/>
        <path {...stroke} d="M32 22v12l8 6"/>
        <path {...stroke} d="M26 14h12M32 14v8"/>
        <path {...stroke} d="M44 20l4-4"/>
      </g>
    ),
    drop: (
      <g>
        <path {...stroke} d="M32 10 C32 10 16 28 16 38 a16 16 0 0 0 32 0 C48 28 32 10 32 10Z"/>
        <path {...stroke} d="M24 40 Q28 34 36 38" strokeWidth={2.4}/>
      </g>
    ),
    medal: (
      <g>
        <circle cx="32" cy="38" r="14" {...stroke}/>
        <path {...stroke} d="M26 10h12l-4 14h-4L26 10Z"/>
        <path {...stroke} d="M32 30l2.6 5.3 5.9.8-4.3 4.2 1 5.8L32 43.3l-5.2 2.8 1-5.8-4.3-4.2 5.9-.8L32 30Z" strokeWidth={2.2}/>
      </g>
    ),
  };
  return (
    <svg width={Math.round(size * 0.74)} height={Math.round(size * 0.74)} viewBox="0 0 64 64"
      style={{ color, display:'block', filter:`drop-shadow(0 0 ${Math.max(4, size * 0.10)}px ${color}66)` }}>
      {glyphs[id] || glyphs.academy}
    </svg>
  );
};

const PlayerAvatar = ({ avatarId, initials, size = 48, ring }) => {
  const avatar = getPlayerAvatar(avatarId);
  const baseStyle = {
    width: size,
    height: size,
    borderRadius: '50%',
    display:'flex',
    alignItems:'center',
    justifyContent:'center',
    fontFamily:'Oswald',
    fontWeight: 800,
    flexShrink: 0,
    position:'relative',
    overflow:'hidden',
    boxSizing:'border-box',
  };
  if (!avatar) {
    return (
      <div style={{
        ...baseStyle,
        background:'radial-gradient(circle at 35% 22%, rgba(255,255,255,0.14), transparent 32%), linear-gradient(145deg,#242424,#080808)',
        border: ring ? `2px solid ${ring}` : '1px solid rgba(255,255,255,0.12)',
        boxShadow:'inset 0 0 0 1px rgba(255,255,255,0.04), 0 8px 18px rgba(0,0,0,0.24)',
        color:'#fff',
        fontSize: size * 0.34,
        letterSpacing: '0.04em',
      }}>
        <div style={{ position:'absolute', inset:4, borderRadius:'50%',
          border:'1px solid rgba(255,255,255,0.06)' }}/>
        <span style={{ position:'relative', zIndex:1 }}>{initials}</span>
      </div>
    );
  }
  return (
    <div style={{
      ...baseStyle,
      background:`radial-gradient(circle at 32% 22%, rgba(255,255,255,0.20), transparent 30%), radial-gradient(circle at 70% 78%, ${avatar.glow}30, transparent 42%), linear-gradient(145deg, #202020 0%, #0B0B0B 58%, ${avatar.color}18 100%)`,
      border: ring ? `2px solid ${ring}` : `1px solid ${avatar.color}70`,
      boxShadow:`inset 0 0 0 1px rgba(255,255,255,0.05), 0 0 ${Math.max(12, size * 0.34)}px ${avatar.color}22, 0 8px 18px rgba(0,0,0,0.28)`,
      color: avatar.color,
    }}>
      <div style={{ position:'absolute', inset:4, borderRadius:'50%',
        border:`1px solid ${avatar.color}30` }}/>
      <div style={{ position:'absolute', left:'14%', right:'14%', top:'13%', height:'18%',
        borderRadius:'999px', background:'rgba(255,255,255,0.08)', filter:'blur(0.2px)' }}/>
      <div style={{ position:'relative', zIndex:1, display:'flex', alignItems:'center', justifyContent:'center' }}>
        <PlayerAvatarGlyph id={avatar.id} color={avatar.color} size={size}/>
      </div>
    </div>
  );
};

// ───── Localization helper ─────
const STR = {
  tr: {
    home:'Ana sayfa', training:'Antrenman', achievements:'Başarımlar', profile:'Profil',
    todayMission:'Bugünkü hedef', startSession:'Antrenmana başla', viewReport:'Raporu gör',
    weeklyForm:'Bu haftaki form', level:'Seviye', xp:'XP', nextLevel:'Sonraki seviyeye',
    streak:'Seri', daysInRow:'gün üst üste', sessions:'Antrenmanlar', upcoming:'Yaklaşan',
    completed:'Tamamlandı', overall:'Genel · OVR', attributes:'Özellikler',
    pas:'Pas', sut:'Şut', hiz:'Hız', sav:'Savunma', dri:'Dribbling', fiz:'Fizik',
    coach:'Koç', team:'Takım', position:'Pozisyon', age:'Yaş', match:'Maç',
    unlocked:'Açıldı', locked:'Kilitli', inProgress:'Devam ediyor',
    parentReport:'Veli raporu', attendance:'Katılım', minutes:'Dakika',
    leaderboard:'Sıralama', viewAll:'Tümünü gör', hatTrick:'Hat Trick',
    winStreak:'Galibiyet serisi', captain:'Kaptan', moves:'Top sürme', signOut:'Çıkış yap',
    welcome:'Hoş geldin', earnedXP:'kazandın', goal:'Gol', assist:'Asist',
  },
  en: {
    home:'Home', training:'Training', achievements:'Achievements', profile:'Profile',
    todayMission:"Today's mission", startSession:'Start session', viewReport:'View report',
    weeklyForm:'Weekly form', level:'Level', xp:'XP', nextLevel:'To next level',
    streak:'Streak', daysInRow:'days in row', sessions:'Sessions', upcoming:'Upcoming',
    completed:'Completed', overall:'Overall · OVR', attributes:'Attributes',
    pas:'Passing', sut:'Shooting', hiz:'Pace', sav:'Defending', dri:'Dribbling', fiz:'Physical',
    coach:'Coach', team:'Team', position:'Position', age:'Age', match:'Match',
    unlocked:'Unlocked', locked:'Locked', inProgress:'In progress',
    parentReport:'Parent report', attendance:'Attendance', minutes:'Minutes',
    leaderboard:'Leaderboard', viewAll:'View all', hatTrick:'Hat Trick',
    winStreak:'Win Streak', captain:'Captain', moves:'Dribbling', signOut:'Sign out',
    welcome:'Welcome', earnedXP:'earned', goal:'Goal', assist:'Assist',
  },
  ru: {
    home:'Главная', training:'Тренировка', achievements:'Достижения', profile:'Профиль',
    todayMission:'Задание на сегодня', startSession:'Начать тренировку', viewReport:'Посмотреть отчёт',
    weeklyForm:'Форма за неделю', level:'Уровень', xp:'XP', nextLevel:'До следующего уровня',
    streak:'Серия', daysInRow:'дней подряд', sessions:'Тренировки', upcoming:'Предстоящие',
    completed:'Завершено', overall:'Общее · OVR', attributes:'Характеристики',
    pas:'Пас', sut:'Удар', hiz:'Скорость', sav:'Защита', dri:'Дриблинг', fiz:'Физика',
    coach:'Тренер', team:'Команда', position:'Позиция', age:'Возраст', match:'Матч',
    unlocked:'Открыто', locked:'Заблокировано', inProgress:'В процессе',
    parentReport:'Отчёт для родителей', attendance:'Посещаемость', minutes:'Минуты',
    leaderboard:'Рейтинг', viewAll:'Посмотреть все', hatTrick:'Хет-трик',
    winStreak:'Победная серия', captain:'Капитан', moves:'Дриблинг', signOut:'Выйти',
    welcome:'Привет', earnedXP:'заработал', goal:'Гол', assist:'Ассист',
  },
};

const langKeyOf = (lang) => lang === 'ru' ? 'ru' : lang === 'en' ? 'en' : 'tr';
const textForLang = (entry, lang, fallback = '') => {
  if (entry == null) return fallback;
  if (typeof entry === 'string') return entry;
  const key = langKeyOf(lang);
  return entry[key] ?? entry.tr ?? entry.en ?? fallback ?? '';
};

// ───── ATOMS ─────
const Button = ({ kind = 'primary', children, onClick, full, icon, size = 'md', disabled = false }) => {
  const base = {
    fontFamily: 'Manrope, system-ui', fontWeight: 700, letterSpacing: '0.04em',
    textTransform: 'uppercase', border: 'none', cursor: disabled ? 'not-allowed' : 'pointer',
    display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8,
    borderRadius: 12, transition: 'all 180ms cubic-bezier(0.22,1,0.36,1)',
    width: full ? '100%' : undefined,
    opacity: disabled ? 0.48 : 1,
    pointerEvents: disabled ? 'none' : undefined,
  };
  const sizing = size === 'lg'
    ? { padding: '18px 24px', fontSize: 15, minHeight: 56 }
    : size === 'sm'
    ? { padding: '8px 12px', fontSize: 11 }
    : { padding: '13px 18px', fontSize: 14 };
  const styles = {
    primary:   { background: 'var(--nx-accent)', color: 'var(--nx-accent-ink)', boxShadow: 'var(--nx-btn-primary-shadow)' },
    secondary: { background: '#1C1C1C', color: 'var(--nx-accent)', border: '1px solid var(--nx-accent-glow)' },
    ghost:     { background: 'transparent', color: '#fff', border: '1px solid rgba(255,255,255,0.10)' },
    warning:   { background: 'rgba(255,200,87,0.10)', color: '#FFC857', border: '1px solid rgba(255,200,87,0.35)' },
    success:   { background: 'rgba(79,209,197,0.10)', color: '#4FD1C5', border: '1px solid rgba(79,209,197,0.35)' },
    danger:    { background: 'rgba(255,107,107,0.08)', color: '#FF6B6B', border: '1px solid rgba(255,107,107,0.25)' },
  };
  return (
    <button disabled={disabled} onClick={disabled ? undefined : onClick}
      style={{ ...base, ...sizing, ...styles[kind] }}
      onMouseDown={e => { if (!disabled) e.currentTarget.style.transform='scale(0.97)'; }}
      onMouseUp={e => e.currentTarget.style.transform='scale(1)'}
      onMouseLeave={e => e.currentTarget.style.transform='scale(1)'}>
      {children}
      {icon && <Ico name={icon} size={16}/>}
    </button>
  );
};

const Chip = ({ children, on, color, onClick }) => (
  <button onClick={onClick} style={{
    padding: '7px 14px', borderRadius: 999, border: '1px solid',
    fontFamily: 'Manrope', fontWeight: 600, fontSize: 12,
    background: on ? (color || '#00FF88') : '#1C1C1C',
    color: on ? '#001A0E' : '#B8B8B8',
    borderColor: on ? 'transparent' : 'rgba(255,255,255,0.06)',
    cursor: 'pointer', transition: 'all 180ms',
    whiteSpace: 'nowrap', flexShrink: 0,
  }}>{children}</button>
);

const SectionHead = ({ title, action, onAction }) => (
  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', padding: '10px 20px 0' }}>
    <span style={{ fontFamily: 'Oswald', fontWeight: 600, fontSize: 16, textTransform: 'uppercase',
      letterSpacing: '0.06em', color: '#fff' }}>{title}</span>
    {action && <button onClick={onAction} style={{
      margin: 0, padding: 0, background:'transparent', border:'none',
      fontFamily: 'Manrope', fontWeight: 700, fontSize: 11,
      letterSpacing: '0.14em', textTransform: 'uppercase',
      color: '#7A7A7A', cursor: onAction ? 'pointer' : 'default'
    }}>{action} →</button>}
  </div>
);

const Label = ({ children, color = '#7A7A7A', style }) => (
  <span style={{ fontFamily: 'Manrope', fontWeight: 700, fontSize: 10,
    letterSpacing: '0.14em', textTransform: 'uppercase', color, ...style }}>{children}</span>
);

// ───── XP BAR ─────
const XPBar = ({ level = 14, current = 960, total = 1500, gain }) => {
  const pct = (current / total) * 100;
  const t = window.NXT_T || STR.tr;
  return (
    <div style={{ background: '#141414', border: '1px solid rgba(255,255,255,0.06)',
      borderRadius: 16, padding: '16px 18px', display: 'flex', flexDirection: 'column', gap: 12 }}>
      <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between' }}>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 10 }}>
          <Label>{t.level}</Label>
          <span style={{ fontFamily: 'Oswald', fontWeight: 700, fontSize: 48, color: '#fff', lineHeight: 0.9, fontVariantNumeric: 'tabular-nums' }}>
            {level}<span style={{ color: 'var(--nx-accent)', textShadow: '0 0 24px var(--nx-accent-glow)' }}>.</span>
          </span>
        </div>
        <span style={{ fontFamily: 'JetBrains Mono', fontSize: 11, color: '#7A7A7A' }}>
          {t.nextLevel} <b style={{ color: '#fff', fontFamily: 'Oswald', fontWeight: 700, fontSize: 16 }}>{total-current}</b> XP
        </span>
      </div>
      <div style={{ height: 12, background: '#242424', borderRadius: 999, overflow: 'hidden',
        border: '1px solid rgba(255,255,255,0.06)', position: 'relative' }}>
        <div style={{ height: '100%', width: `${pct}%`, borderRadius: 999,
          background: 'linear-gradient(90deg,var(--nx-accent-lo),var(--nx-accent))',
          boxShadow: '0 0 16px var(--nx-accent-glow)' }}/>
      </div>
      {gain != null && (
        <div style={{ display:'flex', alignItems:'center', gap: 8 }}>
          <span style={{ fontFamily:'Oswald', fontWeight:700, fontSize:22, color:'var(--nx-accent)', textShadow:'0 0 14px var(--nx-accent-glow)' }}>+{gain} XP</span>
          <span style={{ fontFamily:'Manrope', fontSize:12, color:'#7A7A7A' }}>{t.earnedXP}</span>
        </div>
      )}
    </div>
  );
};

// ───── ATTRIBUTE RING ─────
const AttributeRing = ({ value, label, delta, hi }) => {
  const r = 28, c = 2 * Math.PI * r;
  const off = c - (value / 99) * c;
  const color = hi === 'gold' ? '#FFB800' : hi === 'on' ? 'var(--nx-accent)' : '#fff';
  return (
    <div style={{ background:'#141414', border:'1px solid rgba(255,255,255,0.06)',
      borderRadius: 12, padding: '10px 6px', display:'flex', flexDirection:'column',
      alignItems:'center', gap: 4 }}>
      <div style={{ position:'relative', width: 64, height: 64 }}>
        <svg width="64" height="64" style={{ transform:'rotate(-90deg)' }}>
          <circle cx="32" cy="32" r={r} stroke="rgba(255,255,255,0.08)" strokeWidth="5" fill="none"/>
          <circle cx="32" cy="32" r={r} stroke={color} strokeWidth="5" fill="none"
            strokeLinecap="round" strokeDasharray={c} strokeDashoffset={off}
            style={{ filter: hi==='on' ? 'drop-shadow(0 0 4px var(--nx-accent-glow))' : undefined }}/>
        </svg>
        <span style={{ position:'absolute', inset:0, display:'flex', alignItems:'center', justifyContent:'center',
          fontFamily:'Oswald', fontWeight:700, fontSize: 22, color, textShadow: hi==='on' ? '0 0 10px var(--nx-accent-glow)' : 'none' }}>{value}</span>
      </div>
      <Label>{label}</Label>
      {delta != null && (
        <span style={{ fontFamily:'JetBrains Mono', fontSize: 10,
          color: delta > 0 ? 'var(--nx-accent)' : '#FF3B30' }}>
          {delta > 0 ? '▲' : '▼'} {Math.abs(delta)}
        </span>
      )}
    </div>
  );
};

// ───── SPORT THEME ─────
const getSportTheme = (sportType) => {
  if (sportType === 'swimming') return {
    sportType: 'swimming',
    // Same dark background as football — only accent changes
    bg0: '#050505', bg1: '#0B0B0B', bg2: '#141414', bg3: '#1C1C1C',
    accent: '#38E8FF', accentHi: '#7AF0FF', accentLo: '#1FC8DF',
    accentInk: '#031014',
    accentGlow: 'rgba(56,232,255,0.35)', accentSoft: 'rgba(56,232,255,0.14)',
    btnShadow: '0 0 0 1px rgba(56,232,255,0.50), 0 12px 24px -12px rgba(56,232,255,0.35)',
    // Extended swimming palette — use selectively for badges, highlights, charts
    mint: '#4FD1C5', lime: '#A7FF2F', warmth: '#FFC857', coral: '#FF6B4A', deepBlue: '#2563EB',
    // Role labels
    playerLabel: 'Yüzücü', playerLabelPlural: 'Yüzücüler',
    coachLabel: 'Eğitmen', coachLabelPlural: 'Eğitmenler',
    teamLabel: 'Grup', teamLabelPlural: 'Gruplar',
    pitchLabel: 'Havuz',
    positionLabel: 'Stil',
    // Content copy labels
    trainingLabel: 'Seans',
    trainingTabLabel: 'Seans',
    drillLabel: 'teknik çalışma',
    drillLibLabel: 'Teknik kütüphanesi',
    sessionStartLabel: 'Seansa başla',
    todayLabel: 'Bugün yüzme seansın var',
    mockSessionTitle: 'Serbest stil · Set 4',
    mockLocation: 'Havuz 2',
    matchLabel: 'Seans',
    scoreLabel: 'SKOR',
    academyLabel: 'Yüzme Akademisi',
    styleExamples: ['Serbest', 'Sırtüstü', 'Kurbağalama', 'Kelebek', 'Karışık'],
    demoNames: ['Efe Yıldız', 'Deniz Kaya', 'Elif Demir', 'Mert Kara', 'Zeynep Arslan', 'Lina Öz', 'Burak Aslan', 'Ada Şahin'],
    sessionExamples: ['Nefes kontrolü', 'Serbest stil tekniği', 'Kick tekniği', 'Dönüş çalışması', 'Dayanıklılık seti'],
  };
  return {
    sportType: 'football',
    bg0: '#050505', bg1: '#0B0B0B', bg2: '#141414', bg3: '#1C1C1C',
    accent: '#00FF88', accentHi: '#6BFFB4', accentLo: '#00C46A',
    accentInk: '#001A0E',
    accentGlow: 'rgba(0,255,136,0.22)', accentSoft: 'rgba(0,255,136,0.10)',
    btnShadow: '0 0 0 1px rgba(0,255,136,0.50), 0 12px 24px -12px rgba(0,255,136,0.35)',
    // Role labels
    playerLabel: 'Sporcu', playerLabelPlural: 'Sporcular',
    coachLabel: 'Koç', coachLabelPlural: 'Koçlar',
    teamLabel: 'Takım', teamLabelPlural: 'Takımlar',
    pitchLabel: 'Saha',
    positionLabel: 'CAM',
    // Content copy labels
    trainingLabel: 'Antrenman',
    trainingTabLabel: 'Antrenman',
    drillLabel: 'drill',
    drillLibLabel: 'Drill kütüphanesi',
    sessionStartLabel: 'Antrenmana başla',
    todayLabel: 'Bugün antrenman var',
    mockSessionTitle: 'Bitiricilik · Set 4',
    mockLocation: 'Pitch 2',
    matchLabel: 'Maç',
    scoreLabel: 'OVR',
    academyLabel: 'Galatasaray Akademi',
    styleExamples: ['CAM', 'ST', 'CB', 'LW', 'GK'],
    demoNames: ['Efe Yıldız', 'Mert Kara', 'Burak Aslan', 'Can Demir', 'Ali Şahin', 'Deniz Öz'],
    sessionExamples: ['Top sürme', 'Şut çalışması', 'Savunma organizasyonu', 'Pas egzersizi', 'Kondisyon antrenmanı'],
  };
};

Object.assign(window, {
  Ico, BrandMark, STR, Button, Chip, SectionHead, Label, XPBar, AttributeRing,
  PLAYER_AVATARS, PLAYER_AVATAR_CHOICES, getPlayerAvatar, PlayerAvatar,
  getAvatarChoicesForSport, getSportTheme, langKeyOf, textForLang,
});
