// Stats screen — gamified: level + streak hero, cleaned vs remaining,
// space saved chart, weekly activity, achievements, recently-deleted grid.
/* global React, Sp, StatusBar, TabBar */

function StatsV1({ theme }) {
  const th = theme;
  const light = th.mode === 'light';

  // Mock data
  const total = 3276;
  const cleaned = 1284;
  // Of the cleaned set: ~32% deleted, ~68% kept
  const deleted = 411;
  const kept = cleaned - deleted;        // 873
  const remaining = total - cleaned;     // 1992 unreviewed
  const pct = Math.round((cleaned / total) * 100);
  // Each tile = 25 photos → more tiles, richer grid.
  const perTile = 25;
  const totalTiles = Math.ceil(total / perTile);       // 132
  const deletedTiles = Math.round(deleted / perTile);  // 16
  const keptTiles = Math.round(kept / perTile);        // 35
  const remainingTiles = totalTiles - deletedTiles - keptTiles;
  const level = 7;
  const xp = 640;
  const xpMax = 1000;
  const streak = 12;
  const spaceSavedMB = 4820;

  // 14-day streak calendar (0 = miss, 1-3 = intensity)
  const days = [1,2,1,0,2,3,3,2,1,0,2,3,3,2];
  const dayLabel = d => ['S','M','T','W','T','F','S'][d % 7];

  // Weekly bars (values 0-100)
  const weekly = [
    {d:'Mon', v:62, n:142},
    {d:'Tue', v:48, n:108},
    {d:'Wed', v:95, n:218},
    {d:'Thu', v:71, n:164},
    {d:'Fri', v:38, n:88},
    {d:'Sat', v:82, n:189},
    {d:'Sun', v:55, n:127},
  ];
  const weeklyTotal = weekly.reduce((a, b) => a + b.n, 0);

  // Space-saved mini-chart (last 14 days, cumulative GB curve)
  const saved = [0.3,0.5,0.8,1.1,1.3,1.6,2.0,2.3,2.6,3.1,3.4,3.9,4.3,4.8];
  const sparkPath = (() => {
    const max = Math.max(...saved);
    const w = 280, h = 60;
    return saved.map((v, i) => {
      const x = (i / (saved.length - 1)) * w;
      const y = h - (v / max) * h;
      return (i === 0 ? 'M' : 'L') + x.toFixed(1) + ',' + y.toFixed(1);
    }).join(' ');
  })();

  const achievements = [
    { t:'Early Bird',    sub:'7-day streak',  ic:'☀', unlocked:true,  c:'#FFE066', c2:'#FF8A3D' },
    { t:'Space Saver',   sub:'5GB cleared',   ic:'◉', unlocked:true,  c:'#6FF0B0', c2:'#2BB869' },
    { t:'Marathoner',    sub:'500 in a day',  ic:'⚡', unlocked:false, c:'#B794FF', c2:'#6B4BFF' },
    { t:'Collector',     sub:'100 favorites', ic:'★', unlocked:true,  c:'#FFD166', c2:'#F07A1A' },
    { t:'Perfectionist', sub:'Full month',    ic:'◆', unlocked:false, c:'#5BE3FF', c2:'#2F7BFF' },
    { t:'Centurion',     sub:'100-day streak',ic:'🔥', unlocked:false, c:'#F05BE8', c2:'#6B4BFF' },
  ];

  // Recently-deleted preview (12 color swatches simulating thumbnails)
  const recent = [
    '#4A5568','#2D3748','#744210','#22543D','#702459','#1A365D',
    '#553C9A','#742A2A','#276749','#97266D','#2A4365','#744210',
  ];

  // XP ring geometry
  const r = 38, C = 2 * Math.PI * r, xpFrac = xp / xpMax;

  return (
    <div style={{width:'100%',height:'100%',background:th.bg0,color:th.fg1,fontFamily:"'Syne',sans-serif",overflow:'hidden',position:'relative'}}>
      <StatusBar th={th}/>

      <div style={{padding:'4px 18px 0', overflowY:'auto', height:'calc(100% - 44px)'}}>
        {/* Header */}
        <div style={{display:'flex', alignItems:'center', gap:10, marginTop:8}}>
          <div style={{flex:1}}>
            <div style={{fontSize:11, color:th.fg3, fontWeight:500}}>Your progress</div>
            <div style={{fontSize:22, fontWeight:800, letterSpacing:'-0.02em', lineHeight:1.1}}>Statistics</div>
          </div>
          <div style={{width:36, height:36, borderRadius:10, background:th.s2, border:`1px solid ${th.b2}`, display:'flex', alignItems:'center', justifyContent:'center', fontSize:13, color:th.fg2}}>⇪</div>
        </div>

        {/* HERO — Progress toward next achievement (Space Saver: 5 GB cleared) */}
        <StatsHero
          streak={streak}
          light={light}
          achievement={{
            title:'Space Saver',
            sub:'Clear 5 GB of photos',
            icon:'◉',
            progress: 3.2,       // GB done
            target: 5.0,         // GB goal
            unit:'GB',
          }}
        />

        {/* Weekly streak — 7 flames right below hero so it's visible up top */}
        <WeeklyStreak th={th} light={light} weekly={weekly} streak={streak}/>

        {/* Library progress — grid of tiles. Pink = deleted (top-left), blue = kept. */}
        <LibraryProgressGrid
          th={th} light={light}
          total={total} kept={kept} deleted={deleted}
          totalTiles={totalTiles}
          deletedTiles={deletedTiles}
          keptTiles={keptTiles}
          remainingTiles={remainingTiles}
          perTile={perTile}
        />

        {/* Achievements */}
        <div style={{marginTop:16, marginBottom:8, display:'flex', alignItems:'baseline', justifyContent:'space-between'}}>
          <div style={{fontSize:13, fontWeight:700, color:th.fg2, letterSpacing:'0.06em', textTransform:'uppercase'}}>Achievements</div>
          <div style={{fontSize:11, color:th.fg3, fontWeight:500}}>3 of 6 unlocked</div>
        </div>
        <div style={{display:'grid', gridTemplateColumns:'1fr 1fr 1fr', gap:8}}>
          {achievements.map((a,i) => (
            <div key={i} style={{
              position:'relative', borderRadius:14, padding:'14px 8px 12px',
              background:th.bg1, border:`1px solid ${th.b2}`, boxShadow:th.cardShadow,
              display:'flex', flexDirection:'column', alignItems:'center', gap:6,
              overflow:'hidden',
              opacity: a.unlocked ? 1 : 0.55,
            }}>
              {a.unlocked && (
                <div style={{
                  position:'absolute', top:-16, left:'50%', transform:'translateX(-50%)',
                  width:60, height:60, borderRadius:999,
                  background:`radial-gradient(circle, ${a.c}55 0%, transparent 70%)`,
                  filter:'blur(8px)',
                }}/>
              )}
              <div style={{
                width:40, height:40, borderRadius:12,
                background: a.unlocked
                  ? `linear-gradient(135deg,${a.c},${a.c2})`
                  : (light ? 'rgba(0,0,0,0.06)' : 'rgba(255,255,255,0.06)'),
                display:'flex', alignItems:'center', justifyContent:'center',
                fontSize:18, color:'#fff',
                boxShadow: a.unlocked ? `0 4px 12px ${a.c}55` : 'none',
                border: a.unlocked ? 'none' : `1px dashed ${th.b3}`,
                position:'relative', zIndex:1,
              }}>{a.unlocked ? a.ic : '🔒'}</div>
              <div style={{fontSize:11, fontWeight:700, color:th.fg1, letterSpacing:'-0.01em', textAlign:'center', position:'relative', zIndex:1}}>{a.t}</div>
              <div style={{fontSize:9, color:th.fg3, fontWeight:500, textAlign:'center', lineHeight:1.3, position:'relative', zIndex:1}}>{a.sub}</div>
            </div>
          ))}
        </div>

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

      <TabBar th={th} active="stats" darkPill={false}/>
    </div>
  );
}
window.StatsV1 = StatsV1;

