import { Link } from '@tanstack/react-router'
import { useAuthStore } from '@/store/auth-store'
import { useAuthModalStore } from '@/store/auth-modal-store'
import { useGamification, useLeaderboard } from '@/hooks/use-gamification'
import { XP_REWARDS } from '@/lib/gamification-service'

const LEVEL_LABEL: Record<string, string> = {
  beginner: 'Beginner',
  bronze: 'Bronze',
  silver: 'Silver',
  gold: 'Gold',
  master: 'Master',
}

function calcNumericLevel(xp: number) {
  return Math.max(1, Math.floor(xp / 100))
}
function xpForNext(xp: number) {
  return (Math.floor(xp / 100) + 1) * 100
}

const EARN_ITEMS = [
  { label: 'Hoàn thành mục tiêu ngày', amt: 10 },
  { label: 'Mốc chuỗi (Streak)',       amt: 20 },
  { label: 'Xem quảng cáo',            amt: 5  },
  { label: 'Chia sẻ với bạn bè',       amt: 15 },
]

const SPEND_ITEMS = [
  { label: 'Streak Freeze',       amt: 20, desc: 'Giữ streak 1 ngày nghỉ' },
  { label: 'AI Writing Feedback', amt: 30, desc: 'Phân tích bài viết sâu' },
  { label: 'Bộ thẻ Premium',      amt: 50, desc: 'Mở khoá toàn bộ chủ đề' },
  { label: 'Đổi theme hiếm',      amt: 40, desc: 'Giao diện Atelier Noir' },
]

type Badge = { id: string; name: string; desc: string; earned: boolean; progress?: number; icon: string; color: string }

const BADGES: Badge[] = [
  { id: 'b1', name: 'Khởi hành',    desc: 'Học ngày đầu tiên',     earned: true,  icon: 'auto_awesome', color: 'var(--at-brand)' },
  { id: 'b2', name: 'Một tuần',     desc: '7 ngày liên tiếp',      earned: false, progress: 40, icon: 'local_fire_department', color: 'var(--at-streak)' },
  { id: 'b3', name: 'Bền bỉ',       desc: '30 ngày liên tiếp',     earned: false, progress: 10, icon: 'local_fire_department', color: 'var(--at-warm)' },
  { id: 'b4', name: 'Mọt sách',     desc: 'Thuộc 100 từ vựng',     earned: false, progress: 30, icon: 'style', color: '#8B5CF6' },
  { id: 'b5', name: 'Nhà ngôn ngữ', desc: 'Thuộc 500 từ vựng',     earned: false, progress: 10, icon: 'style', color: '#8B5CF6' },
  { id: 'b6', name: 'Điểm số vàng', desc: 'Đạt 800+ TOEIC',        earned: false, progress: 20, icon: 'emoji_events', color: 'var(--at-good)' },
  { id: 'b7', name: 'Thí sinh',     desc: 'Hoàn thành 10 đề full', earned: false, progress: 0,  icon: 'fact_check', color: 'var(--at-brand)' },
  { id: 'b8', name: 'Cây viết',     desc: 'Gửi 20 bài AI Writing', earned: false, progress: 10, icon: 'edit_note', color: 'var(--at-good)' },
]

function Coin({ size = 14 }: { size?: number }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" style={{ display: 'inline-block', verticalAlign: '-2px' }}>
      <circle cx="12" cy="12" r="10" fill="#F5B94A" stroke="#C9902F" strokeWidth="1.2" />
      <circle cx="12" cy="12" r="7" fill="none" stroke="#C9902F" strokeWidth="0.8" opacity="0.6" />
      <text x="12" y="15.5" textAnchor="middle" fontFamily="var(--at-serif)" fontSize="9.5" fontWeight="700" fill="#7B5210">XU</text>
    </svg>
  )
}

