// Pau Fit — shared components
// Icons, tab bar, progress rings, pills

// ─────────────────────────────────────────────────────────────
// Icons (line style, hairline 1.6)
// ─────────────────────────────────────────────────────────────
const Icon = {
  // PACK NUEVO inspirado en Silbe: outline limpio inactivo, FILLED sólido cuando activo.
  // Sin fill parcial — siempre o totalmente fill o totalmente outline.
  // Cromo de accesos rápidos (DISEÑO.md §4: SVG para navegación, emoji solo en contenido)
  camera: (c = '#000', size = 22) => (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none">
      <path d="M4 8.5a2 2 0 0 1 2-2h1.5l1.2-1.8a1 1 0 0 1 .83-.45h4.94a1 1 0 0 1 .83.45L16.5 6.5H18a2 2 0 0 1 2 2V17a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V8.5z" stroke={c} strokeWidth="1.6" strokeLinejoin="round"/>
      <circle cx="12" cy="12.5" r="3.2" stroke={c} strokeWidth="1.6"/>
    </svg>
  ),
  calendarDays: (c = '#000', size = 22) => (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none">
      <rect x="4" y="5.5" width="16" height="15" rx="2.5" stroke={c} strokeWidth="1.6"/>
      <path d="M4 10h16M8.5 3.5v3.5M15.5 3.5v3.5" stroke={c} strokeWidth="1.6" strokeLinecap="round"/>
      <circle cx="8.5" cy="14" r="1" fill={c}/><circle cx="12" cy="14" r="1" fill={c}/><circle cx="15.5" cy="14" r="1" fill={c}/>
    </svg>
  ),
  trophy: (c = '#000', size = 22) => (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none">
      <path d="M8 4h8v6a4 4 0 0 1-8 0V4z" stroke={c} strokeWidth="1.6" strokeLinejoin="round"/>
      <path d="M8 5.5H5c0 2.5 1.2 4.2 3 4.7M16 5.5h3c0 2.5-1.2 4.2-3 4.7M12 14v3.5M8.5 20.5h7M12 17.5c-1.2 0-2 .8-2.4 1.6h4.8c-.4-.8-1.2-1.6-2.4-1.6z" stroke={c} strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/>
    </svg>
  ),
  home: (c = '#000', f = false) => f ? (
    <svg width="24" height="24" viewBox="0 0 24 24" fill={c}>
      <path d="M3.5 11.2L12 4l8.5 7.2V20a1 1 0 0 1-1 1h-4.5v-5.5a3 3 0 0 0-6 0V21H4.5a1 1 0 0 1-1-1v-8.8z"/>
    </svg>
  ) : (
    <svg width="24" height="24" viewBox="0 0 24 24" fill="none">
      <path d="M3.5 11.2L12 4l8.5 7.2V20a1 1 0 0 1-1 1h-4.5v-5.5a3 3 0 0 0-6 0V21H4.5a1 1 0 0 1-1-1v-8.8z"
        stroke={c} strokeWidth="1.8" strokeLinejoin="round" fill="none"/>
    </svg>
  ),

  // RUTINAS — mancuerna (dumbbell) bonita
  target: (c = '#000', f = false) => f ? (
    <svg width="24" height="24" viewBox="0 0 24 24" fill={c}>
      <rect x="2" y="9" width="2.5" height="6" rx="1"/>
      <rect x="4.5" y="7" width="2.5" height="10" rx="1.2"/>
      <rect x="7" y="11" width="10" height="2" rx="0.5"/>
      <rect x="17" y="7" width="2.5" height="10" rx="1.2"/>
      <rect x="19.5" y="9" width="2.5" height="6" rx="1"/>
    </svg>
  ) : (
    <svg width="24" height="24" viewBox="0 0 24 24" fill="none">
      <rect x="2" y="9" width="2.5" height="6" rx="1" stroke={c} strokeWidth="1.6"/>
      <rect x="4.5" y="7" width="2.5" height="10" rx="1.2" stroke={c} strokeWidth="1.6"/>
      <path d="M7 12h10" stroke={c} strokeWidth="2.2" strokeLinecap="round"/>
      <rect x="17" y="7" width="2.5" height="10" rx="1.2" stroke={c} strokeWidth="1.6"/>
      <rect x="19.5" y="9" width="2.5" height="6" rx="1" stroke={c} strokeWidth="1.6"/>
    </svg>
  ),

  // COMIDAS — manzana mordida (más clara que el tenedor)
  fork: (c = '#000', f = false) => f ? (
    <svg width="24" height="24" viewBox="0 0 24 24" fill={c}>
      <path d="M12 7.5c-.8-1.2-2.2-2-3.7-2-2.5 0-4.3 2-4.3 4.7 0 4.3 4.5 9 8 9s8-4.7 8-9c0-2.7-1.8-4.7-4.3-4.7-1.5 0-2.9.8-3.7 2z"/>
      <path d="M12 7c.3-1.5 1.3-3 3-3.5" stroke={c} strokeWidth="1.5" strokeLinecap="round" fill="none"/>
    </svg>
  ) : (
    <svg width="24" height="24" viewBox="0 0 24 24" fill="none">
      <path d="M12 7.5c-.8-1.2-2.2-2-3.7-2-2.5 0-4.3 2-4.3 4.7 0 4.3 4.5 9 8 9s8-4.7 8-9c0-2.7-1.8-4.7-4.3-4.7-1.5 0-2.9.8-3.7 2z"
        stroke={c} strokeWidth="1.8" strokeLinejoin="round" fill="none"/>
      <path d="M12 7c.3-1.5 1.3-3 3-3.5" stroke={c} strokeWidth="1.5" strokeLinecap="round" fill="none"/>
    </svg>
  ),

  // COMUNIDAD — dos figuras redondeadas
  people: (c = '#000', f = false) => f ? (
    <svg width="24" height="24" viewBox="0 0 24 24" fill={c}>
      <circle cx="9" cy="8" r="3.5"/>
      <circle cx="17" cy="9.5" r="2.8"/>
      <path d="M3.5 19c0-3 2.5-5.5 5.5-5.5s5.5 2.5 5.5 5.5v1.5a.5.5 0 0 1-.5.5h-10a.5.5 0 0 1-.5-.5V19z"/>
      <path d="M15 14c1.5 0 2.7.4 3.5 1 .8.6 1 1.5 1 2.5v1.5a.5.5 0 0 1-.5.5h-2.5"/>
    </svg>
  ) : (
    <svg width="24" height="24" viewBox="0 0 24 24" fill="none">
      <circle cx="9" cy="8" r="3.5" stroke={c} strokeWidth="1.8"/>
      <circle cx="17" cy="9.5" r="2.8" stroke={c} strokeWidth="1.8"/>
      <path d="M3.5 19c0-3 2.5-5.5 5.5-5.5s5.5 2.5 5.5 5.5" stroke={c} strokeWidth="1.8" strokeLinecap="round"/>
      <path d="M15 13.5c2.7 0 4.5 2 4.5 4.5" stroke={c} strokeWidth="1.8" strokeLinecap="round"/>
    </svg>
  ),

  user: (c = '#000', f = false) =>
  <svg width="24" height="24" viewBox="0 0 24 24" fill="none">
      <circle cx="12" cy="8" r="4" stroke={c} strokeWidth="1.6" fill={f ? c : 'none'} />
      <path d="M4 21c0-4 3.5-7 8-7s8 3 8 7" stroke={c} strokeWidth="1.6" strokeLinecap="round" fill="none" />
    </svg>,

  play: (c = '#fff') =>
  <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
      <path d="M3 2l9 5-9 5V2z" fill={c} />
    </svg>,

  back: (c = '#000') =>
  <svg width="22" height="22" viewBox="0 0 22 22" fill="none">
      <path d="M14 4l-7 7 7 7" stroke={c} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
    </svg>,

  close: (c = '#000') =>
  <svg width="22" height="22" viewBox="0 0 22 22" fill="none">
      <path d="M5 5l12 12M17 5L5 17" stroke={c} strokeWidth="2" strokeLinecap="round" />
    </svg>,

  heart: (c = '#000', f = false) =>
  <svg width="22" height="22" viewBox="0 0 22 22" fill="none">
      <path d="M11 19s-7-4.5-7-10.5A4 4 0 0 1 11 6a4 4 0 0 1 7 2.5C18 14.5 11 19 11 19z"
    stroke={c} strokeWidth="1.6" fill={f ? c : 'none'} strokeLinejoin="round" />
    </svg>,

  flame: (size = 22, c = '#D14C7A') =>
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none">
      <path d="M12 3c.5 1.5-.5 2.6-1 3.4-1 1.6-2 3-2 5.1 0 3.3 2.2 5.5 5 5.5 3.3 0 5-2.5 5-5.5 0-3-1.7-5.2-3.5-7-1-1-2-1.8-3.5-1.5z"
    fill={c} opacity="0.95" />
      <path d="M10 14.5c0-1.5 1-2.5 2-3.5.5 1.5 2 2 2 3.5 0 1.5-1 2.5-2 2.5s-2-1-2-2.5z"
    fill="#fff" opacity="0.6" />
    </svg>,

  check: (c = '#fff', size = 14) =>
  <svg width={size} height={size} viewBox="0 0 14 14" fill="none">
      <path d="M3 7.5l2.5 2.5L11 4.5" stroke={c} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
    </svg>,

  lock: (c = '#fff', size = 12) =>
  <svg width={size} height={size} viewBox="0 0 12 12" fill="none">
      <rect x="2" y="5" width="8" height="6" rx="1.2" fill={c} />
      <path d="M4 5V3.5a2 2 0 0 1 4 0V5" stroke={c} strokeWidth="1.4" fill="none" />
    </svg>,

  diamond: (size = 26, c = '#C9956B') =>
  <svg width={size} height={size} viewBox="0 0 26 26" fill="none">
      <path d="M5 9l4-5h8l4 5-8 13L5 9z" fill={c} />
      <path d="M9 4l4 5 4-5M5 9h16M9 9l4 13M17 9l-4 13" stroke="#fff" strokeWidth="0.8" strokeLinejoin="round" opacity="0.5" />
    </svg>,

  search: (c = '#000') =>
  <svg width="20" height="20" viewBox="0 0 20 20" fill="none">
      <circle cx="9" cy="9" r="6" stroke={c} strokeWidth="1.6" />
      <path d="M14 14l4 4" stroke={c} strokeWidth="1.6" strokeLinecap="round" />
    </svg>,

  sort: (c = '#000') =>
  <svg width="20" height="20" viewBox="0 0 20 20" fill="none">
      <path d="M4 6h12M6 10h8M8 14h4" stroke={c} strokeWidth="1.6" strokeLinecap="round" />
    </svg>,

  chevR: (c = '#000', size = 10) =>
  <svg width={size} height={size * 1.6} viewBox="0 0 10 16" fill="none">
      <path d="M2 2l6 6-6 6" stroke={c} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" fill="none" />
    </svg>,

  bell: (c = '#000') =>
  <svg width="22" height="22" viewBox="0 0 22 22" fill="none">
      <path d="M5 16h12l-1.5-2V10a4.5 4.5 0 0 0-9 0v4L5 16zM9 19a2 2 0 0 0 4 0" stroke={c} strokeWidth="1.6" strokeLinejoin="round" fill="none" />
    </svg>,

  share: (c = '#000') =>
  <svg width="22" height="22" viewBox="0 0 22 22" fill="none">
      <path d="M11 14V3M7 7l4-4 4 4M5 12v6a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2v-6" stroke={c} strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" fill="none" />
    </svg>,

  clock: ({ c = '#000', size = 14 } = {}) =>
  <svg width={size} height={size} viewBox="0 0 16 16" fill="none">
      <circle cx="8" cy="8" r="6.5" stroke={c} strokeWidth="1.6"/>
      <path d="M8 4.5V8l2.5 1.5" stroke={c} strokeWidth="1.6" strokeLinecap="round"/>
    </svg>,

  playFilled: ({ c = '#fff', size = 12 } = {}) =>
  <svg width={size} height={size} viewBox="0 0 12 12" fill="none">
      <path d="M3 1.5l7 4.5-7 4.5V1.5z" fill={c}/>
    </svg>,

  fire: (c = '#FF2E78', size = 14) =>
  <svg width={size} height={size} viewBox="0 0 16 16" fill="none">
      <path d="M8 2c.3 1-.3 1.7-.7 2.3C6.6 5.4 6 6.3 6 7.7c0 2.2 1.4 3.7 3.3 3.7s3-1.6 3-3.7c0-2-1-3.5-2.3-4.7C9 2.3 8.7 2 8 2z" fill={c}/>
    </svg>

};