// =====================================================================
// WeeklyStreak — 7 flame icons, one per weekday. Active (lit) when the
// user reviewed photos that day. "Today" is highlighted with a ring.
// =====================================================================
function WeeklyStreak({ th, light, weekly, streak }) {
  // Monday-first, today = Thursday (index 3) for mock
  const todayIdx = 3;
  // Active if the day had any activity in mock data
  const days = weekly.map((w, i) => ({
    label: w.d.slice(0,1), // "M","T","W","T","F","S","S"
    active: w.n > 0,
    isToday: i === todayIdx,
    isFuture: i > todayIdx,
  }));
  const activeCount = days.filter(d => d.active && !d.isFuture).length;

  return (
    <div style={{
      marginTop:12, borderRadius:18, padding:'14px 14px 14px',
      background:th.bg1, border:`1px solid ${th.b2}`, boxShadow:th.cardShadow,
    }}>
      <div style={{fontSize:11, fontWeight:800, color:th.fg3, letterSpacing:'0.14em', textTransform:'uppercase'}}>
        This week
      </div>

      <div style={{display:'grid', gridTemplateColumns:'repeat(7, 1fr)', gap:6, marginTop:12}}>
        {days.map((d, i) => <FlameDay key={i} d={d} light={light} th={th}/>)}
      </div>
    </div>
  );
}

