/* ============================================================
   ROOY · 07 成就
   ───────────────────────────────────────────────────────────
   需求：成就墙。三类分组 —— 能力成就（关卡通关）/ 瞬间成就
   （ROOY 见证的"第一次"）/ 极限挑战（高难度）。

   结构：NavBar + Segmented (复盘/课程/成就) → hero（italic 7 +
   脚标 "/28"）+ 3 行 RarityRow → 三类成就的 2-col MedalCard 网格。

   italic anchor：已解锁数 7（hero）。
   accent budget：gold（瞬间成就高光 + 刚解锁卡边框 + 呼吸光）。

   刚解锁状态（justUnlocked）：1px gold border + 22px halo（0.26 alpha）
   呼吸光 —— Apple Fitness "ring closed" 量级，不是 Duolingo 宝石。
   ============================================================ */

function AchievementScreen({ onNav }) {
  const [tab, setTab] = React.useState('medals');

  return (
    <div style={{
      height: '100%', display: 'flex', flexDirection: 'column',
      background: R.bg, position: 'relative', color: R.ink, ...T.subhead,
    }}>
      <StatusBar/>

      <NavBar onBack={() => onNav && onNav('home')} title="滑雪学院"/>

      <div style={{ padding: '0 16px 8px', position: 'relative', zIndex: 1 }}>
        <Segmented value={tab} items={ACADEMY_TABS} onChange={(v) => {
          setTab(v);
          if (v === 'review') onNav && onNav('review');
          if (v === 'course') onNav && onNav('course');
        }}/>
      </div>

      <div style={{ flex: 1, overflowY: 'auto', position: 'relative', zIndex: 1, paddingBottom: 36 }}>

        {/* Hero —— italic 7 + 脚标 /28 + 右侧 rarity strip.
            alignItems: center 让左右在 hero 垂直中心轴对齐 (italic 7
            的 lineHeight 0.82 line box 较矮, 不能用 flex-end). */}
        <div style={{ padding: '20px 22px 0' }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 20 }}>
            {/* italic 7 是 anchor; 28 作为 7 的脚标 baseline-aligned,
                upright + N.reg, 表示 "已解锁 / 全部" 的比例. 不再额外
                出 "已解锁 · 共 28 个" 副标——脚标已经承担这条信息. */}
            <span style={{ display: 'inline-flex', alignItems: 'baseline', gap: 6 }}>
              <span style={{ ...N.italic, fontSize: 108, color: R.ink, lineHeight: 0.82 }}>7</span>
              <span style={{ ...N.reg, fontSize: 24, color: R.ink3, fontWeight: 500 }}>/28</span>
            </span>

            {/* Rarity completion strip — 3 thin rows, each gets a
               name + fraction + 2px progress. */}
            <div style={{
              flexShrink: 0, flex: '0 0 142px',
              display: 'flex', flexDirection: 'column', gap: 12,
            }}>
              <RarityRow l="能力" cur={3} max={8}/>
              <RarityRow l="瞬间" cur={4} max={16}/>
              <RarityRow l="极限" cur={0} max={4}/>
            </div>
          </div>
        </div>

        <div style={{ height: 32 }}/>

        {/* ── 能力成就 ─────────────────────────── */}
        <SectionTitle style={{ padding: '0 22px 14px' }} meta="3 / 8" subtitle="关卡通关">
          能力成就
        </SectionTitle>
        <MedalGrid items={[
          { n: '平行式',     d: '基础站位与平行下滑', w: '4 月 10 日', kind: 'cap', e: true },
          { n: '刃滑 I',     d: '基础立刃感觉',       w: '4 月 18 日', kind: 'cap', e: true },
          { n: '刃滑 II',    d: '稳定 40°',           w: '进行中',     kind: 'cap', e: true },
          { n: '短弯节奏',   d: '高频小幅转弯',       w: '下一步',     kind: 'cap', locked: true },
        ]}/>

        <div style={{ height: 28 }}/>

        {/* ── 瞬间成就 ─────────────────────────── */}
        <SectionTitle style={{ padding: '0 22px 14px' }} meta="4 / 16" subtitle={"ROOY 见证的“第一次”"}>
          瞬间成就
        </SectionTitle>
        <MedalGrid items={[
          { n: '首破 40°',      d: '立刃稳定一整趟',   w: '刚刚解锁', kind: 'moment', e: true,  hi: true, justUnlocked: true },
          { n: '生涯 100 km',   d: '累计垂降破百',      w: '4 月 22 日', kind: 'moment', e: true },
          { n: '日出第一道',    d: '清晨开板',          w: '锁定中',     kind: 'moment', locked: true },
          { n: '夜场一小时',    d: '夜灯下连滑 1h',     w: '锁定中',     kind: 'moment', locked: true },
        ]}/>

        <div style={{ height: 28 }}/>

        {/* ── 极限挑战 ─────────────────────────── */}
        <SectionTitle style={{ padding: '0 22px 14px' }} meta="0 / 4" subtitle="少数高难度任务">
          极限挑战
        </SectionTitle>
        <MedalGrid items={[
          { n: '高级雪道',      d: '黑道首滑完成',         w: '锁定中', kind: 'extreme', locked: true },
          { n: '破百公里',      d: '突破 100 km/h',        w: '锁定中', kind: 'extreme', locked: true },
        ]}/>

      </div>
    </div>
  );
}