// ─────────────────────────────────────────────────────────────
// Progress Ring (conic gradient)
// ─────────────────────────────────────────────────────────────
function ProgressRing({ value = 0.4, size = 64, stroke = 6, color = '#D4847A', track = 'rgba(0,0,0,0.06)', children }) {
  const r = (size - stroke) / 2;
  const c = 2 * Math.PI * r;
  const off = c * (1 - value);
  return (
    <div style={{ width: size, height: size, position: 'relative', display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}>
      <svg width={size} height={size} style={{ position: 'absolute', inset: 0, transform: 'rotate(-90deg)' }}>
        <circle cx={size / 2} cy={size / 2} r={r} fill="none" stroke={track} strokeWidth={stroke} />
        <circle cx={size / 2} cy={size / 2} r={r} fill="none" stroke={color} strokeWidth={stroke}
        strokeDasharray={c} strokeDashoffset={off} strokeLinecap="round"
        style={{ transition: 'stroke-dashoffset 600ms cubic-bezier(.2,.8,.2,1)' }} />
      </svg>
      <div style={{ position: 'relative', zIndex: 1 }}>{children}</div>
    </div>);

}

// ─────────────────────────────────────────────────────────────
// Pill (filter chip)
// ─────────────────────────────────────────────────────────────
function Pill({ active, onClick, children, dark = false, color = '#D4847A' }) {
  // Anna-style: pill compacta bold, uppercase, mucha personalidad
  return (
    <button onClick={onClick} style={{
      border: 'none', cursor: 'pointer',
      padding: '9px 16px', borderRadius: 999,
      fontFamily: 'Poppins, system-ui', fontSize: 11, fontWeight: 800, letterSpacing: 0.3,
      background: active ? color : dark ? 'rgba(255,255,255,0.06)' : 'rgba(0,0,0,0.04)',
      color: active ? '#fff' : dark ? 'rgba(255,255,255,0.6)' : 'rgba(45,42,46,0.7)',
      whiteSpace: 'nowrap',
      transition: 'all 200ms ease'
    }}>{children}</button>);

}

// ─────────────────────────────────────────────────────────────
// Tab Bar (5 tabs, blur glass)
// ─────────────────────────────────────────────────────────────
function TabBar({ active, onChange, dark = false, accent = '#D4847A' }) {
  const tabs = [
  { id: 'home', label: 'Inicio', icon: Icon.home },
  { id: 'retos', label: 'Rutinas', icon: Icon.target },
  { id: 'recetas', label: 'Comidas', icon: Icon.fork },
  { id: 'comunidad', label: 'Comunidad', icon: Icon.people }];

  const inactiveColor = dark ? 'rgba(255,255,255,0.55)' : '#A89C94';
  // PRO TabBar (Sweat/Silbe style): glass blur + sólido contraste
  return (
    <div style={{
      position: 'absolute', bottom: 0, left: 0, right: 0, zIndex: 40,
      paddingBottom: 'calc(env(safe-area-inset-bottom, 0px) + 18px)', paddingTop: 10,
      background: dark ? 'rgba(26,20,24,0.78)' : 'rgba(255,255,255,0.78)',
      backdropFilter: 'saturate(180%) blur(20px)',
      WebkitBackdropFilter: 'saturate(180%) blur(20px)',
      borderTop: dark ? '0.5px solid rgba(255,255,255,0.08)' : '0.5px solid rgba(45,42,46,0.08)',
    }}>
      <div style={{ display: 'flex', justifyContent: 'space-around', padding: '0 8px', alignItems: 'center' }}>
        {tabs.map((t) => {
          const isActive = active === t.id;
          // Pill activo: background ACCENT con icon en blanco que sí contrasta sobre rosa fuerte
          // Si el accent es claro pueden contrastar mejor con T.text — pero default Pau peach es contrast OK
          // iOS-style: sin píldora — el activo se distingue por tinte + relleno
          const iconColor = isActive ? accent : inactiveColor;
          return (
            <button key={t.id} onClick={() => onChange(t.id)} style={{
              border: 'none', background: 'transparent', cursor: 'pointer',
              display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4,
              padding: 0, flex: 1,
              WebkitTapHighlightColor: 'transparent',
            }}>
              <div style={{
                padding: '6px 12px',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                transition: 'all 240ms cubic-bezier(.2,.8,.2,1)',
              }}>
                {t.icon(iconColor, isActive)}
              </div>
              <span style={{
                fontFamily: 'Poppins, system-ui', fontSize: 9,
                fontWeight: isActive ? 700 : 500,
                color: isActive ? accent : inactiveColor,
                letterSpacing: 0.3,
              }}>{t.label}</span>
            </button>);

        })}
      </div>
    </div>);

}

// ─────────────────────────────────────────────────────────────
// Badge for reto cards (GRATIS / PRO)
// ─────────────────────────────────────────────────────────────
function RetoBadge({ tag, dark = false, isPremium = false }) {
  if (tag === 'GRATIS') {
    return (
      <span style={{
        fontFamily: 'Poppins, system-ui', fontSize: 9, fontWeight: 700,
        letterSpacing: 1.2, color: '#5C7A56',
        padding: '4px 8px', borderRadius: 6,
        background: 'rgba(168,197,160,0.28)'
      }}>GRATIS</span>);

  }
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 4,
      fontFamily: 'Poppins, system-ui', fontSize: 9, fontWeight: 700,
      letterSpacing: 1.2, color: '#F5E6C8',
      padding: '4px 8px', borderRadius: 6,
      background: '#2D2A26'
    }}>
      {!isPremium && <span style={{ fontSize: 7 }}>{Icon.lock('#F5E6C8', 8)}</span>}
      PRO
    </span>);

}

