// ═══════════════════════════════════════════════════════════════
// Pau Fit — PROGRAMAS estructurados por semanas (estilo Sweat)
//
// - ProgramasSection: carrusel de programas para el tab Entreno
// - ProgramaDetailScreen: detalle con semanas, días y progreso
// - ProgramaTodayHero: héroe "tu entreno de hoy" para Home
//
// Datos: window.PauUserProgramas (user-programas.js) + __pauCache
// ═══════════════════════════════════════════════════════════════

// Aliases propios de hooks (cada archivo Babel declara los suyos)
const usePgState = React.useState;
const usePgEffect = React.useEffect;

function programaCoverUrl(p) {
  return p && p.cover_path
    ? `${window.__PAU_SUPABASE_URL || ''}/storage/v1/object/public/programas-covers/${p.cover_path}`
    : null;
}

// Refresca el cache del programa activo (y sus días) y notifica a la app
async function refreshProgramaCache() {
  try {
    const api = window.PauUserProgramas;
    if (!api) return;
    const active = await api.getActive();
    window.__pauCache = window.__pauCache || {};
    window.__pauCache.activePrograma = active;
    if (active) {
      window.__pauCache.activeProgramaDays = await api.getDays(active.programa_id);
      if (!(window.__pauCache.programas || []).find(x => x.id === active.programa_id)) {
        const p = await api.getPrograma(active.programa_id);
        if (p) window.__pauCache.programas = [...(window.__pauCache.programas || []), p];
      }
    } else {
      window.__pauCache.activeProgramaDays = null;
    }
    window.dispatchEvent(new CustomEvent('pau:cache-updated'));
  } catch (e) {
    console.warn('[programas cache]', e?.message || e);
  }
}