function FlameDay({ d, light, th }) {
  const { active, isToday, isFuture, label } = d;
  const dim = light ? 'rgba(10,10,12,0.12)' : 'rgba(255,255,255,0.16)';
  const dimBg = light ? 'rgba(0,0,0,0.03)' : 'rgba(255,255,255,0.04)';

  return (
    <div style={{display:'flex', flexDirection:'column', alignItems:'center', gap:6}}>
      <div style={{
        width:'100%', aspectRatio:'1',
        maxWidth:40,
        borderRadius:12,
        display:'flex', alignItems:'center', justifyContent:'center',
        position:'relative',
        background: active
          ? 'linear-gradient(135deg, rgba(255,138,61,0.18), rgba(240,91,232,0.18))'
          : dimBg,
        border: isToday
          ? '1.5px solid transparent'
          : active
            ? '1px solid rgba(255,138,61,0.35)'
            : `1px solid ${th.b2}`,
        backgroundImage: isToday
          ? 'linear-gradient(135deg, rgba(255,138,61,0.25), rgba(240,91,232,0.25)),' +
            'linear-gradient(135deg,#FFE066,#F05BE8,#5BE3FF)'
          : undefined,
        backgroundOrigin: isToday ? 'border-box' : undefined,
        backgroundClip: isToday ? 'padding-box, border-box' : undefined,
        boxShadow: active && !isFuture ? '0 4px 14px rgba(255,138,61,0.3)' : 'none',
      }}>
        <FlameSVG lit={active && !isFuture} dim={dim}/>
      </div>
      <div style={{
        fontSize:10, fontWeight: isToday ? 800 : 600,
        color: isToday ? th.fg1 : th.fg3,
        letterSpacing:'0.04em',
      }}>{label}</div>
    </div>
  );
}

function FlameSVG({ lit, dim }) {
  if (lit) {
    return (
      <span style={{fontSize:22, lineHeight:1, filter:'drop-shadow(0 2px 6px rgba(255,138,61,0.5))'}}>🔥</span>
    );
  }
  return (
    <span style={{fontSize:22, lineHeight:1, filter:'grayscale(1)', opacity:0.25}}>🔥</span>
  );
}
window.WeeklyStreak = WeeklyStreak;