// ─────────────────────────────────────────────────────────────
// Streak Flame — wobble animation
// ─────────────────────────────────────────────────────────────
function StreakFlame({ count, color = '#D14C7A' }) {
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 6
    }}>
      <span style={{
        width: 28, height: 28, borderRadius: 999,
        background: `linear-gradient(135deg, ${color}25, ${color}10)`,
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
        fontSize: 14
      }}>🔥</span>
      <span style={{
        fontFamily: 'Poppins, system-ui', fontSize: 18, fontWeight: 700, color
      }}>{count}</span>
    </div>);

}

// ─────────────────────────────────────────────────────────────
// Confetti — emoji burst for completion
// ─────────────────────────────────────────────────────────────
function Confetti({ show }) {
  if (!show) return null;
  // Burst real: 24 items con posiciones y rotaciones random
  // Estilo Sweat/Growingannanas — emoji + papelillos pequeños
  const emojis = ['✨', '💗', '🎉', '⭐️', '🌸', '💪🏻', '💖', '🌟', '🔥', '💕'];
  const dots = ['#D9477E', '#F4A8BD', '#FFD166', '#7CD2A0', '#9B7BE5'];
  const items = Array.from({ length: 24 }, (_, i) => {
    const isEmoji = i % 3 === 0;
    const x = 5 + Math.random() * 90;  // 5%..95%
    const yStart = -5 + Math.random() * 35; // -5%..30%
    const rot = (Math.random() - 0.5) * 720;
    const scale = 0.7 + Math.random() * 0.7;
    const dur = 1400 + Math.random() * 800;
    const delay = Math.random() * 200;
    return { isEmoji, x, yStart, rot, scale, dur, delay, char: emojis[i % emojis.length], color: dots[i % dots.length], size: 18 + Math.random() * 14 };
  });
  return (
    <div style={{
      position: 'absolute', inset: 0, pointerEvents: 'none', zIndex: 100, overflow: 'hidden'
    }}>
      {items.map((it, i) => (
        it.isEmoji ? (
          <span key={i} style={{
            position: 'absolute', top: `${it.yStart}%`, left: `${it.x}%`,
            fontSize: it.size,
            animation: `confetti-fall ${it.dur}ms cubic-bezier(.2,.5,.4,1) forwards`,
            animationDelay: `${it.delay}ms`,
            transform: `scale(${it.scale}) rotate(${it.rot}deg)`,
          }}>{it.char}</span>
        ) : (
          <span key={i} style={{
            position: 'absolute', top: `${it.yStart}%`, left: `${it.x}%`,
            width: it.size * 0.4, height: it.size * 0.6,
            background: it.color, borderRadius: 2,
            animation: `confetti-fall ${it.dur}ms cubic-bezier(.2,.5,.4,1) forwards`,
            animationDelay: `${it.delay}ms`,
            transform: `scale(${it.scale}) rotate(${it.rot}deg)`,
          }}/>
        )
      ))}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// PauTopBar — header global que aparece en todas las tab screens
// Izquierda: pill racha (toca → logros)
// Centro: logo Pau Fit
// Derecha: avatar circular con iniciales (toca → perfil)
// ─────────────────────────────────────────────────────────────
// variant: 'home' → ⭐ puntos izq · LOGO centro · avatar der
//          'default' → LOGO izq · botones der (rutinas/comidas/comunidad)
function PauTopBar({ T, nav, variant = 'default', showSearch, showBookmark, onSearch, onBookmark }) {
  // Bump para re-render cuando cache cambia (avatar nuevo, etc)
  const [, setCacheBump] = React.useState(0);
  React.useEffect(() => {
    const handler = () => setCacheBump(x => x + 1);
    window.addEventListener('pau:cache-updated', handler);
    return () => window.removeEventListener('pau:cache-updated', handler);
  }, []);

  const cache = (typeof window !== 'undefined' && window.__pauCache) || {};
  const profile = cache.profile || {};
  const fullName = profile.full_name || profile.username || '';
  // Solo usamos iniciales si tiene nombre/username REAL.
  // Si solo hay email (ej. "p" de paulasmareyes), mostramos el logo Pau Fit.
  const initials = fullName
    ? fullName.split(' ').map(s => s[0]).slice(0,2).join('').toUpperCase()
    : null;
  const avatarUrl = profile.avatar_url || null;
  const points = profile.points || 0;

  // STICKY + glass al scrollear
  const [scrolled, setScrolled] = React.useState(false);
  const ref = React.useRef(null);
  React.useEffect(() => {
    if (!ref.current) return;
    let parent = ref.current.parentElement;
    while (parent && !parent.classList?.contains('scroll-area')) parent = parent.parentElement;
    if (!parent) return;
    const onScroll = () => setScrolled(parent.scrollTop > 8);
    parent.addEventListener('scroll', onScroll, { passive: true });
    onScroll();
    return () => parent.removeEventListener('scroll', onScroll);
  }, []);

  const isDark = T.dark;
  const bgScrolled = isDark
    ? 'rgba(27,22,18,0.82)'
    : `${T.bg}cc`;

  // Botón redondeado reusable arriba derecha
  const RoundBtn = ({ icon, onClick }) => (
    <button onClick={onClick} style={{
      width: 38, height: 38, borderRadius: 999, border: 'none',
      background: T.card, color: T.accent, cursor: 'pointer',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      boxShadow: '0 2px 8px rgba(0,0,0,0.08)',
    }}>{icon}</button>
  );
  const avatarBtn = (
    <button onClick={() => nav.go('perfil')} style={{
      width: 42, height: 42, borderRadius: 999, border: 'none',
      background: T.card, color: T.text, cursor: 'pointer',
      fontSize: 14, fontWeight: 700, letterSpacing: -0.2,
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      boxShadow: '0 2px 8px rgba(0,0,0,0.08)',
      padding: 0, overflow: 'hidden',
    }}>
      {avatarUrl
        ? <img src={avatarUrl} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }}/>
        : initials
          ? initials
          : <img src="/branding/logo.png" alt="Pau Fit" style={{ width: 26, height: 26, objectFit: 'contain' }}/>
      }
    </button>
  );

  return (
    <div ref={ref} style={{
      position: 'sticky', top: 0, zIndex: 50,
      padding: '14px 20px 10px',
      background: scrolled ? bgScrolled : 'transparent',
      backdropFilter: scrolled ? 'blur(20px) saturate(180%)' : 'none',
      WebkitBackdropFilter: scrolled ? 'blur(20px) saturate(180%)' : 'none',
      transition: 'background 220ms ease',
      borderBottom: scrolled ? `0.5px solid ${T.dark ? 'rgba(255,255,255,0.06)' : 'rgba(0,0,0,0.05)'}` : 'none',
    }}>
      {variant === 'home' ? (
        // HOME: ⭐ puntos izq · LOGO centro (perfectamente centrado) · avatar der
        <div style={{ display: 'grid', gridTemplateColumns: '1fr auto 1fr', alignItems: 'center', gap: 8 }}>
          <div style={{ justifySelf: 'start' }}>
            <button onClick={() => nav.go('logros')} style={{
              border: 'none', cursor: 'pointer',
              display: 'flex', alignItems: 'center', gap: 6,
              padding: '8px 14px', borderRadius: 999,
              background: T.card, color: T.text,
              boxShadow: '0 2px 8px rgba(0,0,0,0.08)',
            }}>
              <span style={{ fontSize: 14 }}>⭐</span>
              <span style={{ fontSize: 13, fontWeight: 800, letterSpacing: -0.2 }}>{points}</span>
            </button>
          </div>
          <img src="/branding/logo.png" alt="Pau Fit" style={{
            height: 44, width: 'auto', objectFit: 'contain',
            justifySelf: 'center',
          }}/>
          <div style={{ justifySelf: 'end' }}>{avatarBtn}</div>
        </div>
      ) : (
        // DEFAULT: LOGO izq · botones der
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8 }}>
          <img src="/branding/logo.png" alt="Pau Fit" style={{
            height: 44, width: 'auto', objectFit: 'contain',
            flexShrink: 0,
          }}/>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
            {showBookmark && (
              <RoundBtn onClick={onBookmark} icon={
                <svg width="16" height="18" viewBox="0 0 16 18" fill="none">
                  <path d="M2 2v14l6-4 6 4V2H2z" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/>
                </svg>
              }/>
            )}
            {showSearch && (
              <RoundBtn onClick={onSearch} icon={
                <svg width="18" height="18" viewBox="0 0 20 20" fill="none">
                  <circle cx="9" cy="9" r="6" stroke="currentColor" strokeWidth="2"/>
                  <path d="M14 14l4 4" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/>
                </svg>
              }/>
            )}
            {avatarBtn}
          </div>
        </div>
      )}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// EmptyState — patrón consistente Sweat/BODi para pantallas vacías
