// Pau Fit — new home widgets
// Apple Health card, Spotify mini, Weekly calendar, Live cards,
// improved locked state for PRO content.

const { useState: useWg, useEffect: useEfWg } = React;

// ═════════════════════════════════════════════════════════════
// APPLE HEALTH CARD — three rings + week strip
// ═════════════════════════════════════════════════════════════
function AppleHealthCard({ T, onOpen }) {
  if (!HEALTH || !HEALTH.connected) return null;
  const h = HEALTH;
  const move = Math.min(1, h.activeKcal / h.activeKcalGoal);
  const exercise = Math.min(1, h.exerciseMin / h.exerciseGoal);
  const stand = Math.min(1, h.steps / h.stepsGoal);

  return (
    <div onClick={onOpen} style={{
      margin: '0 20px', padding: '18px 20px 16px',
      background: T.card, borderRadius: 20, border: T.border,
      cursor: 'pointer', position: 'relative', overflow: 'hidden',
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
        <AppleHealthGlyph/>
        <span style={{ fontSize: 11, color: T.muted, fontWeight: 600, letterSpacing: 0.5,  }}>Salud · Apple Health</span>
        <span style={{ marginLeft: 'auto', fontSize: 10, color: T.muted }}>conectada ✓</span>
      </div>

      <div style={{ display: 'flex', alignItems: 'center', gap: 18, marginTop: 14 }}>
        {/* Three-ring SVG */}
        <ThreeRings move={move} exercise={exercise} stand={stand} size={86}/>

        <div style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: 5 }}>
          <RingMetric color="#FA2D48" label="Movimiento" value={`${h.activeKcal}/${h.activeKcalGoal}`} unit="kcal" T={T}/>
          <RingMetric color="#A8E61D" label="Ejercicio"   value={`${h.exerciseMin}/${h.exerciseGoal}`} unit="min" T={T}/>
          <RingMetric color="#00C7C7" label="Pasos"       value={`${(h.steps/1000).toFixed(1)}/${h.stepsGoal/1000}`} unit="K" T={T}/>
        </div>
      </div>

      {/* Sub-stats */}
      <div style={{
        marginTop: 14, paddingTop: 12,
        borderTop: T.dark ? '0.5px solid rgba(255,255,255,0.05)' : '0.5px solid rgba(0,0,0,0.05)',
        display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 8,
      }}>
        <MiniStat icon="❤️" v={h.heartAvg} u="bpm" l="ritmo" T={T}/>
        <MiniStat icon="😴" v={`${h.sleep}h`} u="" l="sueño" T={T}/>
        <MiniStat icon="📍" v={`${(h.steps/1000).toFixed(1)}`} u="km" l="distancia" T={T}/>
      </div>
    </div>
  );
}