export function Dashboard() {
  const user = useAuthStore((s) => s.user)
  const openModal = useAuthModalStore((s) => s.open)
  const { data: gam, isLoading } = useGamification()
  const { data: leaderboard } = useLeaderboard()

  if (!user) {
    return (
      <div className="px-4 lg:px-6 py-20 flex flex-col items-center text-center gap-4">
        <div className="at-serif italic text-5xl" style={{ color: 'var(--at-mute-2)' }}>Thành tích</div>
        <p className="max-w-sm" style={{ color: 'var(--at-mute)' }}>
          Đăng nhập để xem streak, XP, Xu và bảng xếp hạng của bạn.
        </p>
        <button
          onClick={() => openModal('login')}
          className="mt-2 px-6 py-2.5 rounded-xl font-semibold text-sm hover:opacity-90 transition"
          style={{ background: 'var(--at-ink)', color: 'var(--at-paper)' }}
        >
          Đăng nhập
        </button>
      </div>
    )
  }

  const xu = gam?.xu ?? 50
  const streak = gam?.streak ?? 0
  const xp = gam?.xp ?? 0
  const levelLabel = LEVEL_LABEL[gam?.level ?? 'beginner']
  const numericLevel = calcNumericLevel(xp)
  const nextLevelXp = xpForNext(xp)
  const xpIntoLevel = xp - numericLevel * 100
  const levelPct = Math.round((xpIntoLevel / 100) * 100)
  const xpLeft = nextLevelXp - xp

  // Week metrics
  const userLbRow = leaderboard?.find((r) => r.userId === user.id)
  const weeklyXp = userLbRow?.xpEarned ?? 0
  const weeklyCompleted = Math.min(Math.floor(weeklyXp / XP_REWARDS.test), 5)
  const weekGoalTotal = 5

  // 7-day history mock pattern — actual tracking would need daily_activity table
  const todayDayIdx = (new Date().getDay() + 6) % 7 // Mon=0..Sun=6
  const history = ['T2', 'T3', 'T4', 'T5', 'T6', 'T7', 'CN'].map((d, i) => {
    if (i === todayDayIdx) return { d, state: 'today' as const }
    if (i < todayDayIdx) return { d, state: i < weeklyCompleted ? 'done' as const : 'empty' as const }
    return { d, state: 'future' as const }
  })

  // Leaderboard display (top 5, highlight self)
  const board = (leaderboard ?? []).slice(0, 5).map((row, idx) => ({
    rank: idx + 1,
    name: row.userId === user.id ? `${user.name} (Bạn)` : `User ${row.userId.slice(0, 6)}`,
    xp: row.xpEarned,
    you: row.userId === user.id,
    avatar: (row.userId === user.id ? user.name : 'U').charAt(0).toUpperCase(),
  }))

  return (
    <div className="px-6 lg:px-10 py-10 page-enter">
      {/* Editorial head */}
      <div className="flex flex-col lg:flex-row lg:items-end lg:justify-between gap-6 mb-10">
        <div>
          <div className="at-eyebrow mb-3">Thành tích</div>
          <h1 className="at-title text-4xl lg:text-[44px]">
            Bảng <i>thành tích</i>
          </h1>
          <p className="mt-4 text-sm" style={{ color: 'var(--at-mute)' }}>
            Xin chào, <b style={{ color: 'var(--at-ink)' }}>{user.name}</b> — tiếp tục chuỗi học tập nhé!
          </p>
        </div>
        <div className="flex gap-2.5 flex-shrink-0">
          <button
            className="inline-flex items-center gap-2 px-4 py-2.5 rounded-xl text-[13.5px] font-semibold hover:bg-[var(--at-line-2)] transition-colors"
            style={{ background: 'var(--at-surface)', border: '1px solid var(--at-line)', color: 'var(--at-ink-2)' }}
          >
            <span className="material-symbols-outlined" style={{ fontSize: 15 }}>share</span>
            Chia sẻ
          </button>
          <Link
            to="/toeic"
            className="inline-flex items-center gap-2 px-5 py-2.5 rounded-xl text-[13.5px] font-semibold hover:opacity-90 transition-opacity"
            style={{ background: 'var(--at-ink)', color: 'var(--at-paper)' }}
          >
            <span className="material-symbols-outlined" style={{ fontSize: 15 }}>play_arrow</span>
            Học tiếp
          </Link>
        </div>
      </div>

      {isLoading ? (
        <div className="grid grid-cols-1 md:grid-cols-3 gap-5 mb-5">
          {[1, 2, 3].map((i) => (
            <div key={i} className="rounded-2xl h-32 animate-pulse" style={{ background: 'var(--at-surface)', border: '1px solid var(--at-line)' }} />
          ))}
        </div>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-3 gap-5 mb-5" style={{ gridTemplateColumns: '1fr 1.2fr 1fr' }}>
          {/* XU */}
          <div
            className="rounded-2xl p-5 relative overflow-hidden"
            style={{ background: 'var(--at-surface)', border: '1px solid var(--at-line)' }}
          >
            <div
              className="absolute inset-0 pointer-events-none"
              style={{ background: 'radial-gradient(120% 80% at 100% 0%, color-mix(in oklab, #F5B94A 18%, transparent) 0%, transparent 55%)' }}
            />
            <div className="relative">
              <div className="at-eyebrow" style={{ color: '#B88432' }}>Số dư Xu</div>
              <div className="flex items-baseline gap-2.5 mt-2">
                <div className="at-serif" style={{ fontSize: 54, fontWeight: 400, letterSpacing: '-0.03em', lineHeight: 0.95 }}>
                  {xu}
                </div>
                <Coin size={26} />
              </div>
              <div className="text-[12.5px] mt-2.5 max-w-[200px]" style={{ color: 'var(--at-mute)' }}>
                Dùng để mở tính năng premium, freeze streak hoặc đổi giao diện.
              </div>
            </div>
          </div>

          {/* STREAK (featured, ink) */}
          <div
            className="rounded-2xl p-5 relative overflow-hidden"
            style={{
              background: 'linear-gradient(135deg, var(--at-ink) 0%, color-mix(in oklab, var(--at-ink) 88%, var(--at-brand)) 100%)',
              color: 'var(--at-paper)',
            }}
          >
            <div
              className="absolute at-serif italic"
              style={{ top: -20, right: -20, fontSize: 160, opacity: 0.08, lineHeight: 1 }}
            >
              ♦
            </div>
            <div className="at-eyebrow" style={{ color: 'color-mix(in oklab, var(--at-paper) 70%, transparent)' }}>
              Chuỗi học tập
            </div>
            <div className="flex items-baseline gap-2.5 mt-2">
              <div className="at-serif" style={{ fontSize: 54, fontWeight: 400, letterSpacing: '-0.03em', lineHeight: 0.95 }}>
                {streak}
              </div>
              <div className="at-serif italic" style={{ fontSize: 26, fontWeight: 300 }}>ngày</div>
              <span className="material-symbols-outlined" style={{ fontSize: 28, color: '#F5B94A', fontVariationSettings: "'FILL' 1" }}>
                local_fire_department
              </span>
            </div>
            <div className="text-[12.5px] opacity-75 mt-2.5">Giữ vững chuỗi học mỗi ngày nhé!</div>
          </div>

          {/* LEVEL */}
          <div className="rounded-2xl p-5" style={{ background: 'var(--at-surface)', border: '1px solid var(--at-line)' }}>
            <div className="at-eyebrow">Cấp độ</div>
            <div className="flex items-baseline justify-between mt-2">
              <div className="flex items-baseline gap-2.5">
                <div className="at-serif" style={{ fontSize: 54, fontWeight: 400, letterSpacing: '-0.03em', lineHeight: 0.95 }}>
                  {numericLevel}
                </div>
                <div className="at-serif italic" style={{ fontSize: 20, color: 'var(--at-mute)' }}>Level</div>
              </div>
              <div
                className="w-11 h-11 rounded-xl grid place-items-center"
                style={{ background: 'var(--at-paper-2)', color: 'var(--at-brand)' }}
              >
                <span className="material-symbols-outlined" style={{ fontSize: 22 }}>emoji_events</span>
              </div>
            </div>
            <div className="mt-2.5">
              <span className="at-chip at-chip-warm" style={{ fontSize: 10.5 }}>
                <span className="at-chip-dot" />
                Hạng {levelLabel}
              </span>
            </div>
          </div>
        </div>
      )}

      {/* Row 2 — level ring + week goal + history */}
      <div className="grid grid-cols-1 gap-5 mb-5" style={{ gridTemplateColumns: 'minmax(0, 1fr) minmax(0, 1.4fr)' }}>
        {/* Level progress ring */}
        <div className="rounded-2xl p-5" style={{ background: 'var(--at-surface)', border: '1px solid var(--at-line)' }}>
          <div className="flex justify-between items-baseline">
            <div className="at-serif text-[20px] tracking-tight" style={{ color: 'var(--at-ink)', fontWeight: 500 }}>
              Tiến độ <i style={{ color: 'var(--at-brand)', fontStyle: 'italic' }}>cấp độ</i>
            </div>
            <span className="at-serif italic text-[11px]" style={{ color: 'var(--at-mute)' }}>
              Lv.{numericLevel} → Lv.{numericLevel + 1}
            </span>
          </div>
          <div className="flex justify-center py-5">
            <LevelRing value={levelPct} xpInto={xpIntoLevel} xpGoal={100} />
          </div>
          <div className="text-center text-[12.5px] mb-3" style={{ color: 'var(--at-mute)' }}>
            Chỉ còn <b style={{ color: 'var(--at-brand)' }}>{xpLeft} XP</b> nữa để đạt Level {numericLevel + 1}!
          </div>
          <button
            className="w-full py-2.5 rounded-xl text-[13px] font-semibold transition-colors hover:bg-[var(--at-line-2)]"
            style={{ background: 'var(--at-surface)', border: '1px solid var(--at-line)', color: 'var(--at-ink-2)' }}
          >
            <span className="material-symbols-outlined inline-block align-middle mr-1" style={{ fontSize: 15 }}>target</span>
            Xem nhiệm vụ XP
          </button>
        </div>

        {/* Week goal + history */}
        <div className="flex flex-col gap-5">
          <div className="rounded-2xl p-5" style={{ background: 'var(--at-surface)', border: '1px solid var(--at-line)' }}>
            <div className="flex justify-between items-start mb-3">
              <div>
                <div className="at-serif text-[20px] tracking-tight" style={{ color: 'var(--at-ink)', fontWeight: 500 }}>
                  Mục tiêu <i style={{ color: 'var(--at-good)', fontStyle: 'italic' }}>tuần</i>
                </div>
                <div className="text-xs mt-1" style={{ color: 'var(--at-mute)' }}>
                  Hoàn thành {weekGoalTotal} bài học mỗi tuần
                </div>
              </div>
              <div
                className="at-serif"
                style={{ fontSize: 36, fontWeight: 400, letterSpacing: '-0.02em', lineHeight: 1, color: 'var(--at-good)' }}
              >
                {weeklyCompleted}
                <span className="italic" style={{ color: 'var(--at-mute-2)' }}>/{weekGoalTotal}</span>
              </div>
            </div>
            <div className="at-bar" style={{ height: 8 }}>
              <span style={{ width: `${(weeklyCompleted / weekGoalTotal) * 100}%`, background: 'var(--at-good)' }} />
            </div>
            <div className="flex justify-between mt-2.5 text-[11.5px]" style={{ color: 'var(--at-mute)' }}>
              <span>Đã hoàn thành</span>
              {weeklyCompleted >= weekGoalTotal ? (
                <span>
                  <b style={{ color: 'var(--at-good)' }}>Đạt mục tiêu!</b> · +50 XP thưởng
                </span>
              ) : (
                <span>
                  Còn <b style={{ color: 'var(--at-good)' }}>{weekGoalTotal - weeklyCompleted} bài</b>
                </span>
              )}
            </div>
          </div>

          <div className="rounded-2xl p-5" style={{ background: 'var(--at-surface)', border: '1px solid var(--at-line)' }}>
            <div className="flex justify-between items-baseline mb-4">
              <div className="at-serif text-[20px] tracking-tight" style={{ color: 'var(--at-ink)', fontWeight: 500 }}>
                Lịch sử <i style={{ color: 'var(--at-streak)', fontStyle: 'italic' }}>rèn luyện</i>
              </div>
              <span className="at-serif italic text-[11px]" style={{ color: 'var(--at-mute)' }}>7 ngày qua</span>
            </div>
            <div className="grid grid-cols-7 gap-2">
              {history.map((h, i) => {
                const isDone = h.state === 'done'
                const isToday = h.state === 'today'
                return (
                  <div key={i} className="flex flex-col items-center gap-2">
                    <div
                      style={{
                        fontSize: 10,
                        fontWeight: 700,
                        letterSpacing: '0.1em',
                        textTransform: 'uppercase',
                        color: isToday ? 'var(--at-brand)' : 'var(--at-mute)',
                      }}
                    >
                      {isToday ? 'H.NAY' : h.d}
                    </div>
                    <div
                      className="grid place-items-center"
                      style={{
                        width: 44,
                        height: 44,
                        borderRadius: 12,
                        background: isDone ? 'color-mix(in oklab, var(--at-good) 18%, transparent)' : 'transparent',
                        border: isToday
                          ? '2px dashed var(--at-brand)'
                          : isDone
                            ? '1px solid color-mix(in oklab, var(--at-good) 30%, transparent)'
                            : '1px solid var(--at-line)',
                        color: isDone ? 'var(--at-good)' : isToday ? 'var(--at-brand)' : 'var(--at-mute-2)',
                      }}
                    >
                      {isDone && <span className="material-symbols-outlined" style={{ fontSize: 18 }}>check</span>}
                      {isToday && <span className="material-symbols-outlined" style={{ fontSize: 14 }}>play_arrow</span>}
                    </div>
                  </div>
                )
              })}
            </div>
          </div>
        </div>
      </div>

      {/* Row 3 — Xu shop + leaderboard */}
      <div className="grid grid-cols-1 gap-5 mb-5" style={{ gridTemplateColumns: 'minmax(0, 1fr) minmax(0, 1.4fr)' }}>
        {/* Xu shop */}
        <div className="rounded-2xl p-5" style={{ background: 'var(--at-surface)', border: '1px solid var(--at-line)' }}>
          <div className="flex justify-between items-baseline mb-3.5">
            <div className="at-serif text-[20px] tracking-tight" style={{ color: 'var(--at-ink)', fontWeight: 500 }}>
              Cửa hàng <i style={{ color: '#B88432', fontStyle: 'italic' }}>Xu</i>
            </div>
            <span className="at-chip" style={{ fontSize: 10.5 }}>
              <Coin size={11} /> {xu} xu
            </span>
          </div>

          <div
            style={{ fontSize: 10, fontWeight: 700, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--at-good)', marginBottom: 8 }}
          >
            Kiếm xu
          </div>
          {EARN_ITEMS.map((e, i) => (
            <div
              key={i}
              className="flex justify-between items-center py-2.5"
              style={{ borderTop: i === 0 ? 'none' : '1px solid var(--at-line)' }}
            >
              <span className="text-[13px]" style={{ color: 'var(--at-ink-2)' }}>{e.label}</span>
              <span
                className="inline-flex items-center gap-1 text-xs font-bold"
                style={{ color: 'var(--at-good)' }}
              >
                +{e.amt} <Coin size={11} />
              </span>
            </div>
          ))}

          <div
            style={{
              fontSize: 10,
              fontWeight: 700,
              letterSpacing: '0.14em',
              textTransform: 'uppercase',
              color: '#C8383E',
              marginTop: 18,
              marginBottom: 8,
            }}
          >
            Tiêu xu
          </div>
          {SPEND_ITEMS.map((s, i) => (
            <div
              key={i}
              className="flex justify-between items-center py-2.5 gap-2.5"
              style={{ borderTop: i === 0 ? 'none' : '1px solid var(--at-line)' }}
            >
              <div className="min-w-0 flex-1">
                <div className="text-[13px] font-medium" style={{ color: 'var(--at-ink-2)' }}>{s.label}</div>
                <div className="text-[11px]" style={{ color: 'var(--at-mute)' }}>{s.desc}</div>
              </div>
              <button
                disabled={xu < s.amt}
                className="px-2.5 py-1 rounded-lg text-[11.5px] flex-shrink-0 inline-flex items-center gap-1 transition-opacity disabled:opacity-50"
                style={{ background: 'var(--at-surface)', border: '1px solid var(--at-line)', color: 'var(--at-ink-2)', fontWeight: 600 }}
              >
                {s.amt} <Coin size={11} />
              </button>
            </div>
          ))}
        </div>

        {/* Leaderboard */}
        <div
          className="rounded-2xl overflow-hidden"
          style={{ background: 'var(--at-surface)', border: '1px solid var(--at-line)' }}
        >
          <div className="flex justify-between items-center px-5 py-4" style={{ borderBottom: '1px solid var(--at-line)' }}>
            <div>
              <div className="at-serif text-[20px] tracking-tight" style={{ color: 'var(--at-ink)', fontWeight: 500 }}>
                Bảng xếp hạng <i style={{ color: 'var(--at-brand)', fontStyle: 'italic' }}>tuần</i>
              </div>
              <div className="text-xs mt-0.5" style={{ color: 'var(--at-mute)' }}>Top học viên tuần này</div>
            </div>
            <span className="at-chip at-chip-brand" style={{ fontSize: 10.5 }}>
              <span className="at-chip-dot" />
              Top tuần này
            </span>
          </div>
          <div
            className="grid px-5 py-2.5 text-[10px]"
            style={{
              gridTemplateColumns: '60px 1fr auto',
              gap: 12,
              background: 'var(--at-paper-2)',
              fontWeight: 700,
              color: 'var(--at-mute)',
              letterSpacing: '0.12em',
              textTransform: 'uppercase',
            }}
          >
            <span>Hạng</span>
            <span>Người học</span>
            <span>XP tuần</span>
          </div>
          {board.length === 0 ? (
            <div className="px-5 py-8 text-center text-sm" style={{ color: 'var(--at-mute)' }}>
              Chưa có ai trên bảng xếp hạng tuần này.
            </div>
          ) : (
            board.map((p) => {
              const rankColors: Record<number, string> = { 1: '#F5B94A', 2: '#BFC5CC', 3: '#C8844A' }
              const rc = rankColors[p.rank]
              return (
                <div
                  key={p.rank}
                  className="grid items-center px-5 py-3.5"
                  style={{
                    gridTemplateColumns: '60px 1fr auto',
                    gap: 12,
                    borderTop: '1px solid var(--at-line)',
                    background: p.you ? 'color-mix(in oklab, var(--at-brand) 6%, transparent)' : 'transparent',
                  }}
                >
                  <div
                    className="w-7 h-7 rounded-full grid place-items-center at-serif"
                    style={{
                      background: rc ? `color-mix(in oklab, ${rc} 25%, var(--at-paper-2))` : 'var(--at-paper-2)',
                      border: rc ? `1px solid ${rc}` : '1px solid var(--at-line)',
                      color: rc ? 'var(--at-ink)' : 'var(--at-mute)',
                      fontSize: 14,
                      fontWeight: 500,
                    }}
                  >
                    {p.rank}
                  </div>
                  <div className="flex items-center gap-2.5 min-w-0">
                    <div
                      className="w-8 h-8 rounded-full grid place-items-center text-[13px] font-bold flex-shrink-0"
                      style={{ background: p.you ? 'var(--at-brand)' : 'var(--at-ink-2)', color: 'var(--at-paper)' }}
                    >
                      {p.avatar}
                    </div>
                    <div className="min-w-0 overflow-hidden text-ellipsis whitespace-nowrap">
                      <span
                        className="text-[13.5px]"
                        style={{ fontWeight: p.you ? 700 : 500, color: p.you ? 'var(--at-brand)' : 'var(--at-ink)' }}
                      >
                        {p.name}
                      </span>
                    </div>
                  </div>
                  <div className="at-serif" style={{ fontSize: 17, fontWeight: 400, letterSpacing: '-0.01em' }}>
                    {p.xp}
                    <span className="italic ml-1" style={{ fontSize: 11, color: 'var(--at-mute)', fontWeight: 400 }}>XP</span>
                  </div>
                </div>
              )
            })
          )}
        </div>
      </div>

      {/* Row 4 — Badges */}
      <div className="rounded-2xl p-5" style={{ background: 'var(--at-surface)', border: '1px solid var(--at-line)' }}>
        <div className="flex justify-between items-baseline mb-4">
          <div>
            <div className="at-eyebrow mb-1">Huy hiệu</div>
            <div className="at-serif text-[20px] tracking-tight" style={{ color: 'var(--at-ink)', fontWeight: 500 }}>
              Thành tựu <i style={{ color: 'var(--at-brand)', fontStyle: 'italic' }}>đã mở</i>
            </div>
          </div>
          <span className="text-xs" style={{ color: 'var(--at-mute)' }}>
            <b style={{ color: 'var(--at-ink)' }}>{BADGES.filter((b) => b.earned).length}</b> / {BADGES.length} mở khoá
          </span>
        </div>
        <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-3.5">
          {BADGES.map((b) => (
            <div
              key={b.id}
              className="p-4 rounded-2xl relative"
              style={{
                background: b.earned ? 'var(--at-surface)' : 'var(--at-paper-2)',
                border: '1px solid var(--at-line)',
                opacity: b.earned ? 1 : 0.72,
              }}
            >
              <div
                className="w-12 h-12 rounded-xl grid place-items-center mb-3"
                style={{
                  background: b.earned ? `color-mix(in oklab, ${b.color} 16%, transparent)` : 'var(--at-line-2)',
                  color: b.earned ? b.color : 'var(--at-mute-2)',
                }}
              >
                <span className="material-symbols-outlined" style={{ fontSize: 22 }}>{b.icon}</span>
              </div>
              <div
                className="at-serif mb-1"
                style={{ fontSize: 16, fontWeight: 500, letterSpacing: '-0.01em', color: 'var(--at-ink)' }}
              >
                {b.name}
              </div>
              <div className="text-[11.5px] leading-[1.4] mb-2" style={{ color: 'var(--at-mute)' }}>{b.desc}</div>
              {b.earned ? (
                <span className="at-chip at-chip-good" style={{ fontSize: 10 }}>
                  <span className="at-chip-dot" />
                  Đã mở
                </span>
              ) : (
                <div>
                  <div className="at-bar" style={{ height: 4, marginBottom: 4 }}>
                    <span style={{ width: `${b.progress ?? 0}%`, background: b.color }} />
                  </div>
                  <span className="text-[10.5px] font-semibold" style={{ color: 'var(--at-mute)' }}>
                    {b.progress ?? 0}% tiến độ
                  </span>
                </div>
              )}
            </div>
          ))}
        </div>
      </div>
    </div>
  )
}

function LevelRing({ value, xpInto, xpGoal }: { value: number; xpInto: number; xpGoal: number }) {
  const r = 80
  const c = 2 * Math.PI * r
  const offset = c - (value / 100) * c
  return (
    <div className="relative grid place-items-center" style={{ width: 180, height: 180 }}>
      <svg width="180" height="180">
        <circle cx="90" cy="90" r={r} fill="none" stroke="var(--at-line-2)" strokeWidth="10" />
        <circle
          cx="90"
          cy="90"
          r={r}
          fill="none"
          stroke="var(--at-brand)"
          strokeWidth="10"
          strokeDasharray={c}
          strokeDashoffset={offset}
          strokeLinecap="round"
          transform="rotate(-90 90 90)"
          style={{ transition: 'stroke-dashoffset 0.6s cubic-bezier(0.2, 0.7, 0.2, 1)' }}
        />
      </svg>
      <div className="absolute text-center">
        <div className="at-serif" style={{ fontSize: 40, fontWeight: 400, letterSpacing: '-0.02em', lineHeight: 1, color: 'var(--at-ink)' }}>
          {value}%
        </div>
        <div style={{ fontSize: 10.5, color: 'var(--at-mute)', marginTop: 4, fontWeight: 600, letterSpacing: '0.1em' }}>
          {xpInto} / {xpGoal} XP
        </div>
      </div>
    </div>
  )
}