function MedalGrid({ items }) {
  return (
    <div style={{
      padding: '0 16px',
      display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10,
    }}>
      {items.map((m, i) => <MedalCard key={i} m={m}/>)}
    </div>
  );
}

/* RarityRow — hero 右侧三档稀有度完成率行。单色 ink，靠 progress
   填充长度表达"离这档还差多少"。能力/瞬间/极限的语义差异由 name
   本身承担——三档同色避免触发"三色齐出"。 */
function RarityRow({ l, cur, max }) {
  const pct = max ? (cur / max) * 100 : 0;
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
      <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between' }}>
        <span style={{ ...T.footnote, color: R.ink2 }}>{l}</span>
        <span style={{ ...N.reg, ...T.footnote, color: R.ink, fontWeight: 600 }}>
          {cur} <span style={{ color: R.ink4 }}>/</span> {max}
        </span>
      </div>
      <div style={{ height: 2, background: R.hair, borderRadius: 1, overflow: 'hidden' }}>
        <div style={{ width: `${pct}%`, height: '100%', background: R.ink, borderRadius: 1 }}/>
      </div>
    </div>
  );
}


function MedalCard({ m }) {
  const isLocked = m.locked;
  const isCurrent = m.current;
  const isJustUnlocked = m.justUnlocked;
  const earned = m.e && !isCurrent && !isLocked;

  const Glyph = m.kind === 'moment' ? (m.hi ? TrophyGlyph : FlagGlyph)
              : m.kind === 'extreme' ? MountainGlyph
              : MedalGlyph;

  const iconBg = isCurrent ? `${R.rooy}1a`
              : isLocked ? R.systemFill
              : m.hi ? `${R.gold}1a`
              : R.ink;
  const iconColor = isCurrent ? 'var(--r-rooy)'
                  : isLocked ? R.ink3
                  : m.hi ? 'var(--r-gold)'
                  : '#fff';

  return (
    <div className={isJustUnlocked ? 'medal-glow' : ''} style={{
      padding: '14px 14px 12px',
      borderRadius: B.card,
      background: isLocked ? 'transparent' : R.card,
      border: isCurrent ? `1.5px solid ${R.rooy}`
            : isJustUnlocked ? `1px solid ${R.gold}`
            : isLocked ? `1px dashed ${R.hair2}`
            : 'none',
      opacity: isLocked ? 0.55 : 1,
      position: 'relative',
    }}>
      {isJustUnlocked && (
        <div style={{
          position: 'absolute', top: 10, right: 10,
          display: 'flex', alignItems: 'center', gap: 5,
        }}>
          <span style={{
            width: 6, height: 6, borderRadius: '50%', background: R.gold,
            boxShadow: `0 0 0 3px ${R.gold}33`,
          }}/>
          <span style={{ ...T.eyebrow, color: R.gold }}>刚刚</span>
        </div>
      )}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 12 }}>
        <div style={{
          width: 40, height: 40, borderRadius: 12,
          background: iconBg,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <Glyph size={20} color={iconColor}/>
        </div>
        {earned && !isJustUnlocked && (
          <svg width="16" height="16" viewBox="0 0 16 16"><circle cx="8" cy="8" r="7.2" fill={R.ink}/><path d="M4.5 8l2.5 2.5L11.5 5.5" stroke="#fff" strokeWidth="1.5" fill="none" strokeLinecap="round" strokeLinejoin="round"/></svg>
        )}
      </div>
      <p style={{ ...T.headline, color: R.ink }}>{m.n}</p>
      <p style={{ ...T.footnote, color: R.ink3, marginTop: 3 }}>{m.d}</p>
      <p style={{ ...T.footnote, color: isCurrent ? R.rooy : isLocked ? R.ink3 : m.hi ? R.gold : R.ink3, marginTop: 10 }}>{m.w}</p>
    </div>
  );
}