function ThreeRings({ move, exercise, stand, size = 72 }) {
  const stroke = 9;
  const gap = 3;
  const r1 = (size - stroke) / 2;
  const r2 = r1 - stroke - gap;
  const r3 = r2 - stroke - gap;
  const C = r => 2 * Math.PI * r;
  return (
    <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`} style={{ transform: 'rotate(-90deg)' }}>
      {[
        { r: r1, color: '#FA2D48', v: move },
        { r: r2, color: '#A8E61D', v: exercise },
        { r: r3, color: '#00C7C7', v: stand },
      ].map((ring, i) => (
        <g key={i}>
          <circle cx={size/2} cy={size/2} r={ring.r} fill="none" stroke={`${ring.color}28`} strokeWidth={stroke}/>
          <circle cx={size/2} cy={size/2} r={ring.r} fill="none" stroke={ring.color} strokeWidth={stroke}
            strokeDasharray={C(ring.r)} strokeDashoffset={C(ring.r) * (1 - ring.v)}
            strokeLinecap="round"
            style={{ transition: 'stroke-dashoffset 800ms cubic-bezier(.2,.8,.2,1)' }}/>
        </g>
      ))}
    </svg>
  );
}

function AppleHealthGlyph() {
  return (
    <svg width="20" height="20" viewBox="0 0 32 32">
      <rect x="1" y="1" width="30" height="30" rx="8" fill="#FFE5EC"/>
      <path d="M16 25 C 9 19, 6 15, 6 11.5 C 6 9, 8 7, 10.5 7 C 12.5 7, 14 8, 16 10.5 C 18 8, 19.5 7, 21.5 7 C 24 7, 26 9, 26 11.5 C 26 15, 23 19, 16 25 Z"
        fill="#F1325E"/>
    </svg>
  );
}

function RingMetric({ color, label, value, unit, T }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
      <span style={{ width: 6, height: 6, borderRadius: 999, background: color, flexShrink: 0 }}/>
      <span style={{ fontSize: 11, color: T.muted, fontWeight: 500 }}>{label}</span>
      <span style={{ marginLeft: 'auto', fontSize: 12, color: T.text, fontWeight: 600, fontVariantNumeric: 'tabular-nums', letterSpacing: -0.2 }}>
        {value}
        {unit && <span style={{ fontSize: 10, color: T.muted, fontWeight: 500, marginLeft: 3 }}>{unit}</span>}
      </span>
    </div>
  );
}

function MiniStat({ icon, v, u, l, T }) {
  return (
    <div style={{ textAlign: 'center' }}>
      <div style={{ fontSize: 14 }}>{icon}</div>
      <div style={{ fontSize: 14, fontWeight: 700, color: T.text, marginTop: 2, letterSpacing: -0.3 }}>
        {v}<span style={{ fontSize: 10, fontWeight: 500, color: T.muted, marginLeft: 1 }}>{u}</span>
      </div>
      <div style={{ fontSize: 9, color: T.muted, fontWeight: 500, letterSpacing: 0.4,  marginTop: 1 }}>{l}</div>
    </div>
  );
}

// ═════════════════════════════════════════════════════════════
// WEEKLY CALENDAR — auto plan strip + detail
// ═════════════════════════════════════════════════════════════
function WeeklyCalendar({ T, onDay }) {
  if (!WEEK_PLAN || WEEK_PLAN.length === 0) return null;
  return (
    <div style={{
      margin: '0 20px', padding: '16px 14px',
      background: T.card, borderRadius: 20, border: T.border,
    }}>
      <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', padding: '0 4px' }}>
        <div>
          <div style={{ fontSize: 11, color: T.muted, fontWeight: 600, letterSpacing: 0.5,  }}>Tu semana</div>
          <div className="pf-display" style={{ fontSize: 22, fontWeight: 500, color: T.text, marginTop: 2, letterSpacing: -0.4 }}>13–19 de mayo</div>
        </div>
        <span style={{ fontSize: 11, color: T.accent, fontWeight: 600 }}>5/7 ✓</span>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', gap: 5, marginTop: 14 }}>
        {WEEK_PLAN.map((d, i) => {
          const isToday = d.status === 'today';
          const isDone = d.status === 'done';
          return (
            <button key={i} onClick={() => onDay && onDay(d)} style={{
              padding: '8px 2px', cursor: 'pointer',
              border: isToday ? `1.5px solid ${T.accent}` : 'none',
              background: isToday ? `${T.accent}12` : (isDone ? T.subtle : 'transparent'),
              borderRadius: 14,
              display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 3,
              position: 'relative',
            }}>
              <span style={{ fontSize: 9, color: T.muted, fontWeight: 600, letterSpacing: 0.3 }}>{d.day}</span>
              <span style={{ fontSize: 15, fontWeight: 600, color: isToday ? T.accent : T.text, fontVariantNumeric: 'tabular-nums', letterSpacing: -0.3 }}>{d.date}</span>
              <span style={{ fontSize: 13, marginTop: 1, opacity: isDone || isToday ? 1 : 0.45 }}>{d.emoji}</span>
              {isDone && (
                <span style={{
                  position: 'absolute', top: 4, right: 4,
                  width: 10, height: 10, borderRadius: 999, background: '#A8E61D',
                  border: `1.5px solid ${T.card}`,
                }}/>
              )}
            </button>
          );
        })}
      </div>

      <div style={{
        marginTop: 12, padding: '10px 12px',
        background: T.bg, borderRadius: 14,
        display: 'flex', alignItems: 'center', gap: 10,
      }}>
        <span style={{ fontSize: 18 }}>{WEEK_PLAN.find(d => d.status === 'today')?.emoji}</span>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 10, color: T.accent, fontWeight: 700, letterSpacing: 0.4,  }}>Hoy</div>
          <div style={{ fontSize: 13, fontWeight: 600, color: T.text, marginTop: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
            {WEEK_PLAN.find(d => d.status === 'today')?.title}
          </div>
        </div>
        <span style={{ fontSize: 11, color: T.muted, fontWeight: 600 }}>{WEEK_PLAN.find(d => d.status === 'today')?.minutes} min</span>
      </div>
    </div>
  );
}

// ═════════════════════════════════════════════════════════════
// SPOTIFY MINI WIDGET
// ═════════════════════════════════════════════════════════════
function SpotifyWidget({ T, onOpenPlaylist }) {
  const [playing, setPlaying] = useWg(true);
  const s = SPOTIFY.current;
  // Si no hay Spotify conectado, no renderizar nada (el widget está dead code de momento)
  if (!s) return null;

  return (
    <div style={{
      margin: '0 20px', padding: '14px 16px',
      background: T.dark ? '#0B0B0B' : '#1DB954',
      backgroundImage: T.dark
        ? `linear-gradient(135deg, #1DB95440, #0B0B0B 70%)`
        : `linear-gradient(135deg, #1DB954 0%, #169443 100%)`,
      borderRadius: 20, position: 'relative', overflow: 'hidden',
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
        <SpotifyGlyph size={20} c="#fff"/>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 10, color: 'rgba(255,255,255,0.7)', fontWeight: 600, letterSpacing: 0.5,  }}>Sonando para entrenar</div>
          <div style={{ fontSize: 14, fontWeight: 600, color: '#fff', marginTop: 2, letterSpacing: -0.2 }}>
            {s.song} <span style={{ fontWeight: 400, opacity: 0.75 }}>· {s.artist}</span>
          </div>
        </div>
        <button onClick={(e) => { e.stopPropagation(); setPlaying(!playing); }} style={{
          width: 38, height: 38, borderRadius: 999, border: 'none',
          background: '#fff', cursor: 'pointer', flexShrink: 0,
          display: 'flex', alignItems: 'center', justifyContent: 'center', paddingLeft: playing ? 0 : 2,
        }}>
          {playing
            ? <svg width="14" height="14" viewBox="0 0 14 14"><rect x="3" y="2" width="3" height="10" rx="1" fill="#1DB954"/><rect x="8" y="2" width="3" height="10" rx="1" fill="#1DB954"/></svg>
            : <svg width="13" height="13" viewBox="0 0 13 13"><path d="M3 2l8 4.5-8 4.5V2z" fill="#1DB954"/></svg>
          }
        </button>
      </div>

      {/* Sound wave bars */}
      <div style={{
        marginTop: 10, display: 'flex', alignItems: 'flex-end', gap: 2, height: 14,
      }}>
        {Array.from({ length: 40 }).map((_, i) => (
          <span key={i} style={{
            flex: 1, height: `${30 + Math.abs(Math.sin(i * 0.6)) * 70}%`,
            background: 'rgba(255,255,255,0.5)', borderRadius: 1,
            opacity: i < 12 ? 1 : 0.4,
          }}/>
        ))}
      </div>

      {/* Playlists chips */}
      <div style={{ display: 'flex', gap: 6, marginTop: 10, overflowX: 'auto' }} className="hide-scroll">
        {SPOTIFY.playlists.map(p => (
          <button key={p.id} onClick={(e) => { e.stopPropagation(); onOpenPlaylist && onOpenPlaylist(p); }} style={{
            padding: '6px 10px', borderRadius: 999, border: 'none', cursor: 'pointer',
            background: 'rgba(255,255,255,0.16)', color: '#fff',
            fontSize: 11, fontWeight: 500, whiteSpace: 'nowrap',
          }}>{p.title}</button>
        ))}
      </div>
    </div>
  );
}

