// Atlas Method — Home Personalization Card
// A compact, single-row card that surfaces relevant context above the hero.
// Never replaces the landing — only complements it.

const OBJ_LABEL_SHORT = {
  muscle:      'Hipertrofia',
  fat_loss:    'Perder grasa',
  recomp:      'Recomposición',
  performance: 'Rendimiento',
  health:      'Salud',
};

function daysAgo(ts) {
  const d = Math.floor((Date.now() - ts) / 86400000);
  if (d === 0) return 'Hoy';
  if (d === 1) return 'Ayer';
  return `Hace ${d} días`;
}

// ─── Pill button ───────────────────────────────────────────────────────────────
function CtxPill({ label, onClick, primary }) {
  return (
    <button
      onClick={onClick}
      style={{
        padding: '6px 14px', borderRadius: 999, cursor: 'pointer',
        border: primary ? 'none' : '1px solid rgba(15,26,46,0.12)',
        background: primary ? '#0F1A2E' : 'transparent',
        color: primary ? '#FAFAF7' : '#3A4257',
        fontFamily: '"Inter",system-ui', fontSize: 12, fontWeight: 700,
        letterSpacing: -0.1, whiteSpace: 'nowrap',
        transition: 'background .14s, border-color .14s',
      }}
    >
      {label}
    </button>
  );
}

// ─── Separator dot ─────────────────────────────────────────────────────────────
function Dot() {
  return <span style={{ width: 3, height: 3, borderRadius: '50%', background: 'rgba(15,26,46,0.2)', display: 'inline-block', flexShrink: 0 }} />;
}

// ─── Card variants ─────────────────────────────────────────────────────────────

function CardNew({ navigate }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 14, flexWrap: 'wrap' }}>
      <span style={{
        fontFamily: '"Inter",system-ui', fontSize: 13, fontWeight: 700,
        color: '#0F1A2E', letterSpacing: -0.2, whiteSpace: 'nowrap',
      }}>
        Empieza con Atlas
      </span>
      <Dot />
      <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
        <CtxPill label="Hablar con Coach →" onClick={() => navigate('/coach')} primary />
        <CtxPill label="Crear rutina"        onClick={() => navigate('/builder')} />
        <CtxPill label="Mis rutinas"         onClick={() => navigate('/rutinas')} />
        <CtxPill label="Explorar Aula"       onClick={() => navigate('/aula')} />
      </div>
    </div>
  );
}

function CardSession({ session, userName, profile, navigate }) {
  const when    = daysAgo(session.dateTs || Date.now());
  const sesName = session.name || 'Sesión anterior';
  const obj     = profile?.objective ? OBJ_LABEL_SHORT[profile.objective] : null;

  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 14, flexWrap: 'wrap' }}>
      <span style={{ fontFamily: '"Inter",system-ui', fontSize: 13, fontWeight: 700, color: '#0F1A2E', letterSpacing: -0.2, whiteSpace: 'nowrap' }}>
        Hola, {userName}
      </span>
      {obj && (
        <>
          <Dot />
          <span style={{ fontFamily: '"Inter",system-ui', fontSize: 12, color: '#5C6477', whiteSpace: 'nowrap' }}>
            {obj}
          </span>
        </>
      )}
      <Dot />
      <span style={{ fontFamily: '"Inter",system-ui', fontSize: 12, color: '#5C6477', whiteSpace: 'nowrap' }}>
        Última sesión: <strong style={{ color: '#0F1A2E', fontWeight: 700 }}>{sesName}</strong> · {when}
      </span>
      <CtxPill label="Reanudar →" onClick={() => navigate('/builder')} primary />
    </div>
  );
}

function CardPlan({ plan, navigate }) {
  const name = plan?.split?.name || plan?.name || 'Plan recomendado';
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 14, flexWrap: 'wrap' }}>
      <span style={{ fontFamily: '"Inter",system-ui', fontSize: 13, fontWeight: 700, color: '#0F1A2E', letterSpacing: -0.2, whiteSpace: 'nowrap' }}>
        Plan recomendado
      </span>
      <Dot />
      <span style={{ fontFamily: '"Inter",system-ui', fontSize: 12, color: '#5C6477', whiteSpace: 'nowrap' }}>
        {String(name)}
      </span>
      <CtxPill label="Ver recomendación →" onClick={() => navigate('/coach')} primary />
    </div>
  );
}

function CardProfile({ profile, userName, navigate }) {
  const obj = profile?.objective ? OBJ_LABEL_SHORT[profile.objective] : null;
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 14, flexWrap: 'wrap' }}>
      <span style={{ fontFamily: '"Inter",system-ui', fontSize: 13, fontWeight: 700, color: '#0F1A2E', letterSpacing: -0.2, whiteSpace: 'nowrap' }}>
        Hola, {userName}
      </span>
      {obj && (
        <>
          <Dot />
          <span style={{ fontFamily: '"Inter",system-ui', fontSize: 12, color: '#5C6477', whiteSpace: 'nowrap' }}>
            Objetivo: <strong style={{ color: '#0F1A2E', fontWeight: 700 }}>{obj}</strong>
          </span>
        </>
      )}
      <Dot />
      <CtxPill label="Hablar con Coach →" onClick={() => navigate('/coach')} primary />
      <CtxPill label="Ir al Builder"       onClick={() => navigate('/builder')} />
    </div>
  );
}

function CardRoutine({ routine, navigate }) {
  const name = routine.name || 'Rutina activa';
  const sessions = Array.isArray(routine.sessions) ? routine.sessions : [];
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 14, flexWrap: 'wrap' }}>
      <span style={{ fontFamily: '"Inter",system-ui', fontSize: 13, fontWeight: 700, color: '#0F1A2E', letterSpacing: -0.2, whiteSpace: 'nowrap' }}>
        Mi rutina
      </span>
      <Dot />
      <span style={{ fontFamily: '"Inter",system-ui', fontSize: 12, color: '#5C6477', whiteSpace: 'nowrap' }}>
        {name} · {sessions.length} día{sessions.length !== 1 ? 's' : ''}
      </span>
      <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
        {sessions.slice(0, 4).map((s, i) => (
          <CtxPill key={i} label={s.name || `Día ${i+1}`} onClick={() => {
            localStorage.setItem('atlas.pendingWorkout', JSON.stringify(s.exercises || []));
            try { localStorage.setItem('atlas.pendingWorkoutMeta', JSON.stringify({ routineName: name, sessionName: s.name, sessionIndex: i, totalSessions: sessions.length, mode: 'player' })); } catch {}
            navigate('/player');
          }} />
        ))}
        <CtxPill label="Mis rutinas →" onClick={() => navigate('/rutinas')} primary />
      </div>
    </div>
  );
}