// =====================================================================
// LibraryProgressGrid — "contribution graph" for your photo library.
// Each tile = 100 photos. Deleted = pink/orange holo, Kept = green/cyan,
// Unreviewed = dim. A giant headline number on top echoes the reference
// but applies our holo gradient language.
// =====================================================================
function LibraryProgressGrid({
  th, light, total, kept, deleted,
  totalTiles, deletedTiles, keptTiles, remainingTiles, perTile,
}) {
  // Tiles represent REVIEWED photos only (kept + deleted).
  // Pink first (deleted) starting top-left, then blue (kept).
  const reviewedTiles = deletedTiles + keptTiles;
  const cols = 11; // 11 × N rows
  const rows = Math.ceil(reviewedTiles / cols);
  const ordered = Array.from({length: reviewedTiles}, (_, i) =>
    i < deletedTiles ? 'deleted' : 'kept'
  );

  const styleFor = (kind) => {
    if (kind === 'deleted') {
      return {
        background:'linear-gradient(135deg,#F05BE8 0%,#FF6FB0 100%)',
        boxShadow:'0 0 10px rgba(240,91,232,0.55), 0 0 1px rgba(255,255,255,0.3) inset',
      };
    }
    return {
      // Kept = blue (was green/cyan → now cool blues per request)
      background:'linear-gradient(135deg,#5BE3FF 0%,#2F7BFF 100%)',
      boxShadow:'0 0 8px rgba(91,227,255,0.45), 0 0 1px rgba(255,255,255,0.3) inset',
    };
  };

  // Space saved estimate: ~2MB per photo average
  const mbSaved = Math.round(deleted * 2.4);
  const gbSaved = (mbSaved / 1024).toFixed(1);

  return (
    <div style={{
      marginTop:12, borderRadius:20, padding:18,
      background:th.bg1, border:`1px solid ${th.b2}`, boxShadow:th.cardShadow,
      position:'relative', overflow:'hidden',
    }}>
      {/* Header row */}
      <div style={{display:'flex', alignItems:'center', justifyContent:'space-between'}}>
        <div style={{fontSize:11, fontWeight:800, color:th.fg3, letterSpacing:'0.14em', textTransform:'uppercase'}}>
          Library progress
        </div>
        <div style={{fontSize:10, fontWeight:700, color:th.fg3, letterSpacing:'0.06em'}}>
          1 tile · {perTile} photos
        </div>
      </div>

      {/* Big metric */}
      <div style={{display:'flex', alignItems:'baseline', gap:8, marginTop:6}}>
        <div style={{
          fontFamily:'Syne, sans-serif',
          fontSize:40, fontWeight:800, lineHeight:1, letterSpacing:'-0.03em',
          background:'linear-gradient(135deg,#F05BE8 0%,#FF8A3D 50%,#FFE066 100%)',
          WebkitBackgroundClip:'text', backgroundClip:'text', color:'transparent',
        }}>{total.toLocaleString()}</div>
        <div style={{fontSize:14, color:th.fg2, fontWeight:600, letterSpacing:'-0.01em'}}>photos</div>
      </div>

      {/* The grid */}
      <div style={{
        marginTop:14,
        display:'grid',
        gridTemplateColumns:`repeat(${cols}, 1fr)`,
        gap:6,
      }}>
        {ordered.map((kind, i) => (
          <div key={i} style={{
            aspectRatio:'1 / 1',
            borderRadius:6,
            ...styleFor(kind),
          }}/>
        ))}
      </div>

      {/* Breakdown below grid — matches reference's stacked numbers */}
      <div style={{marginTop:16, display:'flex', flexDirection:'column', gap:6}}>
        <Row color="linear-gradient(135deg,#5BE3FF,#2F7BFF)" n={kept} label="photos kept" th={th}/>
        <Row color="linear-gradient(135deg,#F05BE8,#FF6FB0)" n={deleted} label="photos deleted" th={th}/>
      </div>
    </div>
  );
}

function Row({ color, n, label, th, isNote }) {
  return (
    <div style={{display:'flex', alignItems:'center', gap:10}}>
      <div style={{
        width:10, height:10, borderRadius:3, background: color, flexShrink:0,
        boxShadow: isNote ? 'none' : '0 0 6px rgba(255,255,255,0.15)',
      }}/>
      <div style={{
        fontSize:15, fontWeight:800, letterSpacing:'-0.01em', color:th.fg1,
        minWidth:72,
      }}>{typeof n === 'number' ? n.toLocaleString() : n}</div>
      <div style={{fontSize:13, color:th.fg3, fontWeight:500}}>{label}</div>
    </div>
  );
}
window.LibraryProgressGrid = LibraryProgressGrid;