/* gold-glow keyframe — injected once */
if (typeof document !== 'undefined' && !document.getElementById('rooy-glow-style')) {
  const s = document.createElement('style');
  s.id = 'rooy-glow-style';
  s.textContent = `
    @keyframes rooyMedalGlow {
      0%,100% { box-shadow: 0 0 0 0 rgba(217,162,58,0); }
      50%     { box-shadow: 0 0 22px 1px rgba(217,162,58,0.26); }
    }
    .medal-glow { animation: rooyMedalGlow 3.2s ease-in-out infinite; }
  `;
  document.head.appendChild(s);
}

function FlagGlyph({ size = 18, color = '#0E1116' }) {
  return (
    <svg width={size} height={size} viewBox="0 0 18 18" fill="none">
      <path d="M4 2v14M4 3h9l-2 2.5L13 8H4" stroke={color} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
    </svg>
  );
}
function MountainGlyph({ size = 18, color = '#0E1116' }) {
  return (
    <svg width={size} height={size} viewBox="0 0 18 18" fill="none">
      <path d="M2 14L7 5l3 5 2-3 4 7H2z" stroke={color} strokeWidth="1.5" strokeLinejoin="round"/>
      <path d="M6 8l1-1.5L8 8" stroke={color} strokeWidth="1.5" strokeLinecap="round"/>
    </svg>
  );
}
function MedalGlyph({ size = 18, color = '#0E1116' }) {
  return (
    <svg width={size} height={size} viewBox="0 0 20 20" fill="none">
      <path d="M6.5 1.5L5 7.5M13.5 1.5L15 7.5" stroke={color} strokeWidth="1.6" strokeLinecap="round"/>
      <circle cx="10" cy="13" r="5" stroke={color} strokeWidth="1.6"/>
      <circle cx="10" cy="13" r="1.8" fill={color}/>
    </svg>
  );
}
function TrophyGlyph({ size = 20, color = '#0E1116' }) {
  return (
    <svg width={size} height={size} viewBox="0 0 22 22" fill="none">
      <path d="M6 3h10v3.5a5 5 0 01-10 0V3z" stroke={color} strokeWidth="1.6" strokeLinejoin="round"/>
      <path d="M3 4h3v2.5a2.5 2.5 0 01-3-2.5zM19 4h-3v2.5a2.5 2.5 0 003-2.5z" stroke={color} strokeWidth="1.6"/>
      <path d="M11 11.5v3.5M8 19h6" stroke={color} strokeWidth="1.6" strokeLinecap="round"/>
    </svg>
  );
}

Object.assign(window, { AchievementScreen, FlagGlyph, MountainGlyph, MedalGlyph, TrophyGlyph });