// emoji 44–48px + título + descripción + CTA opcional
// ─────────────────────────────────────────────────────────────
function EmptyState({ emoji = '✨', title, description, ctaLabel, onCta, T }) {
  return (
    <div style={{
      padding: '48px 22px 0', textAlign: 'center',
      animation: 'fade-in 320ms ease',
    }}>
      <div style={{ fontSize: 48, marginBottom: 14, opacity: 0.9 }}>{emoji}</div>
      <div style={{
        fontFamily: 'Poppins', fontSize: 16, fontWeight: 700, color: T.text,
        letterSpacing: -0.3, lineHeight: 1.3,
      }}>{title}</div>
      {description && (
        <div style={{
          fontFamily: 'Poppins', fontSize: 13, color: T.muted,
          marginTop: 8, lineHeight: 1.5, maxWidth: 280, margin: '8px auto 0',
        }}>{description}</div>
      )}
      {ctaLabel && onCta && (
        <button onClick={onCta} style={{
          marginTop: 22, padding: '14px 28px',
          border: 'none', borderRadius: 999, cursor: 'pointer',
          background: T.accent, color: '#fff',
          fontFamily: 'Poppins', fontSize: 13, fontWeight: 700,
          letterSpacing: 0.2,
          boxShadow: `0 6px 18px ${T.accent}30`,
        }}>{ctaLabel}</button>
      )}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Skeleton loader — estilo Sweat/BODi
// Reemplaza spinners feos por placeholder rectangular con shimmer
// ─────────────────────────────────────────────────────────────
function Skeleton({ width = '100%', height = 16, radius = 8, style = {} }) {
  return <div className="pf-skeleton" style={{
    width, height, borderRadius: radius,
    ...style,
  }}/>;
}

// PauLoader — loader oficial con logo Pau Fit (pulse + glow accent)
function PauLoader({ T, size = 96, label }) {
  return (
    <div style={{
      display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
      gap: 16, padding: 30,
    }}>
      <div style={{ position: 'relative', width: size, height: size }}>
        <div style={{
          position: 'absolute', inset: 0, borderRadius: '50%',
          background: `radial-gradient(circle, ${T?.accent || '#D9477E'}40, transparent 70%)`,
          animation: 'pulse 1.6s ease-in-out infinite',
        }}/>
        <img src="/branding/logo.png" alt="Pau Fit" style={{
          position: 'relative', width: '100%', height: '100%', objectFit: 'contain',
          animation: 'pulse 1.6s ease-in-out infinite',
        }}/>
      </div>
      {label && (
        <div style={{ fontSize: 12, fontWeight: 600, color: T?.muted || '#999' }}>{label}</div>
      )}
    </div>
  );
}

// SkeletonList — render N skeletons en columna (para listas tipo Historial, Ranking)
function SkeletonList({ count = 3, height = 64, gap = 10, T }) {
  return (
    <div style={{ padding: '14px 20px 0', display: 'flex', flexDirection: 'column', gap }}>
      {Array.from({ length: count }).map((_, i) => (
        <div key={i} style={{
          padding: '14px 16px', background: T?.card || '#fff',
          borderRadius: 16, border: T?.border || '0.5px solid rgba(0,0,0,0.05)',
          display: 'flex', alignItems: 'center', gap: 12,
        }}>
          <div className="pf-skeleton" style={{ width: 44, height: 44, borderRadius: 12, flexShrink: 0 }}/>
          <div style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: 6 }}>
            <div className="pf-skeleton" style={{ width: '40%', height: 10, borderRadius: 5 }}/>
            <div className="pf-skeleton" style={{ width: '75%', height: 14, borderRadius: 6 }}/>
          </div>
        </div>
      ))}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// WelcomeTutorialModal — primer login, 3 slides estilo onboarding
// ─────────────────────────────────────────────────────────────
function WelcomeTutorialModal({ T, onDone }) {
  const [step, setStep] = React.useState(0);
  const slides = [
    { emoji: '💗', title: 'Bienvenida a Pau Fit', desc: 'Tu app fitness con retos guiados, recetas y comunidad' },
    { emoji: '🎯', title: 'Elige tu reto', desc: 'Programas de 7 a 30 días para tu objetivo. Solo tienes que seguir' },
    { emoji: '⭐', title: 'Gana puntos · sube en el ranking', desc: 'Completa días, sube fotos, anota comidas. Cada acción suma' },
  ];
  const isLast = step === slides.length - 1;
  return (
    <div style={{
      position: 'fixed', inset: 0, zIndex: 9999,
      background: 'rgba(0,0,0,0.6)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      padding: 20,
      animation: 'fade-in 240ms ease',
    }}>
      <div style={{
        width: '100%', maxWidth: 340, background: T.bg, borderRadius: 28,
        padding: '36px 24px 24px', position: 'relative',
        animation: 'pop-in 420ms cubic-bezier(.34,1.56,.64,1)',
        boxShadow: '0 24px 70px rgba(0,0,0,0.4)',
      }}>
        <div style={{ fontSize: 72, textAlign: 'center', marginBottom: 16 }}>{slides[step].emoji}</div>
        <div className="pf-display" style={{
          fontSize: 24, fontWeight: 700, color: T.text,
          letterSpacing: -0.4, textAlign: 'center', lineHeight: 1.2,
        }}>{slides[step].title}</div>
        <div style={{
          fontSize: 13, color: T.muted, lineHeight: 1.5, textAlign: 'center',
          marginTop: 10,
        }}>{slides[step].desc}</div>
        {/* Dots */}
        <div style={{ display: 'flex', gap: 6, justifyContent: 'center', marginTop: 24 }}>
          {slides.map((_, i) => (
            <div key={i} style={{
              width: i === step ? 20 : 6, height: 6, borderRadius: 999,
              background: i === step ? T.accent : T.subtle,
              transition: 'all 200ms ease',
            }}/>
          ))}
        </div>
        <button onClick={() => isLast ? onDone() : setStep(step + 1)} style={{
          marginTop: 22, width: '100%', padding: '16px',
          border: 'none', borderRadius: 16, cursor: 'pointer',
          background: T.accent, color: '#fff',
          fontSize: 14, fontWeight: 700, letterSpacing: 0.2,
          boxShadow: `0 6px 18px ${T.accent}40`,
          fontFamily: 'inherit',
        }}>{isLast ? '¡Empezar! 💗' : 'Siguiente'}</button>
        <button onClick={onDone} style={{
          marginTop: 8, width: '100%', padding: '10px',
          border: 'none', background: 'transparent', cursor: 'pointer',
          fontSize: 12, fontWeight: 600, color: T.muted,
          fontFamily: 'inherit',
        }}>Saltar</button>
      </div>
    </div>
  );
}

Object.assign(window, { Icon, ProgressRing, Pill, TabBar, RetoBadge, StreakFlame, Confetti, InsigniaCard, EmptyState, Skeleton, SkeletonList, PauTopBar, WelcomeTutorialModal, PauLoader });

// ─────────────────────────────────────────────────────────────
// Insignia — badge ganada al completar un reto
// Diseño: medalla circular con ring gradient, emoji centro,
// multiplicador (x2, x3...) en esquina si times > 1
// ─────────────────────────────────────────────────────────────
function InsigniaCard({ b, T, large = false }) {
  const size = large ? 120 : 88;
  return (
    <div style={{
      flexShrink: 0, width: size + 24, scrollSnapAlign: 'start',
      display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8,
      padding: '10px 4px'
    }}>
      <div style={{ position: 'relative', width: size, height: size }}>
        {/* outer ring (gradient) */}
        <div style={{
          position: 'absolute', inset: 0, borderRadius: '50%',
          background: `conic-gradient(from -90deg, ${b.color}, ${b.bg}, ${b.color}, ${b.bg}, ${b.color})`,
          padding: 4, boxShadow: `0 8px 24px ${b.color}40`
        }}>
          <div style={{
            width: '100%', height: '100%', borderRadius: '50%',
            background: `radial-gradient(circle at 50% 35%, #fff 0%, ${b.bg} 55%, ${b.color}40 100%)`,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            position: 'relative'
          }}>
            {/* Inner emoji */}
            <span style={{ fontSize: size * 0.5, filter: 'drop-shadow(0 2px 6px rgba(45,42,38,0.18))' }}>{b.emoji}</span>
            {/* Sparkles */}
            <span style={{ position: 'absolute', top: '15%', right: '18%', fontSize: 10, opacity: 0.7 }}>✨</span>
            <span style={{ position: 'absolute', bottom: '20%', left: '18%', fontSize: 8, opacity: 0.6 }}>✨</span>
          </div>
        </div>
        {/* Multiplier */}
        {b.times > 1 &&
        <div style={{
          position: 'absolute', bottom: -2, right: -2,
          minWidth: 28, height: 28, borderRadius: 999, padding: '0 8px',
          background: '#2D2A26', color: '#F5E6C8',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontFamily: 'Poppins', fontSize: 11, fontWeight: 800, letterSpacing: -0.2,
          border: `2px solid ${T.bg || '#fff'}`,
          boxShadow: '0 2px 8px rgba(0,0,0,0.2)'
        }}>×{b.times}</div>
        }
      </div>
      <div style={{ textAlign: 'center' }}>
        <div style={{ fontFamily: 'Poppins', fontSize: 12, fontWeight: 600, color: T.text, letterSpacing: -0.1, lineHeight: 1.2 }}>{b.title}</div>
        <div style={{ fontFamily: 'Poppins', fontSize: 9, color: T.muted, fontWeight: 500, marginTop: 2 }}>{b.lastDate}</div>
      </div>
    </div>);

}