// =====================================================================
// StatsHero — "Next achievement" card.
//   • Black base, static holo sheen, diagonal sparkle constellation.
//   • Radial tick dial on the right, now showing progress toward the
//     next achievement — inside the dial is the achievement glyph,
//     not a level number.
//   • Left column: "NEXT UP" eyebrow, achievement title, current/target
//     with a per-goal unit (e.g. 3.2 / 5.0 GB).
//   • Floating streak flame badge stays top-right.
//   • Bottom hairline mirrors the same progress fraction.
// =====================================================================
function StatsHero({ streak, light, achievement }) {
  const a = achievement;
  const frac = Math.min(1, a.progress / a.target);
  const remaining = Math.max(0, a.target - a.progress);

  const size = 112;
  const cx = size/2, cy = size/2;
  const r = size/2 - 9;
  const C = 2 * Math.PI * r;

  const fmt = (n) => Number.isInteger(n) ? n.toString() : n.toFixed(1);

  return (
    <div style={{
      position:'relative', marginTop:14, borderRadius:24, overflow:'hidden',
      padding:'22px 20px 20px',
      background:'linear-gradient(160deg, #0A0F1E 0%, #0C0820 45%, #1A0814 100%)',
      border:'1px solid rgba(255,255,255,0.12)',
      boxShadow:
        '0 20px 50px rgba(0,0,0,0.55),' +
        '0 1px 0 rgba(255,255,255,0.12) inset,' +
        '0 -40px 80px -20px rgba(0,0,0,0.5) inset',
    }}>
      <style>{`
        @keyframes heroBlob1 {
          0%   { transform: translate(-10%, -20%) scale(1.0); }
          25%  { transform: translate( 30%,  10%) scale(1.35); }
          50%  { transform: translate( 60%, -10%) scale(0.9); }
          75%  { transform: translate( 20%,  30%) scale(1.2); }
          100% { transform: translate(-10%, -20%) scale(1.0); }
        }
        @keyframes heroBlob2 {
          0%   { transform: translate( 80%,  70%) scale(1.1); }
          25%  { transform: translate( 40%,  30%) scale(0.85); }
          50%  { transform: translate( 10%,  60%) scale(1.3); }
          75%  { transform: translate( 60%,  20%) scale(1.0); }
          100% { transform: translate( 80%,  70%) scale(1.1); }
        }
        @keyframes heroBlob3 {
          0%   { transform: translate( 40%, 100%) scale(1.2); }
          33%  { transform: translate( 80%,  20%) scale(0.95); }
          66%  { transform: translate( -10%, 60%) scale(1.4); }
          100% { transform: translate( 40%, 100%) scale(1.2); }
        }
        @keyframes heroBlob4 {
          0%   { transform: translate( 20%,  50%) scale(0.9); }
          50%  { transform: translate( 70%, -20%) scale(1.3); }
          100% { transform: translate( 20%,  50%) scale(0.9); }
        }
        @keyframes heroTipPulse {
          0%,100% { transform: scale(1);   opacity: 0.9; }
          50%     { transform: scale(1.5); opacity: 1; }
        }
        @keyframes heroArcFlow {
          0%   { stroke-dashoffset: var(--heroDashStart); }
          100% { stroke-dashoffset: var(--heroDashEnd); }
        }
        @keyframes heroBottomPulse {
          0%,100% { opacity: 0.8; }
          50%     { opacity: 1; }
        }
        @keyframes heroChipBreathe {
          0%,100% { transform: translateY(0); }
          50%     { transform: translateY(-1px); }
        }
      `}</style>

      {/* LAVA LAMP BACKGROUND — fast morphing blobs behind everything */}
      <div style={{
        position:'absolute', inset:0, overflow:'hidden', pointerEvents:'none',
        filter:'blur(34px) saturate(1.2)',
      }}>
        <div style={{
          position:'absolute', top:0, left:0, width:'55%', height:'100%',
          background:'radial-gradient(circle at 50% 50%, #5BE3FF 0%, rgba(91,227,255,0) 60%)',
          animation:'heroBlob1 6s ease-in-out infinite',
        }}/>
        <div style={{
          position:'absolute', top:0, left:0, width:'55%', height:'100%',
          background:'radial-gradient(circle at 50% 50%, #F05BE8 0%, rgba(240,91,232,0) 60%)',
          animation:'heroBlob2 5.5s ease-in-out infinite',
        }}/>
        <div style={{
          position:'absolute', top:0, left:0, width:'50%', height:'100%',
          background:'radial-gradient(circle at 50% 50%, #FFB45A 0%, rgba(255,180,90,0) 60%)',
          animation:'heroBlob3 7s ease-in-out infinite',
        }}/>
        <div style={{
          position:'absolute', top:0, left:0, width:'50%', height:'100%',
          background:'radial-gradient(circle at 50% 50%, #6FF0B0 0%, rgba(111,240,176,0) 60%)',
          animation:'heroBlob4 5s ease-in-out infinite',
        }}/>
      </div>

      {/* Darken overlay for legibility on top of the lava */}
      <div style={{
        position:'absolute', inset:0, pointerEvents:'none',
        background:'linear-gradient(180deg, rgba(8,6,18,0.35) 0%, rgba(8,6,18,0.55) 100%)',
      }}/>

      {/* Content */}
      <div style={{position:'relative', zIndex:2, display:'flex', alignItems:'stretch', gap:14}}>
        {/* LEFT — redesigned Next Badge panel */}
        <div style={{
          flex:1, minWidth:0,
          position:'relative',
          borderRadius:18,
          padding:'12px 14px 12px',
          background:'rgba(10,8,22,0.55)',
          backdropFilter:'blur(14px)',
          WebkitBackdropFilter:'blur(14px)',
          border:'1px solid rgba(255,255,255,0.1)',
          boxShadow:'0 8px 24px rgba(0,0,0,0.35), 0 1px 0 rgba(255,255,255,0.08) inset',
          display:'flex', flexDirection:'column', justifyContent:'space-between',
        }}>
          {/* Header row: tiny trophy icon + label + % pill */}
          <div style={{display:'flex', alignItems:'center', justifyContent:'space-between', gap:8}}>
            <div style={{display:'flex', alignItems:'center', gap:6, minWidth:0}}>
              <svg width="12" height="12" viewBox="0 0 24 24" fill="none" style={{flexShrink:0}}>
                <path d="M6 4h12v3a6 6 0 0 1-12 0V4Z" stroke="#FFB45A" strokeWidth="1.8" strokeLinejoin="round"/>
                <path d="M4 5h2v2a2 2 0 0 1-2-2Zm14 0h2a2 2 0 0 1-2 2V5Z" stroke="#FFB45A" strokeWidth="1.8" strokeLinejoin="round"/>
                <path d="M9 14h6v3H9z" stroke="#FFB45A" strokeWidth="1.8" strokeLinejoin="round"/>
                <path d="M7 20h10" stroke="#FFB45A" strokeWidth="1.8" strokeLinecap="round"/>
              </svg>
              <div style={{
                fontSize:9, fontWeight:800, letterSpacing:'0.16em',
                color:'rgba(255,255,255,0.75)', textTransform:'uppercase',
                whiteSpace:'nowrap',
              }}>Next Badge</div>
            </div>
            {/* Percent tag */}
            <div style={{
              fontSize:10, fontWeight:800, letterSpacing:'-0.01em',
              padding:'2px 7px', borderRadius:6,
              background:'rgba(255,255,255,0.12)',
              color:'#FFFFFF',
              fontFamily:'Syne, sans-serif',
            }}>{Math.round(frac*100)}%</div>
          </div>

          {/* Title */}
          <div style={{
            fontSize:22, fontWeight:800, letterSpacing:'-0.03em',
            marginTop:8, lineHeight:1.05, color:'#FFFFFF',
          }}>{a.title}</div>

          {/* Inline progress bar */}
          <div style={{marginTop:10}}>
            <div style={{
              position:'relative', height:6, borderRadius:999,
              background:'rgba(255,255,255,0.08)', overflow:'hidden',
            }}>
              <div style={{
                position:'absolute', left:0, top:0, bottom:0, width:`${frac*100}%`,
                background:'linear-gradient(90deg,#5BE3FF 0%,#F05BE8 50%,#FFB45A 100%)',
                borderRadius:999,
                boxShadow:'0 0 8px rgba(240,91,232,0.6)',
              }}/>
            </div>
            <div style={{
              display:'flex', justifyContent:'space-between',
              marginTop:6, fontSize:10.5, fontWeight:600,
            }}>
              <span style={{color:'rgba(255,255,255,0.9)'}}>
                <span style={{fontFamily:'Syne, sans-serif', fontWeight:800}}>{fmt(a.progress)}</span>
                <span style={{color:'rgba(255,255,255,0.45)'}}> / {fmt(a.target)} {a.unit}</span>
              </span>
              <span style={{color:'rgba(255,255,255,0.6)'}}>
                {fmt(remaining)} {a.unit} left
              </span>
            </div>
          </div>
        </div>

        {/* Right — chrome medal */}
        <div style={{position:'relative', width:size, height:size, flexShrink:0}}>
          <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`} style={{display:'block', overflow:'visible'}}>
            <defs>
              {/* Holographic arc — cyan → magenta → amber → mint */}
              <linearGradient id="heroArc" x1="0" y1="0" x2="1" y2="1">
                <stop offset="0%" stopColor="#5BE3FF"/>
                <stop offset="35%" stopColor="#F05BE8"/>
                <stop offset="70%" stopColor="#FFB45A"/>
                <stop offset="100%" stopColor="#6FF0B0"/>
              </linearGradient>
              {/* Holographic medal disc */}
              <linearGradient id="medalFace" x1="0" y1="0" x2="1" y2="1">
                <stop offset="0%" stopColor="#E8FFFF"/>
                <stop offset="30%" stopColor="#5BE3FF"/>
                <stop offset="55%" stopColor="#F05BE8"/>
                <stop offset="80%" stopColor="#FFB45A"/>
                <stop offset="100%" stopColor="#6FF0B0"/>
              </linearGradient>
              <linearGradient id="medalBezel" x1="0.5" y1="0" x2="0.5" y2="1">
                <stop offset="0%" stopColor="#FFFFFF"/>
                <stop offset="50%" stopColor="#F05BE8"/>
                <stop offset="100%" stopColor="#0A0F1E"/>
              </linearGradient>
              <linearGradient id="medalHi" x1="0" y1="0" x2="1" y2="1">
                <stop offset="0%" stopColor="#FFFFFF" stopOpacity="0.85"/>
                <stop offset="40%" stopColor="#FFFFFF" stopOpacity="0.15"/>
                <stop offset="100%" stopColor="#FFFFFF" stopOpacity="0"/>
              </linearGradient>
              <filter id="heroGlow" x="-50%" y="-50%" width="200%" height="200%">
                <feGaussianBlur stdDeviation="2" result="b"/>
                <feMerge>
                  <feMergeNode in="b"/>
                  <feMergeNode in="SourceGraphic"/>
                </feMerge>
              </filter>
            </defs>

            {/* Track */}
            <circle cx={cx} cy={cy} r={r}
              fill="none" stroke="rgba(255,255,255,0.08)" strokeWidth="4"/>

            {/* Progress — violet gradient, animated flow from 0 to target offset */}
            <circle cx={cx} cy={cy} r={r}
              fill="none" stroke="url(#heroArc)"
              strokeWidth="4" strokeLinecap="round"
              strokeDasharray={C}
              transform={`rotate(-90 ${cx} ${cy})`}
              filter="url(#heroGlow)"
              style={{
                ['--heroDashStart']: C,
                ['--heroDashEnd']: C * (1 - frac),
                strokeDashoffset: C * (1 - frac),
                animation: 'heroArcFlow 1.4s cubic-bezier(0.2,0.8,0.2,1) forwards',
              }}
            />
            {/* Pulsing tip dot at end of arc */}
            {(() => {
              const ang = (frac * 2 * Math.PI) - Math.PI/2;
              const tx = cx + Math.cos(ang) * r;
              const ty = cy + Math.sin(ang) * r;
              return (
                <circle cx={tx} cy={ty} r="3"
                  fill="#FFFFFF"
                  style={{
                    filter:'drop-shadow(0 0 6px #F05BE8) drop-shadow(0 0 10px #5BE3FF)',
                    transformOrigin:`${tx}px ${ty}px`,
                    animation:'heroTipPulse 1.8s ease-in-out infinite',
                  }}
                />
              );
            })()}

            {/* Outer bezel ring — chrome */}
            <circle cx={cx} cy={cy} r={r - 8}
              fill="url(#medalBezel)"/>
            {/* Inner recess */}
            <circle cx={cx} cy={cy} r={r - 13}
              fill="url(#medalFace)"/>
            {/* Top-left highlight sweep (specular reflection) — animated drift */}
            <circle cx={cx} cy={cy} r={r - 13}
              fill="url(#medalHi)"
              style={{
                transformOrigin:`${cx}px ${cy}px`,
                animation:'heroSpecular 4.5s ease-in-out infinite',
              }}
            />
            {/* Hairline groove */}
            <circle cx={cx} cy={cy} r={r - 13}
              fill="none" stroke="rgba(0,0,0,0.35)" strokeWidth="0.5"/>
            {/* Tiny engraved tick marks around the bezel */}
            {Array.from({length: 12}).map((_, i) => {
              const ang = (i / 12) * Math.PI * 2;
              const x1 = cx + Math.cos(ang) * (r - 9.5);
              const y1 = cy + Math.sin(ang) * (r - 9.5);
              const x2 = cx + Math.cos(ang) * (r - 11.5);
              const y2 = cy + Math.sin(ang) * (r - 11.5);
              return (
                <line key={i} x1={x1} y1={y1} x2={x2} y2={y2}
                  stroke="rgba(10,15,30,0.6)" strokeWidth="0.6"/>
              );
            })}

            {/* Photo-stack monogram on holographic face */}
            <g transform={`translate(${cx}, ${cy})`}>
              <g opacity="0.9">
                <rect x="-11" y="-10" width="18" height="14" rx="2.5"
                  fill="none" stroke="rgba(10,15,30,0.7)" strokeWidth="1.5"/>
                <rect x="-7" y="-4" width="18" height="14" rx="2.5"
                  fill="rgba(255,255,255,0.9)"
                  stroke="rgba(255,255,255,0.9)" strokeWidth="0.8"/>
              </g>
            </g>
          </svg>

          {/* Streak pill — holographic, breathes subtly */}
          <div style={{
            position:'absolute', top:-4, right:-4,
            display:'flex', alignItems:'center', gap:3,
            padding:'3px 8px 3px 5px', borderRadius:999,
            background:'linear-gradient(135deg,#5BE3FF,#F05BE8,#FFB45A)',
            border:'1px solid rgba(255,255,255,0.35)',
            boxShadow:'0 2px 10px rgba(240,91,232,0.5), 0 1px 0 rgba(255,255,255,0.3) inset',
            animation:'heroChipBreathe 2.4s ease-in-out infinite',
          }}>
            <span style={{fontSize:10}}>🔥</span>
            <span style={{
              fontSize:10, fontWeight:800, letterSpacing:'-0.01em',
              color:'#0A0F1E',
            }}>{streak}</span>
          </div>
        </div>
      </div>

      {/* Bottom hairline — full rainbow flow */}
      <div style={{
        position:'absolute', left:0, right:0, bottom:0, height:2,
        background:'rgba(255,255,255,0.06)',
      }}>
        <div style={{
          position:'absolute', inset:0, width: `${frac * 100}%`,
          background:'linear-gradient(90deg,#6FF0B0,#5BE3FF,#F05BE8,#FFB45A)',
          boxShadow:'0 0 12px rgba(240,91,232,0.6)',
          animation:'heroBottomPulse 2.2s ease-in-out infinite',
        }}/>
      </div>
    </div>
  );
}
window.StatsHero = StatsHero;