function SpotifyGlyph({ size = 18, c = '#1DB954' }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill={c}>
      <path d="M12 0C5.4 0 0 5.4 0 12s5.4 12 12 12 12-5.4 12-12S18.6 0 12 0zm5.5 17.3a.7.7 0 01-1 .2c-2.8-1.7-6.3-2.1-10.4-1.2a.7.7 0 01-.3-1.5c4.5-1 8.3-.6 11.5 1.4.4.2.5.7.2 1.1zm1.5-3.3a1 1 0 01-1.3.3c-3.2-2-8.1-2.5-12-1.4a.9.9 0 01-1.1-.6.9.9 0 01.6-1.1c4.4-1.3 9.8-.7 13.5 1.6.4.2.5.8.3 1.2zm.1-3.4c-3.9-2.3-10.3-2.5-14-1.4a1.1 1.1 0 01-.6-2.1c4.3-1.3 11.4-1 15.8 1.6a1.1 1.1 0 01-1.2 1.9z"/>
    </svg>
  );
}

// ═════════════════════════════════════════════════════════════
// LIVE WORKOUT CARDS
// ═════════════════════════════════════════════════════════════
function LiveWorkoutsStrip({ T, isPremium, nav }) {
  if (!LIVE_WORKOUTS || LIVE_WORKOUTS.length === 0) return null;
  return (
    <div>
      <div style={{
        display: 'flex', alignItems: 'baseline', justifyContent: 'space-between',
        padding: '24px 22px 12px',
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <span className="pf-display" style={{ fontSize: 22, fontWeight: 500, color: T.text, letterSpacing: -0.3 }}>Clases en vivo</span>
          <span style={{
            padding: '3px 7px', borderRadius: 5, background: '#E04545',
            fontSize: 8, fontWeight: 800, color: '#fff', letterSpacing: 0.6,
          }}>● EN VIVO</span>
        </div>
        <span style={{ fontSize: 11, color: T.muted, fontWeight: 500 }}>esta semana</span>
      </div>
      <div style={{
        display: 'flex', gap: 12, padding: '0 18px 4px',
        overflowX: 'auto', scrollSnapType: 'x mandatory',
      }} className="hide-scroll">
        {LIVE_WORKOUTS.map(l => {
          const locked = !isPremium;
          return (
            <div key={l.id} onClick={() => nav.go(locked ? 'paywall' : 'live', l.id)} style={{
              flexShrink: 0, width: 220, cursor: 'pointer', scrollSnapAlign: 'start',
              background: T.card, borderRadius: 20, padding: 0,
              border: T.border, overflow: 'hidden',
              display: 'flex', flexDirection: 'column',
            }}>
              {/* Hero with image-slot */}
              <div style={{
                position: 'relative', aspectRatio: '16 / 11',
                background: `linear-gradient(160deg, ${l.color}cc, ${l.color}66)`,
              }}>
                <image-slot
                  id={`live-${l.id}`}
                  placeholder={`Foto ${l.title}`}
                  shape="rect"
                  style={{ position: 'absolute', inset: 0 }}
                />
                {locked && (
                  <div style={{
                    position: 'absolute', inset: 0,
                    background: 'rgba(255,255,255,0.5)',
                    backdropFilter: 'blur(8px)',
                    WebkitBackdropFilter: 'blur(8px)',
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                  }}>
                    <div style={{
                      width: 40, height: 40, borderRadius: 999,
                      background: 'rgba(42,31,35,0.85)',
                      display: 'flex', alignItems: 'center', justifyContent: 'center',
                    }}>{Icon.lock('#fff', 16)}</div>
                  </div>
                )}
                {/* LIVE badge */}
                <div style={{
                  position: 'absolute', top: 10, left: 10,
                  display: 'flex', alignItems: 'center', gap: 5,
                  padding: '4px 8px', borderRadius: 6,
                  background: l.live ? '#E04545' : 'rgba(42,31,35,0.85)',
                  fontSize: 9, fontWeight: 800, color: '#fff', letterSpacing: 0.6,
                }}>
                  {l.live && <span style={{
                    width: 6, height: 6, borderRadius: 999, background: '#fff',
                    animation: 'live-pulse 1.5s ease-in-out infinite',
                  }}/>}
                  {l.tag}
                </div>
              </div>
              <div style={{ padding: '12px 14px' }}>
                <div style={{ fontSize: 14, fontWeight: 600, color: T.text, letterSpacing: -0.2, lineHeight: 1.2 }}>{l.title}</div>
                <div style={{ fontSize: 11, color: T.muted, marginTop: 4 }}>
                  {l.when} · {l.duration} min
                </div>
                <div style={{ fontSize: 11, color: T.accent, fontWeight: 600, marginTop: 6 }}>
                  💗 {l.attending.toLocaleString('es-ES')} apuntadas
                </div>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

// ═════════════════════════════════════════════════════════════
// HEALTH DETAIL SCREEN (clicking Apple Health card)
// ═════════════════════════════════════════════════════════════
function HealthDetailScreen({ theme, nav }) {
  const T = theme;
  const h = HEALTH;
  return (
    <div style={{ paddingBottom: 110 }}>
      {/* Header */}
      <div style={{ padding: '12px 20px 0', display: 'flex', alignItems: 'center', gap: 12 }}>
        <button onClick={() => nav.back()} style={{
          width: 36, height: 36, borderRadius: 999, border: 'none',
          background: T.card, cursor: 'pointer',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>{Icon.back(T.text)}</button>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 11, color: T.muted, fontWeight: 600, letterSpacing: 0.5,  }}>Salud</div>
          <div className="pf-display" style={{ fontSize: 22, fontWeight: 500, color: T.text, marginTop: 2, letterSpacing: -0.4 }}>Apple Health</div>
        </div>
        <AppleHealthGlyph/>
      </div>

      {/* Big rings */}
      <div style={{
        margin: '20px 18px 0', padding: '24px 20px',
        background: T.card, borderRadius: 20, border: T.border,
        display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 18,
      }}>
        <ThreeRings move={h.activeKcal/h.activeKcalGoal} exercise={h.exerciseMin/h.exerciseGoal} stand={h.steps/h.stepsGoal} size={180}/>
        <div style={{ width: '100%', display: 'flex', flexDirection: 'column', gap: 8 }}>
          <RingMetric color="#FA2D48" label="Movimiento" value={`${h.activeKcal}/${h.activeKcalGoal}`} unit="kcal" T={T}/>
          <RingMetric color="#A8E61D" label="Ejercicio"   value={`${h.exerciseMin}/${h.exerciseGoal}`} unit="min" T={T}/>
          <RingMetric color="#00C7C7" label="Pasos"       value={`${h.steps.toLocaleString('es-ES')}/${h.stepsGoal.toLocaleString('es-ES')}`} T={T}/>
        </div>
      </div>

      {/* Week strip */}
      <div style={{ padding: '20px 22px 8px' }}>
        <span style={{ fontSize: 11, color: T.muted, fontWeight: 600, letterSpacing: 0.5,  }}>Pasos · últimos 7 días</span>
      </div>
      <div style={{
        margin: '0 20px', padding: '18px 20px', background: T.card,
        borderRadius: 20, border: T.border,
      }}>
        <div style={{ display: 'flex', alignItems: 'flex-end', gap: 6, height: 110 }}>
          {h.weekSteps.map((v, i) => {
            const max = Math.max(...h.weekSteps.filter(x => x));
            const pct = v ? (v / max) : 0;
            const label = ['L','M','X','J','V','S','D'][i];
            return (
              <div key={i} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6 }}>
                <span style={{ fontSize: 9, color: T.muted, fontWeight: 600 }}>{v ? v.toLocaleString('es-ES') : '—'}</span>
                <div style={{
                  width: '100%', flex: 1, borderRadius: 6, position: 'relative',
                  background: T.subtle, overflow: 'hidden',
                  display: 'flex', alignItems: 'flex-end',
                }}>
                  <div style={{
                    width: '100%', height: `${pct*100}%`,
                    background: i === 4 ? T.accent : `${T.accent}88`,
                    borderRadius: 6,
                    transition: 'height 600ms ease',
                  }}/>
                </div>
                <span style={{ fontSize: 10, color: i === 4 ? T.accent : T.muted, fontWeight: 600 }}>{label}</span>
              </div>
            );
          })}
        </div>
      </div>

      {/* Detail rows */}
      <div style={{ padding: '20px 22px 8px' }}>
        <span style={{ fontSize: 11, color: T.muted, fontWeight: 600, letterSpacing: 0.5,  }}>Detalles</span>
      </div>
      <div style={{ margin: '0 20px', background: T.card, borderRadius: 20, border: T.border, overflow: 'hidden' }}>
        {[
          { e: '❤️', t: 'Ritmo cardíaco promedio', v: `${h.heartAvg} bpm`, sub: `Zona ${h.heartZone}` },
          { e: '😴', t: 'Sueño',                    v: `${h.sleep}h`,        sub: `Meta ${h.sleepGoal}h` },
          { e: '🚶', t: 'Distancia caminada',       v: `${(h.steps/1300).toFixed(1)} km`, sub: 'Hoy' },
          { e: '🔥', t: 'Calorías basales',         v: '1.580 kcal',          sub: 'Estimadas' },
          { e: '🧘', t: 'Minutos de mindfulness',   v: '12 min',              sub: 'Última sesión hace 1h' },
        ].map((o, i, a) => (
          <div key={i} style={{
            display: 'flex', alignItems: 'center', gap: 12, padding: '14px 16px',
            borderBottom: i < a.length-1 ? (T.dark ? '0.5px solid rgba(255,255,255,0.05)' : '0.5px solid rgba(0,0,0,0.05)') : 'none',
          }}>
            <span style={{ fontSize: 20 }}>{o.e}</span>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 13, fontWeight: 500, color: T.text }}>{o.t}</div>
              <div style={{ fontSize: 10, color: T.muted, marginTop: 1 }}>{o.sub}</div>
            </div>
            <span style={{ fontSize: 14, fontWeight: 700, color: T.text, fontVariantNumeric: 'tabular-nums', letterSpacing: -0.2 }}>{o.v}</span>
          </div>
        ))}
      </div>

      <div style={{
        margin: '16px 18px 0', padding: '14px 16px',
        background: `${T.accent}10`, borderRadius: 20,
        border: `0.5px solid ${T.accent}30`,
        display: 'flex', alignItems: 'center', gap: 10,
      }}>
        <span style={{ fontSize: 18 }}>💡</span>
        <span style={{ fontSize: 12, color: T.text, fontWeight: 500, lineHeight: 1.4 }}>
          Conecta tu Apple Watch para registrar tus entrenos de Pau Fit automáticamente.
        </span>
      </div>
    </div>
  );
}

// ═════════════════════════════════════════════════════════════
// LIVE DETAIL SCREEN
// ═════════════════════════════════════════════════════════════
function LiveDetailScreen({ liveId, theme, isPremium, nav }) {
  const T = theme;
  const l = LIVE_WORKOUTS.find(x => x.id === liveId);
  const [joined, setJoined] = useWg(false);
  if (!l) return null;

  return (
    <div style={{ paddingBottom: 110 }}>
      {/* Hero */}
      <div style={{
        position: 'relative', height: 340,
        background: `linear-gradient(160deg, ${l.color}cc, ${l.color}66)`,
        borderBottomLeftRadius: 32, borderBottomRightRadius: 32,
        overflow: 'hidden',
      }}>
        <image-slot
          id={`live-hero-${l.id}`}
          placeholder={`Foto del live ${l.title}`}
          shape="rect"
          style={{ position: 'absolute', inset: 0 }}
        />
        <div style={{
          position: 'absolute', inset: 0,
          background: 'linear-gradient(180deg, rgba(0,0,0,0.15) 0%, transparent 30%, rgba(0,0,0,0.55) 100%)',
        }}/>
        <div style={{ position: 'absolute', top: 12, left: 22, right: 22, display: 'flex', justifyContent: 'space-between' }}>
          <button onClick={() => nav.back()} style={{
            width: 36, height: 36, borderRadius: 999, border: 'none',
            background: 'rgba(255,255,255,0.6)', backdropFilter: 'blur(10px)',
            cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}>{Icon.back('#2A1F23')}</button>
          <button onClick={() => {
            const userName = (window.__pauCache?.profile?.full_name || window.__pauCache?.profile?.username || '').trim();
            const text = userName
              ? `${userName} va a ver "${l.title}" en Pau Fit 🎥 ${l.live ? 'EN VIVO' : 'live'} con ${l.coach || 'Pau'} — ¡únete!`
              : `Mira este live de Pau Fit: "${l.title}" ${l.live ? '🔴 EN VIVO' : '🎥'} — únete!`;
            window.PauShare && window.PauShare({ title: `${l.title} · Pau Fit`, text, url: 'https://app.paufit.co' }).then(function(r){ if (r.shared) nav.toast(r.method === 'native' ? 'Compartido' : 'Enlace copiado 💗', { icon: '↗' }) });
          }} style={{
            width: 36, height: 36, borderRadius: 999, border: 'none',
            background: 'rgba(255,255,255,0.6)', backdropFilter: 'blur(10px)',
            cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}>{Icon.share('#2A1F23')}</button>
        </div>
        <div style={{ position: 'absolute', bottom: 20, left: 22, right: 22 }}>
          <div style={{
            display: 'inline-flex', alignItems: 'center', gap: 6,
            padding: '5px 10px', borderRadius: 6,
            background: l.live ? '#E04545' : 'rgba(42,31,35,0.85)',
            fontSize: 9, fontWeight: 800, color: '#fff', letterSpacing: 0.8,
          }}>
            {l.live && <span style={{
              width: 7, height: 7, borderRadius: 999, background: '#fff',
              animation: 'live-pulse 1.5s ease-in-out infinite',
            }}/>}
            {l.tag} · {l.when}
          </div>
          <div className="pf-display" style={{ fontSize: 30, fontWeight: 500, color: '#fff', marginTop: 10, letterSpacing: -0.6, lineHeight: 1.1, textShadow: '0 1px 8px rgba(0,0,0,0.3)' }}>
            {l.title}
          </div>
          <div style={{ fontSize: 13, color: 'rgba(255,255,255,0.85)', marginTop: 4 }}>Con {l.coach}</div>
        </div>
      </div>

      {/* Stats */}
      <div style={{ display: 'flex', justifyContent: 'space-around', padding: '20px 20px 0' }}>
        <SmallStatLive v={`${l.duration}'`} l="duración" T={T}/>
        <SmallStatLive v={l.attending.toLocaleString('es-ES')} l="apuntadas" T={T}/>
        <SmallStatLive v="HD" l="calidad" T={T}/>
      </div>

      {/* Description */}
      <div style={{ padding: '24px 20px 0' }}>
        <div style={{ fontSize: 11, color: T.muted, fontWeight: 600, letterSpacing: 0.5,  }}>Sobre la clase</div>
        <p style={{ fontSize: 14, color: T.text, marginTop: 8, lineHeight: 1.55 }}>
          Entrenamiento {l.live ? 'en directo ahora mismo' : 'guiado en directo'} con Pau Moreno.
          Verás a Pau en tiempo real, podrás escribir en el chat en vivo y al terminar quedará
          guardado para repetirlo cuando quieras.
        </p>
      </div>

      {/* Bullets */}
      <div style={{ padding: '20px 20px 0' }}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {[
            { e: '🎥', t: 'Cámara HD multi-ángulo', s: 'Verás cada ejercicio en detalle' },
            { e: '💬', t: 'Chat en vivo', s: 'Habla con Pau y con la comunidad' },
            { e: '⏱️', t: 'Sincroniza con tu Apple Watch', s: 'Calorías y ritmo cardíaco en pantalla' },
            { e: '📥', t: 'Disponible siempre después', s: 'En tu biblioteca, sin caducidad' },
          ].map((o, i) => (
            <div key={i} style={{
              padding: '12px 14px', background: T.card, borderRadius: 20, border: T.border,
              display: 'flex', alignItems: 'center', gap: 12,
            }}>
              <div style={{
                width: 40, height: 40, borderRadius: 14,
                background: T.subtle,
                display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 20,
              }}>{o.e}</div>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 13, fontWeight: 600, color: T.text }}>{o.t}</div>
                <div style={{ fontSize: 11, color: T.muted, marginTop: 1 }}>{o.s}</div>
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* Join button */}
      <div style={{ padding: '24px 18px 0' }}>
        <button onClick={() => {
          setJoined(true);
          nav.toast(l.live ? 'Entrando al live 💗' : 'Apuntada al live ✓', { icon: l.live ? '🔴' : '✓' });
        }} disabled={joined} style={{
          width: '100%', padding: '16px',
          border: 'none', borderRadius: 20, cursor: 'pointer',
          background: joined ? T.subtle : l.color,
          color: joined ? T.text : '#fff',
          fontSize: 15, fontWeight: 600, letterSpacing: -0.1,
          boxShadow: joined ? 'none' : `0 6px 18px ${l.color}55`,
          display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
        }}>
          {joined ? '✓ Apuntada' : (l.live ? '🔴 Entrar al live ahora' : 'Apuntarme al live')}
        </button>
        {joined && (
          <div style={{ textAlign: 'center', marginTop: 10, fontSize: 11, color: T.muted }}>
            Te avisaremos 15 min antes del live 🔔
          </div>
        )}
      </div>
    </div>
  );
}

function SmallStatLive({ v, l, T }) {
  return (
    <div style={{ textAlign: 'center', flex: 1 }}>
      <div className="pf-display" style={{ fontSize: 24, fontWeight: 500, color: T.text, letterSpacing: -0.5 }}>{v}</div>
      <div style={{ fontSize: 10, color: T.muted, marginTop: 2, fontWeight: 500, letterSpacing: 0.5,  }}>{l}</div>
    </div>
  );
}

// ═════════════════════════════════════════════════════════════
// LOCKED OVERLAY — for blurred PRO cards
// ═════════════════════════════════════════════════════════════
function LockedOverlay({ T, label = 'PREMIUM' }) {
  return (
    <div style={{
      position: 'absolute', inset: 0,
      background: T.dark ? 'rgba(11,9,12,0.55)' : 'rgba(255,255,255,0.45)',
      backdropFilter: 'blur(6px) saturate(140%)',
      WebkitBackdropFilter: 'blur(6px) saturate(140%)',
      display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 8,
      borderRadius: 'inherit',
    }}>
      <div style={{
        width: 44, height: 44, borderRadius: 999,
        background: T.dark ? 'rgba(255,255,255,0.92)' : 'rgba(42,31,35,0.92)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>{Icon.lock(T.dark ? '#2A1F23' : '#fff', 18)}</div>
      <span style={{
        padding: '4px 10px', borderRadius: 6,
        background: '#2A1F23', color: T.gold,
        fontSize: 9, fontWeight: 800, letterSpacing: 1.4,
      }}>{label}</span>
    </div>
  );
}

// ═════════════════════════════════════════════════════════════
// SPOTIFY SCREEN — playlists + now playing
// ═════════════════════════════════════════════════════════════
function SpotifyScreen({ theme, nav }) {
  const T = theme;
  const [playing, setPlaying] = useWg(true);
  // Fallback si SPOTIFY.current es null (Spotify no conectado todavía)
  const [current, setCurrent] = useWg(SPOTIFY.current || { song: '—', artist: 'Conecta Spotify para escuchar' });
  const [progress, setProgress] = useWg(0.42);
  const [shuffle, setShuffle] = useWg(false);
  const [repeat, setRepeat] = useWg('off'); // off | one | all

  useEfWg(() => {
    if (!playing) return;
    const id = setInterval(() => setProgress(p => (p + 0.005) % 1), 200);
    return () => clearInterval(id);
  }, [playing]);

  const allTracks = [
    { song: 'Padam Padam', artist: 'Kylie Minogue', duration: '3:21' },
    { song: 'Espresso', artist: 'Sabrina Carpenter', duration: '2:55' },
    { song: 'Houdini', artist: 'Dua Lipa', duration: '3:30' },
    { song: 'Texas Hold \'Em', artist: 'Beyoncé', duration: '3:54' },
    { song: 'Greedy', artist: 'Tate McRae', duration: '2:11' },
    { song: 'Dance The Night', artist: 'Dua Lipa', duration: '2:57' },
    { song: 'Murder On The Dancefloor', artist: 'Sophie Ellis-Bextor', duration: '3:48' },
    { song: 'Levitating', artist: 'Dua Lipa', duration: '3:23' },
  ];

  return (
    <div style={{ paddingBottom: 120, background: '#0F0F0F', minHeight: '100%', color: '#fff' }}>
      {/* Header */}
      <div style={{ padding: '12px 20px 0', display: 'flex', alignItems: 'center', gap: 12 }}>
        <button onClick={() => nav.back()} style={{
          width: 36, height: 36, borderRadius: 999, border: 'none',
          background: 'rgba(255,255,255,0.1)', cursor: 'pointer',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>{Icon.back('#fff')}</button>
        <div style={{ flex: 1 }}>
          <div className="pf-eyebrow" style={{ color: 'rgba(255,255,255,0.6)' }}>Spotify</div>
          <div style={{ fontSize: 17, fontWeight: 700, color: '#fff' }}>Tu música</div>
        </div>
        <SpotifyGlyph size={22} c="#1DB954"/>
      </div>

      {/* Cover */}
      <div style={{ padding: '20px 32px 0' }}>
        <div style={{
          aspectRatio: '1', borderRadius: 20, overflow: 'hidden',
          position: 'relative',
          background: `linear-gradient(135deg, ${T.accent}, ${T.deep})`,
          boxShadow: '0 20px 50px rgba(255,46,120,0.35)',
        }}>
          <image-slot
            id="spotify-cover"
            placeholder="Cover Pau Cardio Mix"
            shape="rect"
            style={{ position: 'absolute', inset: 0 }}
          />
        </div>
      </div>

      {/* Track info */}
      <div style={{ padding: '24px 32px 0' }}>
        <div className="pf-eyebrow" style={{ color: '#1DB954' }}>Reproduciendo</div>
        <div className="pf-display" style={{ fontSize: 26, fontWeight: 800, color: '#fff', marginTop: 4, letterSpacing: -0.6 }}>
          {current.song}
        </div>
        <div style={{ fontSize: 14, color: 'rgba(255,255,255,0.6)', marginTop: 2 }}>
          {current.artist} · Pau Cardio Mix
        </div>

        {/* Progress */}
        <div style={{ marginTop: 16 }}>
          <div style={{
            height: 3, background: 'rgba(255,255,255,0.2)', borderRadius: 999, overflow: 'hidden',
            cursor: 'pointer',
          }} onClick={(e) => {
            const r = e.currentTarget.getBoundingClientRect();
            setProgress((e.clientX - r.left) / r.width);
          }}>
            <div style={{ width: `${progress*100}%`, height: '100%', background: '#fff', borderRadius: 999, transition: 'width 200ms linear' }}/>
          </div>
          <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 6, fontSize: 10, color: 'rgba(255,255,255,0.5)', fontVariantNumeric: 'tabular-nums', fontWeight: 600 }}>
            <span>{Math.floor(progress * 200 / 60)}:{String(Math.floor(progress * 200 % 60)).padStart(2,'0')}</span>
            <span>3:21</span>
          </div>
        </div>

        {/* Controls — todos funcionales */}
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 24, marginTop: 16 }}>
          <button onClick={() => {
            setShuffle(s => !s);
            nav.toast(shuffle ? 'Shuffle off' : 'Shuffle on 🔀', { icon: '🔀' });
          }} style={{
            background: 'transparent', border: 'none', cursor: 'pointer', fontSize: 18,
            opacity: shuffle ? 1 : 0.5,
            color: shuffle ? '#1DB954' : '#fff',
          }}>🔀</button>
          <button onClick={() => {
            const idx = allTracks.findIndex(t => t.song === current.song);
            const prev = allTracks[(idx - 1 + allTracks.length) % allTracks.length];
            setCurrent({ song: prev.song, artist: prev.artist });
            setProgress(0);
          }} style={{ background: 'transparent', border: 'none', cursor: 'pointer', color: '#fff', fontSize: 22 }}>⏮</button>
          <button onClick={() => setPlaying(!playing)} style={{
            width: 60, height: 60, borderRadius: 999, border: 'none', cursor: 'pointer',
            background: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', paddingLeft: playing ? 0 : 3,
          }}>
            {playing
              ? <svg width="22" height="22" viewBox="0 0 22 22"><rect x="5" y="3" width="4" height="16" rx="1" fill="#0F0F0F"/><rect x="13" y="3" width="4" height="16" rx="1" fill="#0F0F0F"/></svg>
              : <svg width="20" height="20" viewBox="0 0 22 22"><path d="M6 3l13 8-13 8V3z" fill="#0F0F0F"/></svg>
            }
          </button>
          <button onClick={() => {
            const idx = allTracks.findIndex(t => t.song === current.song);
            // Si shuffle on, random; si no, siguiente
            const nextIdx = shuffle
              ? Math.floor(Math.random() * allTracks.length)
              : (idx + 1) % allTracks.length;
            const next = allTracks[nextIdx];
            setCurrent({ song: next.song, artist: next.artist });
            setProgress(0);
          }} style={{ background: 'transparent', border: 'none', cursor: 'pointer', color: '#fff', fontSize: 22 }}>⏭</button>
          <button onClick={() => {
            const states = { off: 'one', one: 'all', all: 'off' };
            const next = states[repeat];
            setRepeat(next);
            nav.toast(next === 'off' ? 'Repeat off' : next === 'one' ? 'Repeat 1 🔂' : 'Repeat all 🔁', { icon: '🔁' });
          }} style={{
            background: 'transparent', border: 'none', cursor: 'pointer', fontSize: 18,
            opacity: repeat === 'off' ? 0.5 : 1,
            color: repeat === 'off' ? '#fff' : '#1DB954',
          }}>{repeat === 'one' ? '🔂' : '🔁'}</button>
        </div>
      </div>

      {/* Up next */}
      <div style={{ padding: '32px 22px 12px' }}>
        <div className="pf-eyebrow" style={{ color: 'rgba(255,255,255,0.6)' }}>Siguiente</div>
      </div>
      <div style={{ padding: '0 20px', display: 'flex', flexDirection: 'column', gap: 4 }}>
        {allTracks.map(t => {
          const isPlaying = t.song === current.song;
          return (
            <div key={t.song} onClick={() => { setCurrent({ song: t.song, artist: t.artist }); setProgress(0); }} style={{
              padding: '10px 12px', cursor: 'pointer', borderRadius: 14,
              display: 'flex', alignItems: 'center', gap: 12,
              background: isPlaying ? 'rgba(29,185,84,0.14)' : 'transparent',
            }}>
              <div style={{
                width: 36, height: 36, borderRadius: 6,
                background: `linear-gradient(135deg, ${T.accent}, ${T.deep})`,
                display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 13,
                flexShrink: 0,
              }}>{isPlaying ? '▶' : '🎵'}</div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 13, fontWeight: 600, color: isPlaying ? '#1DB954' : '#fff' }}>{t.song}</div>
                <div style={{ fontSize: 11, color: 'rgba(255,255,255,0.55)', marginTop: 1 }}>{t.artist}</div>
              </div>
              <span style={{ fontSize: 11, color: 'rgba(255,255,255,0.5)', fontVariantNumeric: 'tabular-nums' }}>{t.duration}</span>
            </div>
          );
        })}
      </div>
    </div>
  );
}

// ═════════════════════════════════════════════════════════════
// RANKING SCREEN — leaderboard REAL (top 100 desde Supabase)
// ═════════════════════════════════════════════════════════════
function RankingScreen({ theme, nav }) {
  const T = theme;
  // SIEMPRE mostrar top 100 (público) + tu posición PRIVADA (solo tú la ves)
  // SIN número de usuarias activas en ninguna parte
  const [rankings, setRankings] = React.useState(null);
  const [myPos, setMyPos] = React.useState(null);
  const [error, setError] = React.useState(null);

  React.useEffect(() => {
    const sb = window.__PAU_SUPABASE;
    if (!sb) { setError('No conectado'); return; }
    (async () => {
      try {
        // 1) Top 100 público (ordenado por puntos) — leemos is_public para ocultar nombre
        const { data: top } = await sb
          .from('profiles')
          .select('id, full_name, username, points, is_public, avatar_url')
          .gt('points', 0)
          .order('points', { ascending: false })
          .limit(100);

        // 2) Mi posición REAL — solo visible para mí
        const { data: { user } } = await sb.auth.getUser();
        if (user) {
          const { data: me } = await sb.from('profiles').select('points').eq('id', user.id).maybeSingle();
          const myPoints = me?.points || 0;
          // cuántas tienen más puntos que yo = mi posición - 1
          const { count: ahead } = await sb
            .from('profiles')
            .select('*', { count: 'exact', head: true })
            .gt('points', myPoints);
          const inTopIdx = (top || []).findIndex(r => r.id === user.id);
          setMyPos({
            position: (ahead || 0) + 1,
            points: myPoints,
            inTop: inTopIdx !== -1,
          });
        }
        setRankings(top || []);
      } catch (e) {
        setError(e.message || 'Error cargando ranking');
      }
    })();
  }, []);

  function initialsOf(name) {
    if (!name) return '?';
    return name.split(' ').map(s => s[0]).slice(0,2).join('').toUpperCase();
  }

  return (
    <div style={{ paddingBottom: 120 }}>
      <div style={{ padding: '12px 20px 0', display: 'flex', alignItems: 'center', gap: 12 }}>
        <button onClick={() => nav.back()} style={{
          width: 36, height: 36, borderRadius: 999, border: 'none',
          background: T.card, cursor: 'pointer',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>{Icon.back(T.text)}</button>
        <div style={{ flex: 1 }}>
          <div className='pf-eyebrow' style={{ color: T.muted }}>Comunidad</div>
          <div className='pf-display' style={{ fontSize: 24, fontWeight: 800, color: T.text, letterSpacing: -0.6 }}>Top 100</div>
        </div>
      </div>

      {/* TU POSICIÓN (privada — solo tú la ves) */}
      {myPos && (
        <div style={{
          margin: '16px 20px 0', padding: '14px 16px',
          background: `linear-gradient(135deg, ${T.accent}, ${T.deep})`,
          borderRadius: 20,
          boxShadow: `0 8px 22px ${T.accent}40`,
          display: 'flex', alignItems: 'center', gap: 12,
        }}>
          <div style={{
            width: 44, height: 44, borderRadius: 14,
            background: 'rgba(255,255,255,0.22)', backdropFilter: 'blur(8px)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontSize: 18,
          }}>👑</div>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 10, fontWeight: 700, letterSpacing: 0.6,  color: 'rgba(255,255,255,0.8)' }}>
              Tu posición (privada)
            </div>
            <div style={{ fontSize: 20, fontWeight: 800, color: '#fff', marginTop: 2, letterSpacing: -0.3 }}>
              #{myPos.position}
              {myPos.inTop && <span style={{ fontSize: 12, fontWeight: 600, marginLeft: 8, opacity: 0.85 }}>En el Top 100 🎉</span>}
            </div>
          </div>
          <div style={{ textAlign: 'right' }}>
            <div style={{ fontSize: 22, fontWeight: 800, color: '#fff', lineHeight: 1, letterSpacing: -0.3 }}>{myPos.points}</div>
            <div style={{ fontSize: 9, fontWeight: 600, letterSpacing: 0.5, color: 'rgba(255,255,255,0.75)', marginTop: 2 }}>PUNTOS</div>
          </div>
        </div>
      )}

      {!rankings && !error && <SkeletonList count={5} T={T}/>}

      {error && (
        <div style={{ padding: 30, textAlign: 'center', color: T.muted, fontSize: 13 }}>
          {error}
        </div>
      )}

      {/* TOP 100 PÚBLICO (sin número de usuarias totales) */}
      {rankings && rankings.length === 0 && (
        <EmptyState
          emoji="🏆" T={T}
          title="El Top 100 aún no tiene nombres"
          description="Sé de las primeras en aparecer aquí. Completa días para sumar puntos."
          ctaLabel="Empezar un reto"
          onCta={() => nav.tab('retos')}
        />
      )}

      {rankings && rankings.length > 0 && (
        <div style={{ margin: '20px 20px 0', display: 'flex', flexDirection: 'column', gap: 8 }}>
          {rankings.map((u, i) => {
            const isTop3 = i < 3;
            const isPublic = u.is_public !== false;
            const clickable = isPublic;
            return (
              <button key={u.id} onClick={() => {
                if (clickable && nav.go) nav.go('perfilPublico', u.id);
              }} disabled={!clickable} style={{
                display: 'flex', alignItems: 'center', gap: 12,
                padding: '12px 16px', borderRadius: 20,
                background: isTop3 ? T.subtle : T.card,
                border: T.border,
                cursor: clickable ? 'pointer' : 'default',
                textAlign: 'left', fontFamily: 'inherit', width: '100%',
              }}>
                <span style={{
                  width: 28, textAlign: 'center', fontSize: 13, fontWeight: 800,
                  color: i === 0 ? '#D4A017' : i === 1 ? '#A8A8A8' : i === 2 ? '#CD7F32' : T.muted,
                }}>
                  {i === 0 ? '🥇' : i === 1 ? '🥈' : i === 2 ? '🥉' : i + 1}
                </span>
                <div style={{
                  width: 36, height: 36, borderRadius: 999,
                  background: u.avatar_url ? '#fff' : T.accent, color: '#fff',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  fontSize: 11, fontWeight: 700, overflow: 'hidden',
                }}>
                  {!isPublic
                    ? '?'
                    : u.avatar_url
                      ? <img src={u.avatar_url} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }}/>
                      : initialsOf(u.full_name || u.username)
                  }
                </div>
                <span style={{ flex: 1, fontSize: 13, fontWeight: 600, color: T.text }}>
                  {!isPublic ? 'Anónima' : (u.full_name || u.username || 'Anónima')}
                </span>
                <span style={{ fontSize: 13, fontWeight: 700, color: T.accent }}>{u.points}</span>
                {clickable && <span style={{ fontSize: 12, color: T.muted, marginLeft: 4 }}>›</span>}
              </button>
            );
          })}
        </div>
      )}
    </div>
  );
}

Object.assign(window, {
  AppleHealthCard, ThreeRings, AppleHealthGlyph,
  WeeklyCalendar, SpotifyWidget, SpotifyGlyph,
  LiveWorkoutsStrip, LiveDetailScreen, HealthDetailScreen,
  LockedOverlay, SpotifyScreen, RankingScreen,
});
