// CyberX Battle Pass — Main mobile screen (Screen 1) with 4 states + Reward grid

// Frame wrapper — fixed 375×812 like the brief asks
function PhoneFrame({ children, statusBarTime = '21:34' }) {
  return (
    <div style={{
      width: 375, height: 812, borderRadius: 44, overflow: 'hidden',
      position: 'relative', background: CX.black,
      boxShadow: '0 30px 80px rgba(0,0,0,0.5), 0 0 0 8px #1a1c20, 0 0 0 9px #2a2d35',
      fontFamily: FONT_BODY, color: CX.white,
      WebkitFontSmoothing: 'antialiased',
    }}>
      {/* status bar */}
      <div style={{
        position: 'absolute', top: 0, left: 0, right: 0, height: 44,
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        padding: '14px 28px 0', zIndex: 50,
        fontFamily: FONT_BODY, fontSize: 14, fontWeight: 600, color: CX.white,
      }}>
        <span style={{ fontVariantNumeric: 'tabular-nums' }}>{statusBarTime}</span>
        <div style={{ display: 'flex', gap: 6, alignItems: 'center' }}>
          <svg width="16" height="11" viewBox="0 0 16 11"><path d="M3 8.5 L5 8.5 L5 11 L3 11 Z M7 5 L9 5 L9 11 L7 11 Z M11 2 L13 2 L13 11 L11 11 Z" fill={CX.white}/></svg>
          <svg width="15" height="11" viewBox="0 0 15 11"><path d="M7.5 2.5 C10 2.5 12 3.5 13 5 L11.5 6.5 C11 5.5 9 4.5 7.5 4.5 C6 4.5 4 5.5 3.5 6.5 L2 5 C3 3.5 5 2.5 7.5 2.5 Z M7.5 6 C8.5 6 9.5 6.5 10 7 L8.5 8.5 C8.2 8.2 8 8 7.5 8 C7 8 6.8 8.2 6.5 8.5 L5 7 C5.5 6.5 6.5 6 7.5 6 Z" fill={CX.white}/><circle cx="7.5" cy="9.5" r="1" fill={CX.white}/></svg>
          <svg width="24" height="11" viewBox="0 0 24 11"><rect x="0.5" y="0.5" width="20" height="10" rx="2.5" stroke={CX.white} strokeOpacity="0.5" fill="none"/><rect x="2" y="2" width="17" height="7" rx="1" fill={CX.white}/><rect x="21" y="3.5" width="1.5" height="4" rx="0.5" fill={CX.white} fillOpacity="0.5"/></svg>
        </div>
      </div>
      {/* notch */}
      <div style={{
        position: 'absolute', top: 8, left: '50%', transform: 'translateX(-50%)',
        width: 120, height: 32, borderRadius: 18, background: '#000', zIndex: 49,
      }}/>
      {/* content */}
      <div style={{ height: '100%', overflow: 'hidden', position: 'relative' }}>
        {children}
      </div>
      {/* home indicator */}
      <div style={{
        position: 'absolute', bottom: 7, left: '50%', transform: 'translateX(-50%)',
        width: 134, height: 5, borderRadius: 3, background: 'rgba(255,255,255,0.85)',
        zIndex: 60, pointerEvents: 'none',
      }}/>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Background — subtle cyber grid + red ambient
// ─────────────────────────────────────────────────────────────
function CXBackground({ accent = CX.red }) {
  return (
    <div style={{
      position: 'absolute', inset: 0,
      backgroundColor: CX.black,
      backgroundImage: `
        radial-gradient(ellipse at top, ${accent}26, transparent 50%),
        radial-gradient(ellipse at bottom right, rgba(168,85,247,0.08), transparent 50%),
        linear-gradient(rgba(255,255,255,0.018) 1px, transparent 1px),
        linear-gradient(90deg, rgba(255,255,255,0.018) 1px, transparent 1px)
      `,
      backgroundSize: '100% 100%, 100% 100%, 24px 24px, 24px 24px',
    }}/>
  );
}

// ─────────────────────────────────────────────────────────────
// Profile card on main screen
// ─────────────────────────────────────────────────────────────
function ProfileCard({ nick = 'TENZ_RU', level = 15, xp = 3500, nextXp = 5000, premium = false, initials = 'TZ' }) {
  const t = tierFor(level);
  return (
    <div style={{
      margin: '0 16px', padding: 16, borderRadius: 16,
      background: `linear-gradient(180deg, ${CX.card}, ${CX.black})`,
      border: `1px solid ${CX.line}`,
      position: 'relative', overflow: 'hidden',
    }}>
      {/* subtle tier glow */}
      <div style={{
        position: 'absolute', top: -40, right: -40, width: 160, height: 160,
        borderRadius: '50%', background: `radial-gradient(circle, ${t.color}33, transparent 70%)`,
      }}/>
      <div style={{ display: 'flex', alignItems: 'center', gap: 14, position: 'relative' }}>
        <Avatar size={64} tier={t} initials={initials}/>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
            <span style={{
              fontFamily: FONT_DISPLAY, fontSize: 18, color: CX.white, letterSpacing: '0.05em',
            }}>{nick}</span>
            {premium && <Chip color={CX.premiumGold}><PremiumStar size={10}/> PREMIUM</Chip>}
          </div>
          <div style={{
            marginTop: 4, fontFamily: FONT_DISPLAY, fontSize: 13,
            color: t.hi, letterSpacing: '0.18em',
          }}>{t.name} • УРОВЕНЬ {level}</div>
        </div>
      </div>
      <div style={{ marginTop: 14 }}>
        <XPBar value={xp} max={nextXp} color={CX.amber} label={`До ур. ${level + 1}`}/>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Tab pills
// ─────────────────────────────────────────────────────────────
function TabPills({ active = 'rewards', tabs }) {
  const list = tabs || [
    { id: 'rewards', label: 'НАГРАДЫ' },
    { id: 'tasks', label: 'ЗАДАНИЯ' },
    { id: 'top', label: 'ТАБЛИЦА' },
  ];
  return (
    <div style={{
      display: 'flex', gap: 8, padding: '0 16px', marginTop: 16,
    }}>
      {list.map(t => {
        const on = t.id === active;
        return (
          <div key={t.id} style={{
            flex: 1, padding: '10px 6px', textAlign: 'center', borderRadius: 8,
            background: on ? CX.red : 'transparent',
            border: `1px solid ${on ? CX.red : CX.line}`,
            fontFamily: FONT_DISPLAY, fontSize: 12, letterSpacing: '0.12em',
            color: on ? CX.white : CX.textSec, fontWeight: 700,
            boxShadow: on ? `0 0 14px ${CX.red}77` : 'none',
          }}>{t.label}</div>
        );
      })}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Reward strip — horizontal scroll of LevelColumns
// ─────────────────────────────────────────────────────────────
const SAMPLE_REWARDS = [
  { lvl: 13, free: { kind: 'coins', name: '500 XP' }, prem: { kind: 'sticker', name: 'Стикерпак S1' } },
  { lvl: 14, free: { kind: 'mousepad', name: 'Стикер CyberX' }, prem: { kind: 'hours', name: '+1 час игры' } },
  { lvl: 15, free: { kind: 'coins', name: '300 бонусов' }, prem: { kind: 'avatar', name: 'Аватар-рамка' } },
  { lvl: 16, free: { kind: 'hours', name: '+30 мин' }, prem: { kind: 'mousepad', name: 'Коврик S1' } },
  { lvl: 17, free: { kind: 'sticker', name: 'Стикер #4' }, prem: { kind: 'cup', name: 'Кружка CX' } },
  { lvl: 18, free: { kind: 'coins', name: '500 XP' }, prem: { kind: 'boost', name: '+50% XP buff' } },
  { lvl: 19, free: { kind: 'avatar', name: 'Бейдж KNIGHT' }, prem: { kind: 'tshirt', name: 'Футболка CX' } },
  { lvl: 20, free: { kind: 'coins', name: '800 бонусов' }, prem: { kind: 'hoodie', name: 'Худи CyberX' } },
  { lvl: 21, free: { kind: 'hours', name: '+1 час' }, prem: { kind: 'cup', name: 'Champion-кружка' } },
];

function RewardStrip({ currentLevel = 15, hasPremium = false, claimedThru = 14 }) {
  const rewards = SAMPLE_REWARDS.map(r => ({
    ...r,
    locked: r.lvl > currentLevel,
    current: r.lvl === currentLevel,
    claimedFree: r.lvl <= claimedThru,
    claimedPrem: hasPremium && r.lvl <= claimedThru,
  }));
  return (
    <div style={{
      display: 'flex', gap: 8, padding: '20px 16px 4px',
      overflowX: 'auto', overflowY: 'hidden',
      scrollbarWidth: 'none',
    }}>
      {rewards.map(r => (
        <LevelColumn key={r.lvl}
          level={r.lvl}
          freeReward={r.free}
          premReward={r.prem}
          current={r.current}
          locked={r.locked}
          claimedFree={r.claimedFree}
          claimedPrem={r.claimedPrem}
          hasPremium={hasPremium}
        />
      ))}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Active task list inline section
// ─────────────────────────────────────────────────────────────
const SAMPLE_TASKS = [
  { icon: 'time', title: 'Закрепись за ПК', desc: '2 часа подряд в один день', xp: 150, progress: '1ч 36м', max: '2ч', deadline: 'до 23:59 сегодня', tier: CX.green },
  { icon: 'challenge', title: 'Сломай 50 черепов в CS2', desc: 'Headshot kills, любые карты', xp: 250, progress: 32, max: 50, deadline: 'осталось 3 дня', tier: CX.amber, steam: true },
  { icon: 'referral', title: 'Инвайтни друга', desc: 'Друг должен пополнить на 500₽+', xp: 500, progress: 0, max: 1, deadline: '∞ до конца сезона', tier: CX.legend },
  { icon: 'bar', title: 'Возьми Pepsi в баре', desc: 'Чек ≥ 250₽ через POS', xp: 80, progress: null, max: null, deadline: 'до конца недели', tier: CX.green },
];

function ActiveTasks({ tasks = SAMPLE_TASKS }) {
  return (
    <div style={{ padding: '8px 16px 0' }}>
      <div style={{
        display: 'flex', alignItems: 'baseline', justifyContent: 'space-between',
        marginBottom: 10, marginTop: 6,
      }}>
        <Display size={16} color={CX.white} tracking={0.12}>АКТИВНЫЕ ЗАДАНИЯ</Display>
        <span style={{ fontFamily: FONT_MONO, fontSize: 11, color: CX.textMute }}>{tasks.filter(t=>!t.done).length} активно</span>
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        {tasks.map((t, i) => (
          <TaskCard key={i} icon={t.icon} title={t.title} desc={t.desc} xp={t.xp}
            progress={t.progress} max={t.max} deadline={t.deadline}
            tierColor={t.tier} steam={t.steam} done={t.done} expiring={t.expiring}/>
        ))}
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// CTA red button
// ─────────────────────────────────────────────────────────────
function CTAButton({ label = 'ОТКРЫТЬ ВСЕ ЗАДАНИЯ', color = CX.red, fullWidth = true, icon }) {
  return (
    <div style={{
      margin: '14px 16px 4px',
      padding: '15px 16px',
      borderRadius: 10,
      background: color === CX.premiumGold
        ? `linear-gradient(135deg, ${CX.gold}, ${CX.premiumGold} 60%, #B8860B)`
        : `linear-gradient(180deg, ${color}, ${color === CX.red ? CX.redDeep : color})`,
      boxShadow: `0 8px 24px ${color}55, inset 0 1px 0 rgba(255,255,255,0.2)`,
      display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10,
      fontFamily: FONT_DISPLAY, fontSize: 16, letterSpacing: '0.15em',
      color: color === CX.premiumGold ? '#3a2700' : CX.white, fontWeight: 700,
      textAlign: 'center', width: fullWidth ? 'auto' : 'fit-content',
      position: 'relative', overflow: 'hidden',
    }}>
      {icon}
      <span>{label}</span>
      <svg width="14" height="12" viewBox="0 0 14 12"><path d="M2 6 L11 6 M7 2 L11 6 L7 10" stroke={color === CX.premiumGold ? '#3a2700' : CX.white} strokeWidth="2.2" fill="none" strokeLinecap="round" strokeLinejoin="round"/></svg>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Season meta strip — "До 16 уровня: 1500 XP"
// ─────────────────────────────────────────────────────────────
function SeasonProgress({ toLevel = 16, xpLeft = 1500, daysLeft = 47 }) {
  return (
    <div style={{ margin: '16px 16px 0', padding: '12px 14px', borderRadius: 10,
      background: CX.card, border: `1px solid ${CX.line}`,
      display: 'flex', alignItems: 'center', gap: 12,
    }}>
      <div style={{
        width: 36, height: 36, borderRadius: 8, flexShrink: 0,
        background: `${CX.amber}1F`, border: `1px solid ${CX.amber}44`,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        boxShadow: `0 0 12px ${CX.amber}33`,
      }}>
        <svg width="20" height="20" viewBox="0 0 24 24" fill={CX.amber}><path d="M14 2 L4 14 L11 14 L9 22 L20 10 L13 10 Z" filter={`drop-shadow(0 0 4px ${CX.amber}66)`}/></svg>
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontFamily: FONT_BODY, fontSize: 11, color: CX.textMute, letterSpacing: 0.4, textTransform: 'uppercase' }}>До уровня {toLevel}</div>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 5, marginTop: 1 }}>
          <span style={{ fontFamily: FONT_DISPLAY, fontSize: 22, color: CX.amber, letterSpacing: '0.04em' }}>
            <MonoNum n={xpLeft}/>
          </span>
          <span style={{ fontFamily: FONT_BODY, fontSize: 12, color: CX.textSec }}>XP</span>
        </div>
      </div>
      <div style={{ textAlign: 'right' }}>
        <div style={{ fontFamily: FONT_BODY, fontSize: 10, color: CX.textMute, letterSpacing: 0.4, textTransform: 'uppercase' }}>Осталось</div>
        <div style={{ fontFamily: FONT_MONO, fontSize: 15, color: CX.white, fontWeight: 600 }}>{daysLeft} дней</div>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// MAIN SCREEN — STATE: {early|mid|late|done}
// ─────────────────────────────────────────────────────────────
function MainScreen({ state = 'mid' }) {
  const profiles = {
    early: { nick: 'SPECTRE_05', initials: 'SP', level: 5, xp: 800, nextXp: 1200, premium: false, claimedThru: 4, currentLevel: 5 },
    mid: { nick: 'TENZ_RU', initials: 'TZ', level: 15, xp: 3500, nextXp: 5000, premium: false, claimedThru: 14, currentLevel: 15 },
    late: { nick: 'NEON_K', initials: 'NK', level: 25, xp: 12200, nextXp: 14000, premium: true, claimedThru: 24, currentLevel: 25 },
    done: { nick: 'WRAITH_42', initials: 'WR', level: 30, xp: 30000, nextXp: 30000, premium: true, claimedThru: 30, currentLevel: 30 },
  };
  const p = profiles[state];
  const title = {
    early: 'СЕЗОН 1 • ОПЕРАЦИЯ COPPER',
    mid: 'СЕЗОН 1 • ОПЕРАЦИЯ COPPER',
    late: 'СЕЗОН 1 • ОПЕРАЦИЯ COPPER',
    done: 'СЕЗОН 1 ✓ ЗАВЕРШЕН',
  }[state];

  return (
    <PhoneFrame>
      <CXBackground accent={state === 'done' ? CX.legend : CX.red}/>
      <div style={{ position: 'relative', height: '100%', overflowY: 'auto', paddingBottom: 90, scrollbarWidth: 'none' }}>
        <CXHeader title={title} sub={state === 'done' ? 'Дождись Сезона 2 — старт 01.07.2026' : 'до конца сезона: 47 дней'}/>

        {/* Banner if done */}
        {state === 'done' && (
          <div style={{
            margin: '4px 16px 0', padding: 14, borderRadius: 12,
            background: `linear-gradient(135deg, ${CX.legend}33, ${CX.legendHi}22)`,
            border: `1px solid ${CX.legend}77`,
            boxShadow: `0 0 24px ${CX.legend}44`,
            textAlign: 'center',
          }}>
            <Display size={14} color={CX.legendHi} tracking={0.18}>ВСЁ ВЗЯТО. ТЫ — LEGEND S1.</Display>
            <div style={{ marginTop: 6, fontFamily: FONT_BODY, fontSize: 12, color: CX.textSec }}>
              Статус «Legend Сезон 1» закреплён за тобой навсегда. До Сезона 2: 14 дней.
            </div>
          </div>
        )}

        <div style={{ marginTop: state === 'done' ? 12 : 4 }}>
          <ProfileCard nick={p.nick} level={p.level} xp={p.xp} nextXp={p.nextXp} premium={p.premium} initials={p.initials}/>
        </div>

        {state !== 'done' && <SeasonProgress
          toLevel={p.level + 1}
          xpLeft={p.nextXp - p.xp}
          daysLeft={47}
        />}

        <TabPills active="rewards"/>

        <RewardStrip currentLevel={p.currentLevel} hasPremium={p.premium} claimedThru={p.claimedThru}/>

        {/* Active tasks */}
        {state === 'done' ? (
          <div style={{ padding: '24px 16px', textAlign: 'center' }}>
            <Display size={16} color={CX.textSec} tracking={0.12}>СЕЗОН ПРОЙДЕН ПОЛНОСТЬЮ</Display>
            <div style={{ marginTop: 6, fontFamily: FONT_BODY, fontSize: 13, color: CX.textMute, lineHeight: 1.5 }}>
              Заданий больше нет. Отдыхай, фрагай в своё удовольствие — XP не сгорит, награды не отнимут.
            </div>
          </div>
        ) : (
          <ActiveTasks tasks={state === 'early'
            ? SAMPLE_TASKS.slice(0, 3)
            : state === 'late'
            ? [
                { ...SAMPLE_TASKS[1], expiring: true, deadline: 'осталось 2 часа' },
                ...SAMPLE_TASKS.slice(0, 1),
                { ...SAMPLE_TASKS[2], xp: 750 },
              ]
            : SAMPLE_TASKS
          }/>
        )}

        {state !== 'done' && <CTAButton label="ОТКРЫТЬ ВСЕ ЗАДАНИЯ"/>}

        {!p.premium && state !== 'done' && (
          <div style={{
            margin: '14px 16px 24px', padding: 14, borderRadius: 12,
            background: `linear-gradient(135deg, rgba(255,215,0,0.08), rgba(184,134,11,0.04))`,
            border: `1px solid ${CX.premiumGold}33`,
            display: 'flex', alignItems: 'center', gap: 12,
          }}>
            <PremiumStar size={36}/>
            <div style={{ flex: 1 }}>
              <div style={{ fontFamily: FONT_DISPLAY, fontSize: 13, color: CX.premiumGold, letterSpacing: '0.14em' }}>PREMIUM PASS</div>
              <div style={{ fontFamily: FONT_BODY, fontSize: 11.5, color: CX.textSec, marginTop: 2, lineHeight: 1.35 }}>
                +50% XP, эксклюзивные награды, ДР под ключ на 30 ур.
              </div>
            </div>
            <svg width="14" height="14" viewBox="0 0 14 14"><path d="M4 2 L10 7 L4 12" stroke={CX.premiumGold} strokeWidth="2" fill="none" strokeLinecap="round"/></svg>
          </div>
        )}
      </div>
      <BottomNav active="pass"/>
    </PhoneFrame>
  );
}

Object.assign(window, { PhoneFrame, CXBackground, ProfileCard, TabPills, RewardStrip, ActiveTasks, CTAButton, SeasonProgress, MainScreen, SAMPLE_REWARDS, SAMPLE_TASKS });