// ─────────────────────────────────────────────────────────────
// Carrusel de programas — se muestra arriba del tab Entreno
// ─────────────────────────────────────────────────────────────
function ProgramasSection({ T, isPremium, nav, searchQ = '' }) {
  const q = (searchQ || '').toLowerCase().trim();
  const programas = ((window.__pauCache && window.__pauCache.programas) || []).filter(p => {
    if (q && !(`${p.title} ${p.subtitle || ''} ${p.goal || ''}`).toLowerCase().includes(q)) return false;
    return true;
  });
  if (!programas.length) return null;

  const activeProg = window.__pauCache && window.__pauCache.activePrograma;

  function ProgramaCard({ p }) {
    const locked = p.is_premium && !isPremium;
    const isActive = activeProg && activeProg.programa_id === p.id;
    const coverUrl = programaCoverUrl(p);
    return (
      <div onClick={() => nav.go(locked ? 'paywall' : 'programa', p.id)} style={{
        flexShrink: 0, width: 260, cursor: 'pointer',
        borderRadius: 22, overflow: 'hidden',
        position: 'relative', aspectRatio: '3 / 4',
        background: coverUrl
          ? `url(${coverUrl}) center/cover no-repeat`
          : `linear-gradient(135deg, ${T.accent}, ${T.deep})`,
      }}>
        {!coverUrl && (
          <div style={{ position: 'absolute', top: '30%', left: 0, right: 0, textAlign: 'center', fontSize: 72, opacity: 0.55 }}>
            {p.emoji || '📅'}
          </div>
        )}
        <div style={{
          position: 'absolute', inset: 0,
          background: 'linear-gradient(180deg, rgba(0,0,0,0.25) 0%, transparent 35%, rgba(0,0,0,0.8) 100%)',
        }}/>
        {/* Badge semanas — lo que lo distingue de retos/rutinas */}
        <div style={{
          position: 'absolute', top: 12, left: 12,
          padding: '5px 10px', borderRadius: 6,
          background: 'rgba(255,255,255,0.95)', color: '#0E0A0C',
          fontSize: 9, fontWeight: 800, letterSpacing: 1,
        }}>{p.weeks} SEMANAS</div>
        {isActive && (
          <div style={{
            position: 'absolute', top: 12, right: 12,
            padding: '5px 10px', borderRadius: 999,
            background: '#fff', color: T.text,
            fontSize: 9, fontWeight: 800, letterSpacing: 0.6,
          }}>EN CURSO ✓</div>
        )}
        {locked && !isActive && (
          <div style={{
            position: 'absolute', top: 12, right: 12,
            width: 30, height: 30, borderRadius: 999,
            background: 'rgba(14,10,12,0.7)', backdropFilter: 'blur(10px)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}>{Icon.lock('#fff', 13)}</div>
        )}
        <div style={{ position: 'absolute', bottom: 14, left: 14, right: 14, color: '#fff' }}>
          <div className="pf-display-bold" style={{
            fontSize: 18, color: '#fff', lineHeight: 1.05, letterSpacing: -0.4,
            textShadow: '0 2px 8px rgba(0,0,0,0.5)',
            display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden',
          }}>{p.title}</div>
          <div style={{
            marginTop: 6, fontSize: 9, fontWeight: 800, letterSpacing: 0.6,
            color: 'rgba(255,255,255,0.92)', textShadow: '0 1px 3px rgba(0,0,0,0.5)',
            
          }}>
            {p.days_per_week || 5} DÍAS/SEMANA · {p.level || 'Todos los niveles'}
          </div>
        </div>
      </div>
    );
  }

  return (
    <div style={{ marginTop: 24 }}>
      <div style={{ padding: '0 20px', display: 'flex', alignItems: 'baseline', gap: 8 }}>
        <div className="pf-display-bold" style={{ fontSize: 16, color: T.text, lineHeight: 1 }}>
          Programas por semanas
        </div>
        <span style={{ fontSize: 10, fontWeight: 800, color: T.accent, letterSpacing: 0.6 }}>NUEVO</span>
      </div>
      <div style={{ padding: '0 20px', marginTop: 4, fontSize: 11.5, color: T.muted, fontWeight: 500 }}>
        Tu plan día a día — la app te dice qué toca hoy
      </div>
      <div style={{
        marginTop: 14, display: 'flex', gap: 12, overflowX: 'auto', padding: '0 20px 4px',
      }} className="hide-scroll">
        {programas.map(p => <ProgramaCard key={p.id} p={p}/>)}
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Detalle de programa: hero + progreso + semanas + días
// ─────────────────────────────────────────────────────────────
function ProgramaDetailScreen({ programaId, theme, isPremium, nav }) {
  const T = theme;
  const [programa, setPrograma] = usePgState(
    ((window.__pauCache && window.__pauCache.programas) || []).find(x => x.id === programaId) || null
  );
  const [days, setDays] = usePgState(null); // null = cargando
  const [enrollment, setEnrollment] = usePgState(null);
  const [busy, setBusy] = usePgState(false);
  const [, setBump] = usePgState(0);
  // Semana seleccionada en las pills (null = la actual de la usuaria)
  const [selWeek, setSelWeek] = usePgState(null);

  const api = window.PauUserProgramas;

  usePgEffect(() => {
    let dead = false;
    (async () => {
      if (!api) return;
      const [p, d, e] = await Promise.all([
        programa ? Promise.resolve(programa) : api.getPrograma(programaId),
        api.getDays(programaId),
        api.getForPrograma(programaId),
      ]);
      if (dead) return;
      if (p) setPrograma(p);
      setDays(d);
      setEnrollment(e && !e.completed_at ? e : null);
    })();
    const handler = () => setBump(x => x + 1);
    window.addEventListener('pau:cache-updated', handler);
    return () => { dead = true; window.removeEventListener('pau:cache-updated', handler); };
  }, [programaId]);

  if (!programa) return null;

  const locked = programa.is_premium && !isPremium;
  const coverUrl = programaCoverUrl(programa);
  const totalDays = (programa.weeks || 4) * 7;
  const enrolled = !!enrollment;
  const completedDays = (enrollment && enrollment.completed_days) || [];
  const currentDay = (enrollment && enrollment.current_day) || 1;
  const currentWeek = api ? api.weekOf(currentDay) : 1;
  const programaDone = enrolled && completedDays.length >= totalDays;
  const week = selWeek || (enrolled ? currentWeek : 1);

  // Desbloqueo diario a las 12am local (mismo patrón que retos)
  const todayStr = new Date().toLocaleDateString('en-CA');
  let lastDoneLocal = null;
  try { lastDoneLocal = localStorage.getItem(`paufit-prog-last-done-${programaId}`); } catch {}
  const doneToday = lastDoneLocal === todayStr;

  const rutinas = (window.__pauCache && window.__pauCache.rutinas) || [];
  const dayRows = (days || []).filter(d => d.week === week);
  const workoutsInProgram = (days || []).filter(d => d.kind === 'workout').length;

  async function handleStart() {
    if (locked) { nav.go('paywall'); return; }
    if (!api) return;
    setBusy(true);
    let res = await api.start(programaId);
    if (res && res.conflict) {
      const ok = window.confirm('Ya tienes otro programa en curso. ¿Quieres dejarlo y empezar este?');
      if (!ok) { setBusy(false); return; }
      res = await api.start(programaId, { force: true });
    }
    setBusy(false);
    if (res && res.error) {
      nav.toast('Error: ' + res.error, { icon: '⚠️' });
      return;
    }
    if (res && res.row) {
      setEnrollment(res.row);
      setSelWeek(1);
      nav.toast('¡Programa empezado! 💗', { icon: '🎉' });
      refreshProgramaCache();
    }
  }

  async function handleAbandon() {
    if (!enrollment) return;
    const ok = window.confirm('¿Seguro que quieres dejar este programa? Tu progreso se guarda por si vuelves.');
    if (!ok) return;
    await api.abandon(enrollment.id);
    setEnrollment(null);
    nav.toast('Programa pausado', { icon: '💤' });
    refreshProgramaCache();
  }

  async function handleCompleteToday() {
    if (!enrollment || busy) return;
    setBusy(true);
    const todayContent = (days || []).find(d => api.globalDay(d.week, d.day) === currentDay);
    const res = await api.completeDay(enrollment.id, currentDay, totalDays, todayContent ? todayContent.kind : 'workout');
    setBusy(false);
    if (res && res.error) {
      nav.toast('Error: ' + res.error, { icon: '⚠️' });
      return;
    }
    try { localStorage.setItem(`paufit-prog-last-done-${programaId}`, todayStr); } catch {}
    if (res && res.row) setEnrollment(res.row);
    if (res && res.finished) {
      nav.toast('¡PROGRAMA COMPLETADO! +300 ⭐', { icon: '🏆' });
    } else {
      const pts = todayContent && todayContent.kind !== 'workout' ? 10 : 50;
      nav.toast(`Día ${currentDay} completado · +${pts} ⭐`, { icon: '💪' });
    }
    refreshProgramaCache();
  }

  // Fila de un día de la semana seleccionada
  function DayRow({ d }) {
    const gDay = api ? api.globalDay(d.week, d.day) : (d.week - 1) * 7 + d.day;
    const isDone = completedDays.includes(gDay);
    const isCurrent = enrolled && !programaDone && gDay === currentDay;
    const rutina = d.rutina_id ? rutinas.find(r => r.id === d.rutina_id) : null;
    const isWorkout = d.kind === 'workout';
    const label = isWorkout
      ? (rutina ? rutina.title : (d.title || 'Entreno'))
      : (d.kind === 'active' ? (d.note || 'Descanso activo') : (d.note || 'Descanso'));
    const emoji = isWorkout ? (rutina ? (rutina.emoji || '💪') : '💪') : (d.kind === 'active' ? '🚶‍♀️' : '😴');
    const clickable = isWorkout && rutina;

    return (
      <div
        onClick={() => { if (clickable) nav.go('rutina', rutina.id); }}
        style={{
          display: 'flex', alignItems: 'center', gap: 12,
          padding: '13px 14px', borderRadius: 20,
          background: isCurrent ? T.subtle : T.card,
          border: isCurrent ? `1.5px solid ${T.accent}` : T.border,
          cursor: clickable ? 'pointer' : 'default',
          opacity: !isWorkout && !isCurrent && !isDone ? 0.75 : 1,
        }}
      >
        {/* Círculo estado */}
        <div style={{
          width: 34, height: 34, borderRadius: 999, flexShrink: 0,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          background: isDone ? T.accent : T.subtle,
          color: isDone ? '#fff' : T.text,
          fontSize: isDone ? 15 : 16, fontWeight: 800,
        }}>
          {isDone ? '✓' : emoji}
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 9.5, fontWeight: 800, letterSpacing: 0.8, color: isCurrent ? T.accent : T.muted,  }}>
            Día {d.day}{isCurrent ? ' · HOY TE TOCA' : ''}
          </div>
          <div style={{
            fontSize: 14, fontWeight: 700, color: T.text, marginTop: 2,
            overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
            textDecoration: isDone && isWorkout ? 'line-through' : 'none',
            opacity: isDone ? 0.6 : 1,
          }}>{label}</div>
          {isWorkout && rutina && (
            <div style={{ fontSize: 11, color: T.muted, marginTop: 2 }}>
              {rutina.minutes} min · {rutina.muscle || 'Entreno'}
            </div>
          )}
        </div>
        {clickable && <span style={{ color: T.muted, fontSize: 17 }}>›</span>}
      </div>
    );
  }

  return (
    <div style={{ paddingBottom: 120 }}>
      {/* HERO con portada */}
      <div style={{
        position: 'relative', aspectRatio: '3 / 4',
        background: coverUrl
          ? `url(${coverUrl}) center/cover no-repeat`
          : `linear-gradient(160deg, ${T.accent}, ${T.deep})`,
        overflow: 'hidden',
      }}>
        {!coverUrl && (
          <div style={{ position: 'absolute', top: '34%', left: 0, right: 0, textAlign: 'center', fontSize: 90, opacity: 0.6 }}>
            {programa.emoji || '📅'}
          </div>
        )}
        <div style={{
          position: 'absolute', bottom: 0, left: 0, right: 0, height: '60%',
          background: 'linear-gradient(180deg, transparent 0%, rgba(0,0,0,0.6) 65%, rgba(0,0,0,0.88) 100%)',
          pointerEvents: 'none',
        }}/>
        <div style={{
          position: 'absolute', top: 'calc(env(safe-area-inset-top, 0px) + 16px)', left: 16, right: 16,
          display: 'flex', justifyContent: 'space-between', zIndex: 5,
        }}>
          <button onClick={() => nav.back()} style={{
            width: 36, height: 36, borderRadius: 999, border: 'none',
            background: 'rgba(255,255,255,0.95)', cursor: 'pointer',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            boxShadow: '0 2px 8px rgba(0,0,0,0.2)',
          }}>{Icon.back('#2D2A26')}</button>
          {enrolled && !programaDone && (
            <span style={{
              padding: '6px 12px', borderRadius: 999,
              background: 'rgba(255,255,255,0.95)', color: '#0E0A0C',
              fontSize: 9, fontWeight: 800, letterSpacing: 0.8,
            }}>SEMANA {currentWeek} · DÍA {currentDay}/{totalDays}</span>
          )}
          {programaDone && (
            <span style={{
              padding: '6px 12px', borderRadius: 999,
              background: '#5C7A56', color: '#fff',
              fontSize: 9, fontWeight: 800, letterSpacing: 0.8,
            }}>COMPLETADO 🏆</span>
          )}
        </div>
        <div style={{ position: 'absolute', bottom: 24, left: 22, right: 22, color: '#fff' }}>
          <div style={{ fontSize: 10, fontWeight: 700, letterSpacing: 1.2,  opacity: 0.85 }}>
            Programa · {programa.goal || 'Entrenamiento'}
          </div>
          <div className="pf-display" style={{ fontSize: 30, fontWeight: 800, marginTop: 6, lineHeight: 1.05, letterSpacing: -0.8, textShadow: '0 2px 8px rgba(0,0,0,0.5)' }}>
            {programa.title}
          </div>
          <div style={{ fontSize: 12, marginTop: 8, opacity: 0.92, display: 'flex', gap: 12, flexWrap: 'wrap' }}>
            <span>{programa.weeks} semanas</span>
            <span>· {programa.days_per_week || 5} días/semana</span>
            <span>· {programa.level || 'Todos los niveles'}</span>
          </div>
        </div>
      </div>

      {/* PROGRESO si está inscrita */}
      {enrolled && (
        <div style={{ margin: '18px 20px 0', padding: '16px 18px', background: T.card, border: T.border, borderRadius: 20 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
            <div style={{ fontSize: 12, fontWeight: 700, color: T.text }}>
              {programaDone ? '¡Programa completado! 🏆' : `Semana ${currentWeek} de ${programa.weeks}`}
            </div>
            <div style={{ fontSize: 11, fontWeight: 700, color: T.accent }}>
              {completedDays.length}/{totalDays} días
            </div>
          </div>
          <div style={{ marginTop: 10, height: 8, background: T.subtle, borderRadius: 999, overflow: 'hidden' }}>
            <div style={{
              height: '100%', borderRadius: 999,
              width: `${Math.round((completedDays.length / totalDays) * 100)}%`,
              background: `linear-gradient(90deg, ${T.accent}, ${T.deep})`,
              transition: 'width 400ms ease',
            }}/>
          </div>
        </div>
      )}

      {/* DESCRIPCIÓN */}
      {programa.description && (
        <div style={{ margin: '18px 20px 0', fontSize: 13, color: T.muted, lineHeight: 1.55, fontWeight: 500 }}>
          {programa.description}
        </div>
      )}

      {/* SEMANAS pills */}
      <div style={{ marginTop: 22 }}>
        <div className="pf-display-bold" style={{ padding: '0 20px', fontSize: 16, color: T.text }}>
          Tu plan semana a semana
        </div>
        <div style={{ display: 'flex', gap: 8, padding: '12px 20px 4px', overflowX: 'auto' }} className="hide-scroll">
          {Array.from({ length: programa.weeks }, (_, i) => i + 1).map(w => {
            const active = w === week;
            const weekDone = enrolled && Array.from({ length: 7 }, (_, i) => (w - 1) * 7 + i + 1).every(g => completedDays.includes(g));
            return (
              <button key={w} onClick={() => setSelWeek(w)} style={{
                flexShrink: 0, padding: '9px 16px', borderRadius: 999, cursor: 'pointer',
                border: active ? 'none' : T.border,
                background: active ? T.text : T.card,
                color: active ? T.card : T.text,
                fontSize: 11.5, fontWeight: 800, letterSpacing: 0.3,
                display: 'flex', alignItems: 'center', gap: 6,
              }}>
                Semana {w}{weekDone ? ' ✓' : ''}
              </button>
            );
          })}
        </div>
      </div>

      {/* DÍAS de la semana seleccionada */}
      <div style={{ margin: '10px 20px 0', display: 'flex', flexDirection: 'column', gap: 8 }}>
        {days === null && (
          <div style={{ padding: '30px 0', textAlign: 'center', color: T.muted, fontSize: 13 }}>Cargando…</div>
        )}
        {days !== null && dayRows.length === 0 && (
          <div style={{ padding: '26px 18px', textAlign: 'center', background: T.card, border: T.border, borderRadius: 18, color: T.muted, fontSize: 12.5 }}>
            Esta semana aún no tiene el calendario configurado.
          </div>
        )}
        {dayRows.map(d => <DayRow key={`${d.week}-${d.day}`} d={d}/>)}
      </div>

      {/* CTA principal */}
      <div style={{ margin: '22px 20px 0' }}>
        {!enrolled && !programaDone && (
          <button onClick={handleStart} disabled={busy} style={{
            width: '100%', padding: '16px', border: 'none', borderRadius: 18, cursor: 'pointer',
            background: locked ? '#0E0A0C' : T.accent, color: '#fff',
            fontSize: 14, fontWeight: 800, letterSpacing: 0.4, 
            opacity: busy ? 0.6 : 1,
          }}>
            {locked ? '🔒 Desbloquear con Premium' : busy ? 'Un momento…' : `Empezar programa · ${workoutsInProgram} entrenos`}
          </button>
        )}
        {enrolled && !programaDone && (
          doneToday ? (
            <div style={{
              padding: '16px', borderRadius: 18, textAlign: 'center',
              background: T.subtle, color: T.text, fontSize: 13, fontWeight: 700,
            }}>
              Día {Math.max(...completedDays, 1)} completado ✓ · mañana toca el día {currentDay} 💗
            </div>
          ) : (
            <button onClick={handleCompleteToday} disabled={busy} style={{
              width: '100%', padding: '16px', border: 'none', borderRadius: 18, cursor: 'pointer',
              background: T.accent, color: '#fff',
              fontSize: 14, fontWeight: 800, letterSpacing: 0.4, 
              opacity: busy ? 0.6 : 1,
            }}>
              {busy ? 'Guardando…' : `✓ Marcar día ${currentDay} completado`}
            </button>
          )
        )}
        {enrolled && (
          <button onClick={handleAbandon} style={{
            width: '100%', marginTop: 10, padding: '12px', borderRadius: 14, cursor: 'pointer',
            border: T.border, background: 'transparent', color: T.muted,
            fontSize: 12, fontWeight: 600,
          }}>
            Pausar programa
          </button>
        )}
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Héroe "tu entreno de hoy" para HOME cuando hay programa activo
// ─────────────────────────────────────────────────────────────
function ProgramaTodayHero({ T, nav }) {
  const cache = (typeof window !== 'undefined' && window.__pauCache) || {};
  const enrollment = cache.activePrograma;
  const api = window.PauUserProgramas;
  if (!enrollment || !api) return null;

  const programa = (cache.programas || []).find(p => p.id === enrollment.programa_id);
  if (!programa) return null;

  const days = cache.activeProgramaDays || [];
  const totalDays = (programa.weeks || 4) * 7;
  const completedDays = enrollment.completed_days || [];
  const currentDay = enrollment.current_day || 1;
  const currentWeek = api.weekOf(currentDay);
  const programaDone = completedDays.length >= totalDays;

  const todayStr = new Date().toLocaleDateString('en-CA');
  let lastDoneLocal = null;
  try { lastDoneLocal = localStorage.getItem(`paufit-prog-last-done-${programa.id}`); } catch {}
  const doneToday = lastDoneLocal === todayStr || programaDone;

  const todayContent = days.find(d => api.globalDay(d.week, d.day) === currentDay);
  const rutina = todayContent && todayContent.rutina_id
    ? (cache.rutinas || []).find(r => r.id === todayContent.rutina_id)
    : null;
  const isWorkout = todayContent && todayContent.kind === 'workout';
  const restLabel = todayContent && todayContent.kind === 'active'
    ? (todayContent.note || 'Descanso activo 🚶‍♀️')
    : ((todayContent && todayContent.note) || 'Día de descanso 💤');

  const coverUrl = programaCoverUrl(programa);
  const streak = (cache.stats && cache.stats.streak) || 0;

  return (
    <div onClick={() => nav.go('programa', programa.id)} style={{
      margin: '16px 20px 0', cursor: 'pointer',
      borderRadius: 28, position: 'relative', overflow: 'hidden',
      aspectRatio: '3 / 4',
      background: coverUrl ? '#000' : `linear-gradient(160deg, ${T.accent}, ${T.deep})`,
      boxShadow: '0 16px 36px rgba(0,0,0,0.15), 0 6px 16px rgba(0,0,0,0.08)',
    }}>
      {coverUrl && (
        <img loading="lazy" src={coverUrl} alt={programa.title}
          style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover' }}/>
      )}
      <div style={{
        position: 'absolute', inset: 0,
        background: 'linear-gradient(180deg, rgba(0,0,0,0.4) 0%, transparent 30%, transparent 55%, rgba(0,0,0,0.85) 100%)',
      }}/>

      {/* Top row: racha + estado */}
      <div style={{
        position: 'absolute', top: 14, left: 14, right: 14,
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      }}>
        <div style={{
          padding: '6px 12px', borderRadius: 999,
          background: 'rgba(0,0,0,0.55)', backdropFilter: 'blur(10px)',
          color: '#fff', fontSize: 11, fontWeight: 700,
          display: 'inline-flex', alignItems: 'center', gap: 6,
        }}>
          <span style={{ fontSize: 13 }}>🔥</span>
          {streak} {streak === 1 ? 'día' : 'días'} de racha
        </div>
        <div style={{
          padding: '5px 10px', borderRadius: 6,
          background: 'rgba(255,255,255,0.95)', backdropFilter: 'blur(10px)',
          color: '#0E0A0C', fontSize: 9, fontWeight: 700, letterSpacing: 1.2,
        }}>
          {programaDone ? 'PROGRAMA COMPLETADO 🏆' : `SEMANA ${currentWeek} · DÍA ${currentDay}/${totalDays}`}
        </div>
      </div>

      {/* Bottom info */}
      <div style={{ position: 'absolute', bottom: 16, left: 18, right: 18, color: '#fff' }}>
        <div style={{ fontSize: 10, fontWeight: 500, letterSpacing: 1.2,  color: 'rgba(255,255,255,0.85)' }}>
          {programa.title}
        </div>

        {programaDone ? (
          <>
            <div className="pf-display" style={{ fontSize: 26, fontWeight: 500, marginTop: 4, letterSpacing: -0.5, lineHeight: 1.1, textShadow: '0 2px 12px rgba(0,0,0,0.4)' }}>
              ¡Programa completado! 🏆
            </div>
            <div style={{ fontSize: 12, color: 'rgba(255,255,255,0.9)', marginTop: 6 }}>
              {programa.weeks} semanas terminadas. Eres imparable 💗
            </div>
          </>
        ) : doneToday ? (
          <>
            <div className="pf-display" style={{ fontSize: 24, fontWeight: 500, marginTop: 4, letterSpacing: -0.5, lineHeight: 1.15, textShadow: '0 2px 12px rgba(0,0,0,0.4)' }}>
              Día completado ✓
            </div>
            <div style={{ fontSize: 12, color: 'rgba(255,255,255,0.9)', marginTop: 6 }}>
              Mañana toca el día {currentDay} 💗
            </div>
          </>
        ) : (
          <>
            <div className="pf-display" style={{ fontSize: 28, fontWeight: 500, marginTop: 4, letterSpacing: -0.6, lineHeight: 1.05, textShadow: '0 2px 12px rgba(0,0,0,0.4)' }}>
              {isWorkout ? (rutina ? rutina.title : (todayContent && todayContent.title) || 'Tu entreno de hoy') : restLabel}
            </div>
            {isWorkout && rutina && (
              <div style={{
                marginTop: 10, display: 'flex', alignItems: 'center', gap: 14,
                fontSize: 11, fontWeight: 500, color: 'rgba(255,255,255,0.95)', whiteSpace: 'nowrap',
              }}>
                <span style={{ display: 'flex', alignItems: 'center', gap: 5 }}>
                  {Icon.clock({ c: '#fff', size: 13 })} {rutina.minutes} min
                </span>
                <span>💪 {rutina.muscle || 'Entreno'}</span>
                <span>· {rutina.level || 'Medio'}</span>
              </div>
            )}
            <button onClick={(e) => {
              e.stopPropagation();
              if (isWorkout && rutina) nav.go('rutina', rutina.id);
              else nav.go('programa', programa.id);
            }} style={{
              marginTop: 14, width: '100%', padding: '14px',
              border: 'none', borderRadius: 20, cursor: 'pointer',
              background: '#fff', color: '#0E0A0C',
              fontSize: 13, fontWeight: 600, letterSpacing: 0.3, 
              display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
            }}>
              {isWorkout
                ? <>{Icon.playFilled({ c: '#0E0A0C', size: 11 })} Empezar entreno</>
                : 'Ver mi programa →'}
            </button>
          </>
        )}
      </div>
    </div>
  );
}

// Exportar a window (cada archivo Babel vive en su propio scope)
Object.assign(window, { ProgramasSection, ProgramaDetailScreen, ProgramaTodayHero, programaCoverUrl, refreshProgramaCache });