// ─── Workout-in-progress banner ──────────────────────────────────────────────
// Surfaces a paused/active training session so it's never forgotten. One tap
// resumes the immersive player at the exact point (persistence already exists).
function WorkoutInProgressBanner() {
  const { navigate } = useRoute();
  const active = React.useMemo(() => {
    try { return (typeof WorkoutSessionStore !== 'undefined') ? WorkoutSessionStore.getActive() : null; }
    catch { return null; }
  }, []);
  if (!active) return null;

  const done  = (active.exercises || []).reduce((t, e) => t + (e.sets || []).filter(s => s.done).length, 0);
  const total = (active.exercises || []).reduce((t, e) => t + (e.sets || []).length, 0);
  const label = active.sessionName || active.routineName || 'Entrenamiento';

  return (
    <div style={{ padding: '12px 16px 0' }}>
      <div style={{ maxWidth: 1200, margin: '0 auto' }}>
        <button onClick={() => navigate('/player')} aria-label="Reanudar entrenamiento en curso"
          style={{ width:'100%', display:'flex', alignItems:'center', gap:14, cursor:'pointer', textAlign:'left',
            padding:'13px 16px', borderRadius:14, border:'1px solid rgba(34,197,94,0.35)',
            background:'linear-gradient(135deg, #0F1A2E, #16233D)', color:'#FAFAF7',
            boxShadow:'0 8px 28px -10px rgba(34,197,94,0.45)', animation:'fadeIn 0.3s ease' }}>
          <span style={{ position:'relative', width:10, height:10, flexShrink:0 }}>
            <span style={{ position:'absolute', inset:0, borderRadius:'50%', background:'#22C55E' }} />
            <span style={{ position:'absolute', inset:-4, borderRadius:'50%', border:'2px solid rgba(34,197,94,0.5)', animation:'wpPulse 1.6s ease-out infinite' }} />
          </span>
          <span style={{ flex:1, minWidth:0 }}>
            <span style={{ display:'block', fontFamily:'"Inter",system-ui', fontSize:10, fontWeight:800, letterSpacing:1.2, color:'#7EE2A8' }}>ENTRENAMIENTO EN CURSO</span>
            <span style={{ display:'block', fontFamily:'"Inter",system-ui', fontSize:15, fontWeight:800, letterSpacing:-0.3, overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>
              {label}{total > 0 ? ` · ${done}/${total} series` : ''}
            </span>
          </span>
          <span style={{ flexShrink:0, fontFamily:'"Inter",system-ui', fontSize:13, fontWeight:800, color:'#22C55E' }}>Reanudar →</span>
        </button>
      </div>
    </div>
  );
}

// ─── Preset routines entry (Inicio) ──────────────────────────────────────────
function PresetRoutinesEntry({ mobile }) {
  const { navigate } = useRoute();
  return (
    <div style={{ padding: mobile ? 0 : '12px 48px 0' }}>
      <div style={{ maxWidth: mobile ? '100%' : 1200, margin: '0 auto' }}>
        <button onClick={() => navigate('/plantillas')} aria-label="Rutinas predeterminadas"
          style={{ display:'flex', alignItems:'center', gap:14, width:'100%', textAlign:'left', cursor:'pointer',
            padding:'14px 16px', borderRadius:16, border:'1px solid rgba(59,130,246,0.28)',
            background:'linear-gradient(135deg, #0f2744, #1d3a6b)', color:'#FAFAF7',
            boxShadow:'0 8px 28px -12px rgba(59,130,246,0.45)', animation:'fadeIn 0.3s ease' }}>
          <span style={{ fontSize:26, flexShrink:0 }}>🧬</span>
          <span style={{ flex:1, minWidth:0 }}>
            <span style={{ display:'block', fontFamily:'"Inter",system-ui', fontSize:10, fontWeight:800, letterSpacing:1.2, color:'#93C5FD' }}>BASADAS EN CIENCIA</span>
            <span style={{ display:'block', fontFamily:'"Inter",system-ui', fontSize:15.5, fontWeight:800, letterSpacing:-0.3 }}>Rutinas predeterminadas</span>
          </span>
          <span style={{ flexShrink:0, fontFamily:'"Inter",system-ui', fontSize:13, fontWeight:800, color:'#3B82F6' }}>Ver →</span>
        </button>
      </div>
    </div>
  );
}

// ─── Main component ────────────────────────────────────────────────────────────
function HomeContextCard() {
  const { state } = useStore();
  const { navigate } = useRoute();

  const profile = React.useMemo(() => {
    try { return JSON.parse(localStorage.getItem('atlas.profile.v1') || 'null'); } catch { return null; }
  }, []);

  const activeRoutine = React.useMemo(() => {
    try { return JSON.parse(localStorage.getItem('atlas.routine.active.v1') || 'null'); } catch { return null; }
  }, []);

  const lastSession = (state.log || [])[0] || null;
  const coachPlan   = state.plan || null;
  const hasProfile  = !!(profile?.objective);
  const userName    = state.user?.name || 'Atleta';

  // Pick the highest-priority variant
  let content;
  if (activeRoutine && Array.isArray(activeRoutine.sessions) && activeRoutine.sessions.length) {
    content = <CardRoutine routine={activeRoutine} navigate={navigate} />;
  } else if (lastSession) {
    content = <CardSession session={lastSession} userName={userName} profile={profile} navigate={navigate} />;
  } else if (coachPlan) {
    content = <CardPlan plan={coachPlan} navigate={navigate} />;
  } else if (hasProfile) {
    content = <CardProfile profile={profile} userName={userName} navigate={navigate} />;
  } else {
    content = <CardNew navigate={navigate} />;
  }

  return (
    <div style={{ padding: '16px 48px 0', background: 'transparent' }}>
      <div style={{ maxWidth: 1200, margin: '0 auto' }}>
        <div style={{
          display: 'flex', alignItems: 'center',
          background: '#FFFFFF',
          border: '1px solid rgba(15,26,46,0.07)',
          borderRadius: 14,
          padding: '11px 20px',
          boxShadow: '0 1px 3px rgba(15,26,46,0.04), 0 4px 16px -6px rgba(15,26,46,0.07)',
          animation: 'fadeIn 0.3s ease',
        }}>
          {/* Atlas monogram */}
          <div style={{
            width: 22, height: 22, borderRadius: 6, flexShrink: 0,
            background: '#0F1A2E',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            marginRight: 14,
          }}>
            <AtlasA size={13} color="#FAFAF7" stroke={10} />
          </div>

          {content}
        </div>
      </div>
    </div>
  );
}

// ─── Return-to-habit card ────────────────────────────────────────────────────
// Shown on Inicio when it's been 3+ days since the last recorded session.
// Warm, never guilt-tripping. Dismissable — hidden for another 3 days if closed.
const HABIT_DISMISS_KEY = 'atlas.habit.dismissedAt';

function ReturnToHabitCard({ navigate, compact }) {
  const { state } = useStore();
  const last = (state.log || [])[0] || null;
  const [hidden, setHidden] = React.useState(false);

  const days = last?.dateTs ? Math.floor((Date.now() - last.dateTs) / 86400000) : null;
  const dismissedAt = React.useMemo(() => {
    try { return Number(localStorage.getItem(HABIT_DISMISS_KEY) || 0); } catch { return 0; }
  }, []);
  const recentlyDismissed = dismissedAt && (Date.now() - dismissedAt) < 3 * 86400000;

  if (hidden || days === null || days < 3 || recentlyDismissed) return null;

  const activeRoutine = (() => { try { return JSON.parse(localStorage.getItem('atlas.routine.active.v1') || 'null'); } catch { return null; } })();
  const hasRoutine = activeRoutine && Array.isArray(activeRoutine.sessions) && activeRoutine.sessions.length;

  // "el martes" within a week, otherwise "hace N días"
  let when;
  try {
    when = days <= 7
      ? `el ${new Date(last.dateTs).toLocaleDateString('es-ES', { weekday: 'long' })}`
      : `hace ${days} días`;
  } catch { when = `hace ${days} días`; }

  function dismiss() {
    try { localStorage.setItem(HABIT_DISMISS_KEY, String(Date.now())); } catch {}
    setHidden(true);
  }
  function go() {
    if (hasRoutine) { navigate('/rutinas'); }
    else { navigate('/coach'); }
  }

  return (
    <div style={{ position:'relative', background:'linear-gradient(135deg, #12203A 0%, #0F1A2E 100%)', borderRadius:16, border:'1px solid rgba(59,130,246,0.22)', padding: compact ? '16px 18px' : '18px 20px', boxShadow:'0 6px 24px -12px rgba(15,26,46,0.5)' }}>
      <button onClick={dismiss} aria-label="Descartar" style={{ position:'absolute', top:10, right:12, width:30, height:30, borderRadius:8, border:'none', background:'transparent', color:'rgba(250,250,247,0.35)', fontSize:15, cursor:'pointer' }}>✕</button>
      <div style={{ display:'inline-flex', alignItems:'center', gap:7, marginBottom:10, padding:'3px 10px', borderRadius:999, background:'rgba(59,130,246,0.12)', border:'1px solid rgba(59,130,246,0.22)' }}>
        <span style={{ width:5, height:5, borderRadius:'50%', background:'#3B82F6' }} />
        <span style={{ fontFamily:'ui-monospace,Menlo,monospace', fontSize:9, fontWeight:700, color:'#93C5FD', letterSpacing:1.2 }}>DE VUELTA</span>
      </div>
      <div style={{ fontFamily:'"Inter",system-ui', fontSize:'clamp(16px,4.4vw,18px)', fontWeight:800, color:'#F0F3FA', letterSpacing:-0.3, marginRight:28 }}>
        Tu última sesión fue {when}.
      </div>
      <div style={{ fontFamily:'"Inter",system-ui', fontSize:14, color:'rgba(240,243,250,0.6)', lineHeight:1.5, margin:'6px 0 14px' }}>
        Cada vuelta cuenta más que cualquier racha. ¿Retomamos hoy?
      </div>
      <button onClick={go} style={{ width: compact ? 'auto' : '100%', minHeight:46, padding:'0 18px', borderRadius:11, border:'none', cursor:'pointer', background:'#2563EB', color:'#fff', fontFamily:'"Inter",system-ui', fontSize:14, fontWeight:700 }}>
        {hasRoutine ? 'Ir a Mi rutina →' : 'Hablar con el Coach →'}
      </button>
    </div>
  );
}

// ─── Mobile Inicio dashboard ─────────────────────────────────────────────────
// One-column, utility-ordered: next workout / my routine → streak + recent
// sessions → Aula. Progreso and Aula live here since they're not in the tab bar.
function MdCard({ children, pad = 16 }) {
  return (
    <div style={{ background: '#FFFFFF', border: '1px solid rgba(15,26,46,0.08)', borderRadius: 16,
      padding: pad, boxShadow: '0 1px 3px rgba(15,26,46,0.04), 0 6px 20px -10px rgba(15,26,46,0.10)' }}>
      {children}
    </div>
  );
}
function MdLabel({ children }) {
  return <div style={{ fontFamily:'ui-monospace,Menlo,monospace', fontSize:10, fontWeight:700, color:'#6B7280', letterSpacing:1.2, marginBottom:10, textTransform:'uppercase' }}>{children}</div>;
}
function MdAction({ label, onClick, primary, green, full }) {
  return (
    <button onClick={onClick} style={{
      width: full ? '100%' : undefined, minHeight: 46, padding: '0 16px', borderRadius: 11, cursor: 'pointer',
      border: primary || green ? 'none' : '1px solid rgba(15,26,46,0.14)',
      background: green ? '#16A34A' : primary ? '#0F1A2E' : '#FFFFFF',
      color: primary || green ? '#FFFFFF' : '#0F1A2E',
      fontFamily: '"Inter",system-ui', fontSize: 14, fontWeight: 700, letterSpacing: -0.1,
    }}>{label}</button>
  );
}

// ── One of the three clear "paths" offered on Inicio ──────────────────────────
function HomePathCard({ emoji, title, desc, onClick }) {
  const [hover, setHover] = React.useState(false);
  return (
    <button onClick={onClick} onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
      style={{ display:'flex', alignItems:'center', gap:14, width:'100%', height:'100%', textAlign:'left', cursor:'pointer',
        padding:'15px 16px', borderRadius:16, border:'1px solid rgba(15,26,46,0.09)', background:'#FFFFFF', color:'#0F1A2E',
        boxShadow: hover ? '0 12px 30px -14px rgba(15,26,46,0.20)' : '0 1px 3px rgba(15,26,46,0.04)',
        transform: hover ? 'translateY(-2px)' : 'translateY(0)', transition:'all .2s cubic-bezier(.2,.8,.2,1)' }}>
      <span style={{ fontSize:26, flexShrink:0, lineHeight:1 }}>{emoji}</span>
      <span style={{ flex:1, minWidth:0 }}>
        <span style={{ display:'block', fontFamily:'"Inter",system-ui', fontSize:15.5, fontWeight:800, letterSpacing:-0.3 }}>{title}</span>
        <span style={{ display:'block', fontFamily:'"Inter",system-ui', fontSize:12.5, color:'#5C6477', marginTop:3, lineHeight:1.45 }}>{desc}</span>
      </span>
      <span style={{ flexShrink:0, fontSize:18, fontWeight:700, color:'#B7BECC' }}>→</span>
    </button>
  );
}

// ── Featured carousel ─────────────────────────────────────────────────────────
// Fills the empty desktop space below the paths with a rotating, hand-navigable
// deck of REAL content: featured preset routines, the newest Aula article, a
// Builder shortcut, the user's next workout / activity / saved routines. Slides
// are built from live data, so new articles or routines surface here automatically.

// One category → an accent gradient for slides without their own photo.
const HF_GRAD = {
  builder:  ['#0f2744', '#2a6fdb'],
  article:  ['#120a2e', '#6d28d9'],
  next:     ['#08351f', '#16a34a'],
  activity: ['#0F1A2E', '#1a4fa0'],
  routines: ['#091a09', '#177a2e'],
};

// La portada del artículo destacado se lee de la ÚNICA fuente de verdad de las
// portadas del Aula (window.AULA_PHOTOS): misma categoría → misma imagen que en
// el Aula. Si la categoría no tiene foto, el slide muestra su degradado.
function hfArticlePhoto(category) {
  try { return (window.AULA_PHOTOS || {})[category] || null; } catch (e) { return null; }
}

function homeBuildSlides({ presets, articles, state, activeRoutine, navigate }) {
  const slides = [];
  const savedRoutines = state.savedRoutines || [];
  const log = state.log || [];
  const hasRoutine = activeRoutine && Array.isArray(activeRoutine.sessions) && activeRoutine.sessions.length;

  // Next workout — top priority when the user has an active routine.
  if (hasRoutine) {
    slides.push({ key:'next', kind:'next', icon:'▶', grad:HF_GRAD.next, badge:'Continúa',
      title: activeRoutine.name || 'Tu rutina', subtitle:`${activeRoutine.sessions.length} ${activeRoutine.sessions.length===1?'sesión':'sesiones'} · listo para entrenar`,
      cta:'Entrenar →', onClick:() => navigate('/rutinas') });
  }
  // Newest published Aula article (marked "Nuevo" when recent).
  const art = (articles || [])[0];
  if (art) {
    const isNew = window.ArticlesService && window.ArticlesService.isNew ? window.ArticlesService.isNew(art) : false;
    slides.push({ key:'art-'+art.id, kind:'article', icon:'📖', grad:HF_GRAD.article, badge: isNew ? 'Nuevo' : 'Aula', isNew,
      image: art.coverImage || hfArticlePhoto(art.category),
      title: art.title, subtitle:`${art.readTime || 6} min de lectura${art.subtitle ? ' · '+art.subtitle : ''}`,
      cta:'Leer en el Aula →', onClick:() => navigate('/aula') });
  }
  // Featured preset routines — multi-day splits first, then the rest.
  const order = ['preset-ppl-avanzado','preset-fullbody-principiante','preset-upperlower-intermedio'];
  const featured = [...(presets || [])].sort((a,b) => {
    const ia = order.indexOf(a.id), ib = order.indexOf(b.id);
    return (ia<0?99:ia) - (ib<0?99:ib);
  }).slice(0, 3);
  featured.forEach(pr => {
    const days = Array.isArray(pr.days) ? pr.days.length : 0;
    slides.push({ key:'pr-'+pr.id, kind:'preset', icon:'🗂️', image:pr.image, grad:[pr.accent?.from||'#0f2744', pr.accent?.to||'#2a6fdb'],
      badge: days>1 ? `${days} días` : (pr.objective || 'Rutina'),
      title: pr.name, subtitle: pr.subtitle || '',
      cta:'Ver rutina →', onClick:() => { try { localStorage.setItem('atlas.preset.open', pr.id); } catch {} navigate('/plantillas'); } });
  });
  // Builder shortcut — always available.
  slides.push({ key:'builder', kind:'builder', icon:'🛠️', grad:HF_GRAD.builder, badge:'Builder',
    title:'Crea tu rutina', subtitle:'Constrúyela ejercicio a ejercicio, con la ciencia detrás',
    cta:'Abrir Builder →', onClick:() => navigate('/builder') });
  // The user's own routines, if any.
  if (savedRoutines.length) {
    slides.push({ key:'routines', kind:'routines', icon:'📁', grad:HF_GRAD.routines, badge:'Tuyas',
      title:'Mis rutinas', subtitle:`${savedRoutines.length} ${savedRoutines.length===1?'rutina guardada':'rutinas guardadas'}`,
      cta:'Abrir →', onClick:() => navigate('/rutinas') });
  }
  // A nudge back to progress when there's history.
  if (log.length) {
    const aw = (typeof computeActiveWeeks === 'function') ? computeActiveWeeks(log).streak : 0;
    slides.push({ key:'activity', kind:'activity', icon:'📈', grad:HF_GRAD.activity, badge:'Tu progreso',
      title:'Revisa tu progreso', subtitle:`${state.sessions?.completed||log.length} sesiones${aw ? ' · '+aw+(aw===1?' semana activa':' semanas activas') : ''}`,
      cta:'Ver progreso →', onClick:() => navigate('/progreso') });
  }
  return slides;
}

function HomeFeatSlide({ slide, isMobile, height }) {
  const [imgOk, setImgOk] = React.useState(true);
  const showImg = slide.image && imgOk;
  const [from, to] = slide.grad || ['#0f2744', '#2a6fdb'];
  return (
    <button onClick={slide.onClick}
      style={{ position:'relative', flex:'0 0 100%', width:'100%', height, borderRadius:20, overflow:'hidden', cursor:'pointer',
        border:'none', padding:0, textAlign:'left', display:'block',
        background:`linear-gradient(135deg, ${from}, ${to})` }}>
      {showImg && (
        <img src={slide.image} alt="" loading="lazy" draggable={false} onError={() => setImgOk(false)}
          style={{ position:'absolute', inset:0, width:'100%', height:'100%', objectFit:'cover', display:'block' }} />
      )}
      {!showImg && (
        <span style={{ position:'absolute', right: isMobile ? -6 : 12, bottom: isMobile ? -14 : -18, fontSize: isMobile ? 96 : 168, opacity:0.16, lineHeight:1, pointerEvents:'none' }}>{slide.icon}</span>
      )}
      {/* Legibility gradient */}
      <div style={{ position:'absolute', inset:0, background:'linear-gradient(to top, rgba(6,13,24,0.82), rgba(6,13,24,0.28) 55%, rgba(6,13,24,0.08) 100%)' }} />
      {/* Content */}
      <div style={{ position:'absolute', left:0, right:0, bottom:0, padding: isMobile ? '16px 18px' : '26px 30px' }}>
        <span style={{ display:'inline-flex', alignItems:'center', gap:6, fontFamily:'ui-monospace,Menlo,monospace', fontSize:10, fontWeight:800, letterSpacing:1,
          color:'#fff', background: slide.isNew ? 'rgba(34,197,94,0.92)' : 'rgba(255,255,255,0.18)', backdropFilter:'blur(6px)', borderRadius:999, padding:'4px 10px', textTransform:'uppercase' }}>
          {slide.badge}
        </span>
        <div style={{ fontFamily:'"Inter",system-ui', fontSize: isMobile ? 20 : 30, fontWeight:800, color:'#fff', letterSpacing:-0.6, lineHeight:1.1, margin: isMobile ? '9px 0 3px' : '12px 0 4px',
          display:'-webkit-box', WebkitLineClamp:2, WebkitBoxOrient:'vertical', overflow:'hidden' }}>
          {slide.title}
        </div>
        <div style={{ fontFamily:'"Inter",system-ui', fontSize: isMobile ? 12.5 : 14.5, color:'rgba(255,255,255,0.82)', lineHeight:1.4,
          display:'-webkit-box', WebkitLineClamp: isMobile ? 1 : 2, WebkitBoxOrient:'vertical', overflow:'hidden' }}>
          {slide.subtitle}
        </div>
        <span style={{ display:'inline-block', marginTop: isMobile ? 10 : 14, fontFamily:'"Inter",system-ui', fontSize: isMobile ? 13 : 14, fontWeight:800,
          color:'#0F1A2E', background:'#fff', borderRadius:11, padding: isMobile ? '8px 14px' : '10px 18px' }}>
          {slide.cta}
        </span>
      </div>
    </button>
  );
}

// Featured deck on Inicio. Native horizontal scroll (scroll-snap) so a finger
// swipe on mobile and a mouse drag on desktop both work, without blocking the
// page's vertical scroll (a mostly-vertical gesture keeps scrolling the page).
// Auto-advances every ~5s in a loop; pauses on interaction/hover, when the
// carousel is off-screen or the tab is backgrounded, and under reduced-motion.
function HomeFeaturedCarousel({ slides, isMobile }) {
  const trackRef = React.useRef(null);
  const n = slides.length;
  const height = isMobile ? 188 : 360;
  const reduce = React.useMemo(() => { try { return window.matchMedia('(prefers-reduced-motion: reduce)').matches; } catch { return false; } }, []);
  const [idx, setIdx] = React.useState(0);

  // Autoplay gating — refs so the interval reads fresh values without resetting.
  const interacting = React.useRef(false); // recent touch/drag/arrow/dot action
  const hovering    = React.useRef(false);
  const visible     = React.useRef(true);
  const resumeT     = React.useRef(null);

  const scrollToIdx = React.useCallback((i, smooth = true) => {
    const el = trackRef.current; if (!el) return;
    el.scrollTo({ left: i * el.clientWidth, behavior: smooth && !reduce ? 'smooth' : 'auto' });
  }, [reduce]);

  // Active-dot tracking from the real scroll position.
  const onScroll = React.useCallback(() => {
    const el = trackRef.current; if (!el || !el.clientWidth) return;
    const i = Math.round(el.scrollLeft / el.clientWidth);
    setIdx(prev => (prev === i ? prev : Math.max(0, Math.min(i, n - 1))));
  }, [n]);

  // Interaction → pause autoplay now, resume after a few quiet seconds.
  const bump = React.useCallback(() => {
    interacting.current = true;
    if (resumeT.current) clearTimeout(resumeT.current);
    resumeT.current = setTimeout(() => { interacting.current = false; }, 6000);
  }, []);

  // Autoplay loop.
  React.useEffect(() => {
    if (reduce || n < 2) return;
    const t = setInterval(() => {
      if (interacting.current || hovering.current || !visible.current || document.hidden) return;
      const el = trackRef.current; if (!el || !el.clientWidth) return;
      const cur = Math.round(el.scrollLeft / el.clientWidth);
      el.scrollTo({ left: ((cur + 1) % n) * el.clientWidth, behavior: 'smooth' });
    }, 5000);
    return () => clearInterval(t);
  }, [reduce, n]);

  // Pause when the carousel scrolls out of view.
  React.useEffect(() => {
    const el = trackRef.current; if (!el) return;
    let io;
    try { io = new IntersectionObserver(([e]) => { visible.current = e.isIntersecting; }, { threshold: 0.4 }); io.observe(el); } catch {}
    return () => { if (io) io.disconnect(); };
  }, []);

  // Keep the index valid and the scroll pinned to start as data loads in.
  React.useEffect(() => { if (idx > n - 1) { setIdx(0); scrollToIdx(0, false); } }, [n]);

  // Desktop click-drag to scroll; suppress the slide's click after a real drag.
  const drag = React.useRef({ active:false, startX:0, startScroll:0, moved:false });
  const suppressClick = React.useRef(false);
  const onPointerDown = (e) => {
    bump();
    if (!isMobile && e.pointerType === 'mouse' && e.button === 0 && trackRef.current) {
      drag.current = { active:true, startX:e.clientX, startScroll:trackRef.current.scrollLeft, moved:false };
    }
  };
  const onPointerMove = (e) => {
    const d = drag.current; if (!d.active) return;
    const dx = e.clientX - d.startX;
    if (Math.abs(dx) > 4) d.moved = true;
    trackRef.current.scrollLeft = d.startScroll - dx;
  };
  const endDrag = () => {
    const el = trackRef.current;
    if (drag.current.active && drag.current.moved && el) {
      suppressClick.current = true;
      el.scrollTo({ left: Math.round(el.scrollLeft / el.clientWidth) * el.clientWidth, behavior: reduce ? 'auto' : 'smooth' });
    }
    drag.current.active = false;
  };
  const onClickCapture = (e) => { if (suppressClick.current) { e.stopPropagation(); e.preventDefault(); suppressClick.current = false; } };

  if (!n) return null;
  const go = (d) => { bump(); const el = trackRef.current; if (!el) return; const cur = Math.round(el.scrollLeft / el.clientWidth); scrollToIdx((cur + d + n) % n); };

  const arrow = (dir) => (
    <button aria-label={dir < 0 ? 'Anterior' : 'Siguiente'} onClick={(e) => { e.stopPropagation(); go(dir); }}
      style={{ position:'absolute', top:'50%', [dir<0?'left':'right']: 10, transform:'translateY(-50%)',
        width:38, height:38, borderRadius:'50%', border:'none', cursor:'pointer', zIndex:3,
        background:'rgba(255,255,255,0.88)', color:'#0F1A2E', fontSize:18, fontWeight:800,
        display:'flex', alignItems:'center', justifyContent:'center', boxShadow:'0 4px 14px rgba(0,0,0,0.25)' }}>
      {dir < 0 ? '‹' : '›'}
    </button>
  );

  return (
    <div style={{ marginTop: isMobile ? 6 : 10 }}>
      <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', marginBottom:10 }}>
        <span style={{ fontFamily:'ui-monospace,Menlo,monospace', fontSize:10.5, fontWeight:800, letterSpacing:1.4, color:'#6B7280', textTransform:'uppercase' }}>Destacados</span>
      </div>
      <div
        onMouseEnter={() => { if (!isMobile) hovering.current = true; }}
        onMouseLeave={() => { if (!isMobile) { hovering.current = false; endDrag(); } }}
        style={{ position:'relative', borderRadius:20, boxShadow:'0 14px 40px -18px rgba(15,26,46,0.4)' }}>
        {/* Native scroll track — swipe (mobile) / drag (desktop) */}
        <div ref={trackRef} className="home-feat-track"
          onScroll={onScroll}
          onPointerDown={onPointerDown}
          onPointerMove={onPointerMove}
          onPointerUp={endDrag}
          onPointerCancel={endDrag}
          onClickCapture={onClickCapture}
          onDragStart={(e) => e.preventDefault()}
          style={{ display:'flex', overflowX:'auto', overflowY:'hidden', scrollSnapType:'x mandatory',
            WebkitOverflowScrolling:'touch', borderRadius:20, cursor: isMobile ? 'auto' : 'grab',
            userSelect:'none', WebkitUserSelect:'none' }}>
          {slides.map(s => (
            <div key={s.key} style={{ flex:'0 0 100%', scrollSnapAlign:'start' }}>
              <HomeFeatSlide slide={s} isMobile={isMobile} height={height} />
            </div>
          ))}
        </div>
        {n > 1 && !isMobile && arrow(-1)}
        {n > 1 && !isMobile && arrow(1)}
        {/* Dots — jump to a slide */}
        {n > 1 && (
          <div style={{ position:'absolute', bottom:10, left:'50%', transform:'translateX(-50%)', display:'flex', gap:6, zIndex:3 }}>
            {slides.map((s, i) => (
              <button key={s.key} aria-label={`Ir al destacado ${i+1}`} onClick={(e) => { e.stopPropagation(); bump(); scrollToIdx(i); }}
                style={{ width: i===idx ? 20 : 7, height:7, borderRadius:999, border:'none', cursor:'pointer', padding:0,
                  background: i===idx ? '#fff' : 'rgba(255,255,255,0.5)', transition:'all .25s' }} />
            ))}
          </div>
        )}
      </div>
      {/* Mobile: arrows below (thumb-reachable), since side arrows are hidden */}
      {n > 1 && isMobile && (
        <div style={{ display:'flex', justifyContent:'center', gap:10, marginTop:10 }}>
          <button aria-label="Anterior" onClick={() => go(-1)} style={{ width:40, height:40, borderRadius:'50%', border:'1px solid rgba(15,26,46,0.12)', background:'#fff', cursor:'pointer', fontSize:18, fontWeight:800, color:'#0F1A2E' }}>‹</button>
          <button aria-label="Siguiente" onClick={() => go(1)} style={{ width:40, height:40, borderRadius:'50%', border:'1px solid rgba(15,26,46,0.12)', background:'#fff', cursor:'pointer', fontSize:18, fontWeight:800, color:'#0F1A2E' }}>›</button>
        </div>
      )}
    </div>
  );
}

// ── Inicio — a warm entry: welcome + one clear train action + three free paths.
//    Heavy analytics (Atlas Score, weekly volume, the 4-module system, detailed
//    metrics) live in Perfil/Progreso, not here. "Próximo entrenamiento" and
//    "Últimas sesiones" are kept but pushed below the paths.
// Tarjeta destacada en Inicio → /coach-online. Navy con botón azul, coherente
// con el resto de Inicio. Nunca pop-up ni banner fijo; se muestra solo aquí.
function HomeCoachCard({ navigate, isMobile }) {
  // Servicio de coaching desactivado tras el flag → no se muestra la tarjeta.
  if (!(typeof ATLAS_FEATURE === 'function' && ATLAS_FEATURE('FEATURE_COACH_ONLINE'))) return null;
  return (
    <div style={{
      background:'#0F1A2E', borderRadius:16, padding: isMobile ? '18px 18px' : '22px 26px',
      display:'flex', flexDirection: isMobile ? 'column' : 'row',
      alignItems: isMobile ? 'stretch' : 'center', gap: isMobile ? 14 : 20 }}>
      <div style={{ flex:1, minWidth:0 }}>
        <div style={{ fontFamily:'"Inter",system-ui', fontSize: isMobile ? 17 : 19, fontWeight:800, color:'#FAFAF7', letterSpacing:-0.3, lineHeight:1.25, marginBottom:6 }}>
          Entrena con un coach
        </div>
        <p style={{ fontFamily:'"Inter",system-ui', fontSize: isMobile ? 13.5 : 14, color:'rgba(250,250,247,0.6)', lineHeight:1.55, margin:0 }}>
          Atlas te da el plan. Un entrenador lo adapta a ti: te evalúa, te guía en las sesiones y ajusta tu progreso.
        </p>
      </div>
      <button
        onClick={() => navigate('/coach-online')}
        className="wp-press"
        style={{ flexShrink:0, width: isMobile ? '100%' : 'auto', minHeight: isMobile ? 48 : 46, padding:'0 24px', borderRadius:12, border:'none', cursor:'pointer', background:'#2563EB', color:'#fff', fontFamily:'"Inter",system-ui', fontSize:15, fontWeight:700 }}>
        Ver cómo funciona
      </button>
    </div>
  );
}

function HomeDashboard() {
  const { state } = useStore();
  const { navigate } = useRoute();
  const isMobile = useIsMobile();
  const activeRoutine = React.useMemo(() => { try { return JSON.parse(localStorage.getItem('atlas.routine.active.v1') || 'null'); } catch { return null; } }, []);

  const userName = (state.user?.name || '').trim();
  const log       = state.log || [];
  const activeWeeks = (typeof computeActiveWeeks === 'function') ? computeActiveWeeks(log).streak : 0;
  const completed = state.sessions?.completed || 0;
  const recent    = log.slice(0, 3);
  const hasRoutine = activeRoutine && Array.isArray(activeRoutine.sessions) && activeRoutine.sessions.length;

  // Featured-carousel data — live: preset catalog + published Aula articles.
  const presets = (typeof window !== 'undefined' && window.PRESET_ROUTINES) || [];
  const [articles, setArticles] = React.useState([]);
  React.useEffect(() => {
    let ok = true;
    if (window.ArticlesService && window.ArticlesService.getAll) {
      window.ArticlesService.getAll({ status: 'published' }).then(a => { if (ok) setArticles(a || []); }).catch(() => {});
    }
    return () => { ok = false; };
  }, []);
  const featuredSlides = React.useMemo(
    () => homeBuildSlides({ presets, articles, state, activeRoutine, navigate }),
    [presets, articles, state.savedRoutines, state.log, state.sessions, activeRoutine]
  );

  function trainSession(routine, i) {
    const s = routine.sessions[i];
    if (!s) return;
    try {
      localStorage.setItem('atlas.pendingWorkout', JSON.stringify(s.exercises || []));
      localStorage.setItem('atlas.pendingWorkoutMeta', JSON.stringify({ routineId: routine.id, routineName: routine.name, sessionName: s.name, sessionIndex: i, totalSessions: routine.sessions.length }));
    } catch {}
    navigate('/player');
  }
  function trainNow() {
    if (!hasRoutine) { navigate('/rutinas'); return; }
    if (activeRoutine.sessions.length === 1) trainSession(activeRoutine, 0);
    else navigate('/rutinas');
  }

  const maxW = isMobile ? 560 : 1000;
  return (
    <div style={{ background:'#FAFAF7', minHeight:'100vh', padding: isMobile ? '20px 16px 40px' : '40px 32px 72px' }}>
      <div style={{ maxWidth: maxW, margin:'0 auto', display:'flex', flexDirection:'column', gap:14 }}>

        {/* Resume a paused session, if any */}
        <WorkoutInProgressBanner />

        {/* Warm welcome */}
        <div>
          <h1 style={{ fontFamily:'"Inter",system-ui', fontWeight:800, fontSize:'clamp(26px,7.5vw,38px)', letterSpacing:-1.2, color:'#0F1A2E', margin:0, lineHeight:1.05 }}>
            Hola{userName ? `, ${userName}` : ''} <span style={{ display:'inline-block' }}>👋</span>
          </h1>
          <div style={{ fontFamily:'"Instrument Serif",Georgia,serif', fontStyle:'italic', fontSize:'clamp(18px,5vw,24px)', color:'#3A4257', marginTop:6 }}>
            ¿Entrenamos?
          </div>
        </div>

        {/* One big, clear train action — only when there's a routine to train */}
        {hasRoutine ? (
          <button onClick={trainNow} style={{
            width:'100%', minHeight:56, borderRadius:16, border:'none', cursor:'pointer',
            background:'linear-gradient(135deg,#16A34A,#22C55E)', color:'#fff',
            fontFamily:'"Inter",system-ui', fontSize:16, fontWeight:800, letterSpacing:-0.3,
            boxShadow:'0 10px 28px -10px rgba(34,197,94,0.55)' }}>
            ▶ Entrenar {activeRoutine.sessions.length === 1 ? (activeRoutine.sessions[0].name || 'hoy') : 'hoy'}
          </button>
        ) : recent.length ? (
          <button onClick={() => recent[0] && navigate('/rutinas')} style={{
            width:'100%', minHeight:52, borderRadius:16, border:'1px solid rgba(15,26,46,0.12)', cursor:'pointer',
            background:'#FFFFFF', color:'#0F1A2E', fontFamily:'"Inter",system-ui', fontSize:15, fontWeight:800, letterSpacing:-0.2 }}>
            ▶ Volver a entrenar
          </button>
        ) : null}

        {/* Three free paths — the user chooses, nothing is forced */}
        <div style={{ display:'grid', gridTemplateColumns: isMobile ? '1fr' : 'repeat(3,1fr)', gap:10, marginTop:2 }}>
          <HomePathCard emoji="🗂️" title="Empieza con una rutina lista"
            desc="Si aún no lo tienes claro: rutinas hechas con rigor, listas para entrenar."
            onClick={() => navigate('/plantillas')} />
          <HomePathCard emoji="💬" title="Pregunta al Coach"
            desc="Si prefieres que el Coach te oriente y te proponga un plan según tu perfil."
            onClick={() => navigate('/coach')} />
          <HomePathCard emoji="🛠️" title="Crea tu rutina"
            desc="Si ya sabes lo que quieres y prefieres construirla tú."
            onClick={() => navigate('/builder')} />
        </div>

        {/* Coaching online — destacada, justo debajo del bloque principal */}
        <HomeCoachCard navigate={navigate} isMobile={isMobile} />

        {/* Featured carousel — fills the desktop space with live content */}
        <HomeFeaturedCarousel slides={featuredSlides} isMobile={isMobile} />

        {/* ── Secondary, below the fold: next workout + recent sessions ── */}
        {hasRoutine ? (
          <MdCard>
            <MdLabel>Tu próximo entrenamiento</MdLabel>
            <div style={{ fontFamily:'"Inter",system-ui', fontSize:'clamp(16px,4.6vw,19px)', fontWeight:800, color:'#0F1A2E', letterSpacing:-0.4 }}>{activeRoutine.name || 'Mi rutina'}</div>
            <div style={{ fontFamily:'"Inter",system-ui', fontSize:13, color:'#5C6477', marginTop:3, marginBottom:12 }}>
              {activeRoutine.sessions.length} {activeRoutine.sessions.length === 1 ? 'sesión' : 'sesiones'}
            </div>
            <div style={{ display:'flex', flexDirection:'column', gap:8 }}>
              {activeRoutine.sessions.slice(0, 4).map((s, i) => (
                <button key={i} onClick={() => trainSession(activeRoutine, i)} style={{
                  display:'flex', alignItems:'center', justifyContent:'space-between', gap:10,
                  minHeight:48, padding:'0 14px', borderRadius:11, cursor:'pointer',
                  border:'1px solid rgba(15,26,46,0.10)', background:'#FFFFFF',
                  fontFamily:'"Inter",system-ui', fontSize:14, fontWeight:700, color:'#0F1A2E' }}>
                  <span style={{ overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>{s.name || `Día ${i+1}`}</span>
                  <span style={{ flexShrink:0, color:'#16A34A', fontWeight:800 }}>▶ Entrenar</span>
                </button>
              ))}
            </div>
          </MdCard>
        ) : null}

        {recent.length > 0 && (
          <MdCard>
            <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', marginBottom:12 }}>
              <MdLabel>Últimas sesiones</MdLabel>
              {/* Rigor kept, but summarised — the detail is one tap away */}
              <span style={{ fontFamily:'"Inter",system-ui', fontSize:11.5, fontWeight:700, color:'#6B7280' }}>
                {activeWeeks > 0 ? `🔥 ${activeWeeks} ${activeWeeks === 1 ? 'semana' : 'semanas'} · ` : ''}{completed} {completed === 1 ? 'sesión' : 'sesiones'}
              </span>
            </div>
            <div style={{ display:'flex', flexDirection:'column', gap:8 }}>
              {recent.map((s, i) => (
                <div key={i} style={{ display:'flex', alignItems:'center', justifyContent:'space-between', gap:10 }}>
                  <span style={{ fontFamily:'"Inter",system-ui', fontSize:14, fontWeight:600, color:'#0F1A2E', overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>
                    {s.sessionName || s.routineName || 'Sesión'}
                  </span>
                  <span style={{ flexShrink:0, fontFamily:'ui-monospace,Menlo,monospace', fontSize:11, color:'#6B7280' }}>{daysAgo(s.dateTs || Date.now())}</span>
                </div>
              ))}
            </div>
            <button onClick={() => navigate('/progreso')} style={{ width:'100%', marginTop:14, minHeight:44, borderRadius:11, cursor:'pointer', border:'1px solid rgba(15,26,46,0.14)', background:'#FFFFFF', fontFamily:'"Inter",system-ui', fontSize:14, fontWeight:700, color:'#0F1A2E' }}>
              Ver mi progreso →
            </button>
          </MdCard>
        )}

      </div>
    </div>
  );
}


// ─── Inicio ───────────────────────────────────────────────────────────────────
// A warm, focused entry (welcome + train action + three free paths). The
// marketing landing (Hero / brand story / the 4-module "Sistema Atlas" / etc.)
// and the heavy analytics are intentionally NOT here — Inicio should read like a
// welcome, not a control panel. Same on mobile and desktop.
function HomePage() {
  return <HomeDashboard />;
}

// Return-to-habit banner for desktop Inicio, in a container matching the context card.
function DesktopHabitBanner() {
  const { navigate } = useRoute();
  return (
    <div style={{ padding: '16px 48px 0' }}>
      <div style={{ maxWidth: 1200, margin: '0 auto' }}>
        <ReturnToHabitCard navigate={navigate} compact />
      </div>
    </div>
  );
}

Object.assign(window, { HomeContextCard, HomePage });
