// Dashboard — full user dashboard reading from store
// (Achievement definitions live in web/sections/cosmetics.jsx as the global
// ACHIEVEMENTS / ACHIEVEMENT_CATS — do not redeclare them here.)

// Generate last 30 days with session markers
function getLast30Days(log) {
  const days = [];
  const now = new Date();
  for (let i = 29; i >= 0; i--) {
    const d = new Date(now);
    d.setDate(now.getDate() - i);
    const dateStr = d.toDateString();
    const hasSession = log.some(entry => entry.date === dateStr);
    days.push({ dateStr, hasSession, dayNum: d.getDate(), weekday: d.getDay() });
  }
  return days;
}

function computeAdherence(sessions, log) {
  if (sessions.completed === 0) return 0;
  const last30 = getLast30Days(log);
  const activeDays = last30.filter(d => d.hasSession).length;
  return Math.round((activeDays / 30) * 100);
}

function DashboardSection() {
  const { state, actions } = useStore();
  const { navigate } = useRoute();
  const isMobile = useIsMobile();
  const [editingName, setEditingName] = React.useState(false);
  const [nameInput, setNameInput] = React.useState(state.user.name);
  const nameRef = React.useRef(null);

  React.useEffect(() => {
    if (editingName && nameRef.current) nameRef.current.focus();
  }, [editingName]);

  const handleNameSave = () => {
    if (nameInput.trim()) actions.setUser({ name: nameInput.trim() });
    setEditingName(false);
  };

  const log = state.log || [];
  const sessions = state.sessions;
  const gems = state.gems;
  const achievements = state.achievements || [];
  const completed = state.reading.completed || [];

  const adherence = computeAdherence(sessions, log);
  const calDays = getLast30Days(log);
  const recentSessions = log.slice(0, 5);

  // Chart from log — real weekly volume in kg when available
  const chartData = React.useMemo(() => {
    if (log.length < 2) return [];
    if (typeof peGetWeeklyVolume !== 'undefined') {
      const weeks = peGetWeeklyVolume(log, 12);
      const vols  = weeks.map(w => w.totalVolume);
      if (vols.some(v => v > 0)) return vols;
      return weeks.map(w => w.totalSets);
    }
    return log.slice(0, 12).reverse().map(entry =>
      (entry.exercises || []).reduce((acc, ex) => acc + (ex.sets || []).length, 0)
    );
  }, [log]);

  const progressData = React.useMemo(() => {
    if (typeof peGetProgressSummary === 'undefined' || log.length < 2) return null;
    return peGetProgressSummary(log);
  }, [log]);

  const levelColors = {
    principiante: { bg: '#E7F8EC', text: '#1F8B3A' },
    intermedio: { bg: 'rgba(42,111,219,0.1)', text: '#1a4fa0' },
    avanzado: { bg: 'rgba(15,26,46,0.1)', text: '#0F1A2E' },
  };
  const lvlColor = levelColors[state.user.level] || levelColors.intermedio;

  return (
    <section style={{ padding: isMobile ? '24px 16px' : '120px 32px', background: '#FFFFFF', minHeight: '80vh' }}>
      <div style={{ maxWidth: 1180, margin: '0 auto' }}>

        {/* Header */}
        <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', marginBottom: 40 }}>
          <div>
            <span style={{ fontFamily: '"Inter",system-ui', fontSize: 13, fontWeight: 700, letterSpacing: 1.6, textTransform: 'uppercase', color: '#5C6477' }}>
              Perfil · Dashboard
            </span>
            <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginTop: 10 }}>
              <AvatarBadge
                avatarId={(state.cosmetics || {}).avatar || 'default'}
                frameId={(state.cosmetics || {}).frame || 'none'}
                name={state.user.name}
                size={56}
              />
              <div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                  {editingName ? (
                    <input
                      ref={nameRef}
                      aria-label="Tu nombre"
                      value={nameInput}
                      onChange={e => setNameInput(e.target.value)}
                      onBlur={handleNameSave}
                      onKeyDown={e => e.key === 'Enter' && handleNameSave()}
                      style={{
                        fontFamily: '"Inter",system-ui', fontSize: 28, fontWeight: 700,
                        color: '#0F1A2E', letterSpacing: -0.8,
                        border: 'none', borderBottom: '2px solid #0F1A2E',
                        background: 'transparent', padding: '0 0 2px',
                        width: 200,
                      }}
                    />
                  ) : (
                    <h1 style={{ fontFamily: '"Inter",system-ui', fontSize: 28, fontWeight: 700, color: '#0F1A2E', letterSpacing: -1, margin: 0 }}>
                      Hola, {state.user.name}
                    </h1>
                  )}
                  <button
                    onClick={() => { setNameInput(state.user.name); setEditingName(e => !e); }}
                    aria-label="Editar nombre"
                    title="Editar nombre"
                    style={{ border: 'none', background: 'none', cursor: 'pointer', color: '#6E7686', fontSize: 14 }}
                  >
                    ✏️
                  </button>
                </div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 4 }}>
                  <span style={{
                    padding: '3px 12px', borderRadius: 999,
                    background: lvlColor.bg, color: lvlColor.text,
                    fontFamily: '"Inter",system-ui', fontSize: 12, fontWeight: 700,
                    textTransform: 'capitalize',
                  }}>
                    {state.user.level}
                  </span>
                  <span style={{ fontFamily: '"Inter",system-ui', fontSize: 12, color: '#6B7280' }}>
                    {sessions.completed} sesiones totales
                  </span>
                </div>
              </div>
            </div>
          </div>
          <button
            onClick={() => navigate('/ajustes')}
            aria-label="Ajustes"
            title="Ajustes"
            className="wp-press"
            style={{ flexShrink: 0, width: 44, height: 44, borderRadius: 12, border: '1px solid rgba(15,26,46,0.12)', background: '#FFFFFF', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#3A4257' }}
          >
            <svg width="22" height="22" viewBox="0 0 24 24" fill="none" aria-hidden="true">
              <circle cx="12" cy="12" r="3.2" stroke="currentColor" strokeWidth="1.8" />
              <path d="M12 2.5v2.2M12 19.3v2.2M4.2 7l1.9 1.1M17.9 15.9l1.9 1.1M4.2 17l1.9-1.1M17.9 8.1l1.9-1.1" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" />
            </svg>
          </button>
        </div>

        {/* Perfil Atlas — the single, canonical profile configurator. The Coach
            only links here; the questionnaire itself runs as a guided chat. */}
        {(() => {
          const ap = (typeof window !== 'undefined' && window.AtlasProfile && window.AtlasProfile.get) ? window.AtlasProfile.get() : null;
          const OBJ = { muscle:'Hipertrofia', fat_loss:'Perder grasa', recomp:'Recomposición', performance:'Rendimiento', health:'Salud' };
          const EXP = { beginner:'Principiante', intermediate:'Intermedio', advanced:'Avanzado' };
          const chips = ap ? [OBJ[ap.objective] || ap.objective, EXP[ap.experience] || ap.experience, ap.trainingDays ? `${ap.trainingDays} días/sem` : null].filter(Boolean) : [];
          const launch = () => { try { localStorage.setItem('atlas.profile.launch.v1', '1'); } catch {} navigate('/coach'); };
          return (
            <div style={{ background:'#FAFAF7', borderRadius:20, border:'1px solid rgba(15,26,46,0.06)', padding:'18px 22px', marginBottom: isMobile ? 14 : 24, display:'flex', alignItems:'center', gap:16, flexWrap:'wrap' }}>
              <div style={{ flex:1, minWidth:200 }}>
                <div style={{ display:'flex', alignItems:'center', gap:8 }}>
                  <span style={{ width:8, height:8, borderRadius:'50%', background: ap ? '#1F8B3A' : '#F59E0B', display:'block' }} />
                  <span style={{ fontFamily:'"Inter",system-ui', fontSize:15, fontWeight:800, color:'#0F1A2E', letterSpacing:-0.3 }}>Perfil Atlas</span>
                </div>
                <div style={{ fontFamily:'"Inter",system-ui', fontSize:13, color:'#5C6477', marginTop:6, lineHeight:1.5 }}>
                  {ap
                    ? 'Tus preferencias personalizan las recomendaciones del Coach.'
                    : 'Configúralo una vez para que el Coach adapte rutinas y consejos a tu objetivo, nivel y limitaciones.'}
                </div>
                {chips.length > 0 && (
                  <div style={{ display:'flex', gap:6, flexWrap:'wrap', marginTop:10 }}>
                    {chips.map(c => (
                      <span key={c} style={{ padding:'3px 10px', borderRadius:999, background:'rgba(42,111,219,0.1)', color:'#1a4fa0', fontFamily:'"Inter",system-ui', fontSize:11, fontWeight:700 }}>{c}</span>
                    ))}
                  </div>
                )}
              </div>
              <button onClick={launch} style={{ flexShrink:0, padding:'11px 18px', borderRadius:12, border:'none', cursor:'pointer', background:'#2563EB', color:'#fff', fontFamily:'"Inter",system-ui', fontSize:13, fontWeight:700 }}>
                {ap ? 'Editar Perfil Atlas' : 'Configurar Perfil Atlas'}
              </button>
            </div>
          );
        })()}

        {/* Level & XP — lifetime progress (gross gems earned), with a progress
            bar to the next level and the gems explainer. */}
        {(typeof xpToLevel === 'function') && (() => {
          const lv = xpToLevel(state.xp || 0);
          return (
            <div style={{ background:'#0F1A2E', color:'#FAFAF7', borderRadius:20, padding: isMobile ? '18px 20px' : '22px 26px', marginBottom: isMobile ? 14 : 24 }}>
              <div style={{ display:'flex', alignItems:'center', gap:14 }}>
                <div style={{ flexShrink:0, width:56, height:56, borderRadius:16, background:'rgba(59,130,246,0.18)', border:'1px solid rgba(59,130,246,0.4)', display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center' }}>
                  <span style={{ fontFamily:'ui-monospace,Menlo,monospace', fontSize:8, fontWeight:700, color:'#93C5FD', letterSpacing:0.5 }}>NIVEL</span>
                  <span style={{ fontFamily:'"Inter",system-ui', fontSize:23, fontWeight:900, lineHeight:1 }}>{lv.level}</span>
                </div>
                <div style={{ flex:1, minWidth:0 }}>
                  <div style={{ display:'flex', alignItems:'baseline', gap:8, flexWrap:'wrap' }}>
                    <span style={{ fontFamily:'"Inter",system-ui', fontSize:18, fontWeight:800, letterSpacing:-0.4 }}>{lv.title}</span>
                    <span style={{ fontFamily:'"Inter",system-ui', fontSize:12, color:'rgba(250,250,247,0.55)' }}>{lv.xp.toLocaleString('es-ES')} XP</span>
                  </div>
                  <div style={{ marginTop:10, height:8, borderRadius:999, background:'rgba(255,255,255,0.1)', overflow:'hidden' }}>
                    <div style={{ height:'100%', width:`${Math.round(lv.progress*100)}%`, background:'linear-gradient(90deg,#3B82F6,#60A5FA)', borderRadius:999, transition:'width .4s var(--ease-out,ease)' }} />
                  </div>
                  <div style={{ marginTop:7, fontFamily:'"Inter",system-ui', fontSize:12, color:'rgba(250,250,247,0.6)' }}>
                    {lv.isMax ? 'Nivel máximo alcanzado' : `Faltan ${lv.xpForNext.toLocaleString('es-ES')} XP para ${lv.nextTitle}`}
                  </div>
                </div>
              </div>
              <div style={{ marginTop:14, paddingTop:12, borderTop:'1px solid rgba(255,255,255,0.08)' }}>
                {(typeof GemsHelpButton === 'function') && <GemsHelpButton style={{ color:'#93C5FD' }} />}
              </div>
            </div>
          );
        })()}

        {/* Install app — re-findable entry point for the PWA guide, shown only
            on mobile when Atlas isn't installed yet. */}
        {(typeof window !== 'undefined' && window.AtlasPWA && window.AtlasPWA.available()) && (
          <button onClick={() => window.AtlasPWA.open()} className="wp-press" style={{ width:'100%', textAlign:'left', display:'flex', alignItems:'center', gap:12, background:'#FAFAF7', borderRadius:14, border:'1px solid rgba(15,26,46,0.06)', padding:'13px 18px', marginBottom: isMobile ? 14 : 24, cursor:'pointer' }}>
            <span aria-hidden style={{ flexShrink:0, width:34, height:34, borderRadius:9, background:'rgba(37,99,235,0.10)', color:'#2563EB', display:'flex', alignItems:'center', justifyContent:'center', fontSize:18 }}>⬇</span>
            <span style={{ flex:1, minWidth:0 }}>
              <span style={{ display:'block', fontFamily:'"Inter",system-ui', fontSize:14, fontWeight:800, color:'#0F1A2E' }}>Instalar Atlas en tu móvil</span>
              <span style={{ display:'block', fontFamily:'"Inter",system-ui', fontSize:12, color:'#5C6477', marginTop:1 }}>Tenla como app · funciona sin conexión</span>
            </span>
            <span style={{ flexShrink:0, fontFamily:'"Inter",system-ui', fontSize:13, fontWeight:800, color:'#2563EB' }}>Ver cómo →</span>
          </button>
        )}

        {/* Row 1 — 4 key stats */}
        <div style={{ display: 'grid', gridTemplateColumns: isMobile ? 'repeat(2, 1fr)' : 'repeat(4, 1fr)', gap: isMobile ? 10 : 16, marginBottom: isMobile ? 14 : 24 }}>
          <StatCard label="Semanas activas" value={(typeof computeActiveWeeks === 'function') ? computeActiveWeeks(log).streak : 0} unit="sem" color="#0F1A2E" icon="🔥" />
          <StatCard label="Sesiones totales" value={sessions.completed} unit="" color="#1a4fa0" icon="🏋️" />
          <StatCard label="Gemas acumuladas" value={gems.balance.toLocaleString('es-ES')} unit="" color="#1F8B3A" icon="💎" />
          <StatCard label="Adherencia 30d" value={`${adherence}%`} unit="" color={adherence >= 70 ? '#1F8B3A' : adherence >= 40 ? '#0F1A2E' : '#C24545'} icon="📊" />
        </div>

        {/* Row 2 — calendar + chart */}
        <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : '1fr 1fr', gap: 16, marginBottom: isMobile ? 14 : 24 }}>

          {/* Streak calendar */}
          <div style={{ background: '#FAFAF7', borderRadius: 20, border: '1px solid rgba(15,26,46,0.06)', padding: '20px 24px' }}>
            <div style={sectionLabelStyle}>Últimos 30 días</div>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(10, 1fr)', gap: 5, marginTop: 14 }}>
              {calDays.map((day, i) => (
                <div
                  key={i}
                  title={`${day.dateStr}${day.hasSession ? ' · Sesión' : ''}`}
                  style={{
                    aspectRatio: '1', borderRadius: 6,
                    background: day.hasSession ? '#0F1A2E' : 'rgba(15,26,46,0.07)',
                    position: 'relative',
                  }}
                >
                  {day.hasSession && (
                    <div style={{
                      position: 'absolute', inset: 0, borderRadius: 6,
                      background: 'rgba(255,255,255,0.1)',
                    }} />
                  )}
                </div>
              ))}
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: 12 }}>
              <div style={{ width: 12, height: 12, borderRadius: 3, background: '#0F1A2E' }} />
              <span style={{ fontFamily: '"Inter",system-ui', fontSize: 11, color: '#6B7280' }}>Sesión registrada</span>
              <div style={{ width: 12, height: 12, borderRadius: 3, background: 'rgba(15,26,46,0.07)', marginLeft: 8 }} />
              <span style={{ fontFamily: '"Inter",system-ui', fontSize: 11, color: '#6B7280' }}>Sin sesión</span>
            </div>
          </div>

          {/* Progress chart */}
          <div style={{ background: '#FAFAF7', borderRadius: 20, border: '1px solid rgba(15,26,46,0.06)', padding: '20px 24px' }}>
            <div style={sectionLabelStyle}>Volumen semanal (kg)</div>
            <DashProgressChart data={chartData} />
          </div>
        </div>

        {/* Row 3 — recent sessions */}
        <div style={{ background: '#FAFAF7', borderRadius: 20, border: '1px solid rgba(15,26,46,0.06)', padding: '20px 24px', marginBottom: 24 }}>
          <div style={sectionLabelStyle}>Sesiones recientes</div>
          {recentSessions.length === 0 ? (
            <div style={{ textAlign: 'center', padding: '30px 0', color: '#6B7280' }}>
              <p style={{ fontFamily: '"Inter",system-ui', fontSize: 14 }}>Aún no has registrado sesiones. ¡Ve al Builder!</p>
            </div>
          ) : (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginTop: 14 }}>
              {recentSessions.map((session, i) => {
                const totalSets = (session.exercises || []).reduce((acc, ex) => acc + (ex.sets || []).length, 0);
                const exerciseNames = (session.exercises || []).map(e => e.name).join(', ');
                return (
                  <div key={session.id || i} style={{
                    padding: '12px 16px', borderRadius: 12,
                    background: '#FFFFFF', border: '1px solid rgba(15,26,46,0.06)',
                    display: 'flex', alignItems: 'center', gap: 14,
                  }}>
                    <div style={{
                      width: 36, height: 36, borderRadius: 10, flexShrink: 0,
                      background: '#0F1A2E', color: '#FAFAF7',
                      display: 'flex', alignItems: 'center', justifyContent: 'center',
                      fontFamily: '"Inter",system-ui', fontSize: 13, fontWeight: 700,
                    }}>
                      {(session.exercises || []).length}
                    </div>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ display:'flex', alignItems:'center', gap:8, marginBottom: 2 }}>
                        <span style={{ fontFamily: '"Inter",system-ui', fontSize: 13, fontWeight: 700, color: '#0F1A2E' }}>
                          {session.date}
                        </span>
                        {session.partial && (
                          <span style={{ fontFamily:'"Inter",system-ui', fontSize:9, fontWeight:800, letterSpacing:0.4, color:'#B45309', background:'rgba(251,191,36,0.16)', border:'1px solid rgba(180,83,9,0.28)', borderRadius:999, padding:'2px 7px' }}>PARCIAL</span>
                        )}
                      </div>
                      <div style={{
                        fontFamily: '"Inter",system-ui', fontSize: 11, color: '#6B7280',
                        whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
                      }}>
                        {exerciseNames || 'Sin ejercicios'}
                      </div>
                    </div>
                    <div style={{ textAlign: 'right', flexShrink: 0 }}>
                      <div style={{ fontFamily: 'ui-monospace,Menlo,monospace', fontSize: 12, color: '#5C6477', fontWeight: 700 }}>
                        {totalSets} series
                      </div>
                      {session.gems > 0 && (
                        <div style={{ fontFamily: '"Inter",system-ui', fontSize: 11, color: '#1F8B3A', fontWeight: 600 }}>
                          +{session.gems} 💎
                        </div>
                      )}
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </div>

        {/* Row 4 — Exercise progression */}
        {progressData && (progressData.topProgress.length > 0 || progressData.stagnant.length > 0) && (
          <div style={{ background: '#FAFAF7', borderRadius: 20, border: '1px solid rgba(15,26,46,0.06)', padding: '20px 24px', marginBottom: 24 }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 14 }}>
              <div style={sectionLabelStyle}>Progresión de ejercicios</div>
              {progressData.deload?.needed && (
                <span style={{ padding: '3px 10px', borderRadius: 999, background: 'rgba(180,80,0,0.08)', border: '1px solid rgba(180,80,0,0.18)', fontFamily: '"Inter",system-ui', fontSize: 11, fontWeight: 700, color: '#B45000' }}>
                  Deload recomendado
                </span>
              )}
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : '1fr 1fr', gap: 16 }}>
              <div>
                <div style={{ fontFamily: '"Inter",system-ui', fontSize: 11, fontWeight: 700, color: '#1F8B3A', letterSpacing: 0.3, textTransform: 'uppercase', marginBottom: 10 }}>
                  En progresión ↑
                </div>
                {progressData.topProgress.length === 0
                  ? <div style={{ fontFamily: '"Inter",system-ui', fontSize: 12, color: '#6B7280' }}>Registra cargas para ver tu evolución</div>
                  : progressData.topProgress.map((e, i) => (
                    <div key={i} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '7px 0', borderBottom: i < progressData.topProgress.length - 1 ? '1px solid rgba(15,26,46,0.05)' : 'none' }}>
                      <span style={{ fontFamily: '"Inter",system-ui', fontSize: 12, fontWeight: 600, color: '#0F1A2E' }}>{e.name}</span>
                      <span style={{ fontFamily: 'ui-monospace,Menlo,monospace', fontSize: 11, color: '#1F8B3A', fontWeight: 700 }}>+{e.delta} kg</span>
                    </div>
                  ))
                }
              </div>
              <div>
                <div style={{ fontFamily: '"Inter",system-ui', fontSize: 11, fontWeight: 700, color: '#B45000', letterSpacing: 0.3, textTransform: 'uppercase', marginBottom: 10 }}>
                  Sin progreso
                </div>
                {progressData.stagnant.length === 0
                  ? <div style={{ fontFamily: '"Inter",system-ui', fontSize: 12, color: '#6B7280' }}>Sin estancamientos detectados</div>
                  : progressData.stagnant.slice(0, 3).map((e, i) => (
                    <div key={i} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '7px 0', borderBottom: i < Math.min(progressData.stagnant.length, 3) - 1 ? '1px solid rgba(15,26,46,0.05)' : 'none' }}>
                      <span style={{ fontFamily: '"Inter",system-ui', fontSize: 12, fontWeight: 600, color: '#0F1A2E' }}>{e.name}</span>
                      <span style={{ fontFamily: 'ui-monospace,Menlo,monospace', fontSize: 11, color: '#B45000', fontWeight: 700 }}>{e.sessions} ses.</span>
                    </div>
                  ))
                }
              </div>
            </div>
            {progressData.deload?.needed && (
              <div style={{ marginTop: 14, padding: '10px 14px', borderRadius: 10, background: 'rgba(180,80,0,0.05)', border: '1px solid rgba(180,80,0,0.14)' }}>
                <div style={{ fontFamily: '"Inter",system-ui', fontSize: 12, color: '#B45000', fontWeight: 600, marginBottom: 4 }}>
                  Señales de fatiga acumulada detectadas:
                </div>
                {progressData.deload.reasons.map((r, i) => (
                  <div key={i} style={{ fontFamily: '"Inter",system-ui', fontSize: 11, color: '#7A3A00' }}>• {r}</div>
                ))}
              </div>
            )}
          </div>
        )}

        {/* Row 4.5 — cosmetics customization (equip owned avatar / frame) */}
        <CustomizePanel isMobile={isMobile} />

        {/* Row 5 — achievements (earned by training) */}
        <div style={{ background: '#FAFAF7', borderRadius: 20, border: '1px solid rgba(15,26,46,0.06)', padding: isMobile ? '18px 16px' : '20px 24px', marginTop: 24 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
            <div style={sectionLabelStyle}>Logros</div>
            <span style={{ fontFamily: '"Inter",system-ui', fontSize: 12, color: '#6B7280' }}>
              {ACHIEVEMENTS.filter(a => achievements.includes(a.id)).length} / {ACHIEVEMENTS.length} desbloqueados
            </span>
          </div>
          {ACHIEVEMENT_CATS.map(cat => {
            const list = ACHIEVEMENTS.filter(a => a.cat === cat);
            return (
              <div key={cat} style={{ marginBottom: 18 }}>
                <div style={{ fontFamily: 'ui-monospace,Menlo,monospace', fontSize: 10, fontWeight: 700, color: '#6B7280', letterSpacing: 1, marginBottom: 10, textTransform: 'uppercase' }}>
                  {cat}
                </div>
                <div style={{ display: 'grid', gridTemplateColumns: isMobile ? 'repeat(2, 1fr)' : 'repeat(4, 1fr)', gap: 10 }}>
                  {list.map(ach => {
                    const unlocked = achievements.includes(ach.id);
                    return (
                      <div key={ach.id} style={{
                        padding: '14px 12px', borderRadius: 16,
                        background: unlocked ? '#FFFFFF' : 'rgba(15,26,46,0.03)',
                        border: unlocked ? '1px solid rgba(15,26,46,0.12)' : '1px dashed rgba(15,26,46,0.12)',
                        textAlign: 'center', transition: 'all 0.2s', opacity: unlocked ? 1 : 0.5,
                      }}>
                        <div style={{ fontSize: 26, marginBottom: 6, filter: unlocked ? 'none' : 'grayscale(1)' }}>
                          {unlocked ? ach.icon : '🔒'}
                        </div>
                        <div style={{ fontFamily: '"Inter",system-ui', fontSize: 12, fontWeight: 700, color: '#0F1A2E', marginBottom: 3 }}>
                          {ach.title}
                        </div>
                        <div style={{ fontFamily: '"Inter",system-ui', fontSize: 10, color: '#6B7280', lineHeight: 1.4 }}>
                          {ach.desc}
                        </div>
                      </div>
                    );
                  })}
                </div>
              </div>
            );
          })}
        </div>

        {/* Row 6 — training preferences */}
        <TrainingPrefsBlock />

        {/* Row 6.5 — entrena con un coach */}
        <CoachTechReviewCard navigate={navigate} />

        {/* Datos, ayuda y legal viven ahora en Ajustes (icono de engranaje en la
            cabecera). Se evita así duplicar la lógica de copia de seguridad. */}

      </div>
    </section>
  );
}

// Equip owned avatars & frames. Shows only cosmetics the user already owns
// (default/none are free); more are unlocked in the cosmetic store below.
function CustomizePanel({ isMobile }) {
  const { state, actions } = useStore();
  const owned    = state.store.owned || [];
  const equipped = state.cosmetics || { avatar: 'default', frame: 'none' };
  const name     = state.user.name || '';
  const ownedAvatars = AVATARS.filter(a => a.cost === 0 || owned.includes(a.id));
  const ownedFrames  = FRAMES.filter(f => f.cost === 0 || owned.includes(f.id));

  const row = (items, kind) => (
    <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>
      {items.map(it => {
        const on = equipped[kind] === it.id;
        return (
          <button key={it.id} onClick={() => actions.equipCosmetic(kind, it.id)} title={it.name}
            aria-label={`Equipar ${it.name}`}
            style={{
              border: 'none', background: 'none', cursor: 'pointer', padding: 4, borderRadius: 16,
              outline: on ? '2px solid #3B82F6' : '2px solid transparent',
              outlineOffset: 1, transition: 'outline .15s',
            }}>
            <AvatarBadge
              avatarId={kind === 'avatar' ? it.id : equipped.avatar}
              frameId={kind === 'frame' ? it.id : equipped.frame}
              name={name} size={48} />
          </button>
        );
      })}
    </div>
  );

  const subLabel = { fontFamily: 'ui-monospace,Menlo,monospace', fontSize: 10, fontWeight: 700, color: '#6B7280', letterSpacing: 1, textTransform: 'uppercase', marginBottom: 8 };

  return (
    <div style={{ background: '#FAFAF7', borderRadius: 20, border: '1px solid rgba(15,26,46,0.06)', padding: isMobile ? '18px 16px' : '20px 24px', marginBottom: 24 }}>
      <div style={sectionLabelStyle}>Personalización</div>
      <div style={{ marginTop: 14 }}>
        <div style={subLabel}>Avatar</div>
        {row(ownedAvatars, 'avatar')}
      </div>
      <div style={{ marginTop: 16 }}>
        <div style={subLabel}>Marco</div>
        {row(ownedFrames, 'frame')}
      </div>
      <p style={{ margin: '14px 0 0', fontFamily: '"Inter",system-ui', fontSize: 11.5, color: '#6B7280', lineHeight: 1.5 }}>
        Consigue más avatares y marcos en la <strong>Tienda cosmética</strong>, más abajo. Se ganan con gemas de tus entrenamientos.
      </p>
    </div>
  );
}

// Toggle switch (accessible, 44px tap target)
function PrefToggle({ label, hint, checked, onChange }) {
  const isMobile = useIsMobile();
  return (
    <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', gap:16, padding: isMobile ? '10px 0' : '8px 0' }}>
      <div style={{ minWidth:0 }}>
        <div style={{ fontFamily:'"Inter",system-ui', fontSize: isMobile ? 15 : 14, fontWeight:600, color:'#0F1A2E' }}>{label}</div>
        {hint && <div style={{ fontFamily:'"Inter",system-ui', fontSize:12, color:'#6B7280', marginTop:2, lineHeight:1.5 }}>{hint}</div>}
      </div>
      <button
        role="switch" aria-checked={checked} aria-label={label}
        onClick={() => onChange(!checked)}
        style={{ flexShrink:0, width:52, height:32, borderRadius:999, border:'none', cursor:'pointer', position:'relative',
          background: checked ? '#16A34A' : 'rgba(15,26,46,0.16)', transition:'background .2s' }}>
        <span style={{ position:'absolute', top:3, left: checked ? 23 : 3, width:26, height:26, borderRadius:'50%', background:'#fff', boxShadow:'0 1px 3px rgba(0,0,0,0.25)', transition:'left .2s' }} />
      </button>
    </div>
  );
}

function TrainingPrefsBlock() {
  const { state, actions } = useStore();
  const isMobile = useIsMobile();
  const keepAwake  = state.prefs?.keepAwake !== false;
  const animateEx  = state.prefs?.animateExercises !== false;
  const divider = <div style={{ height:1, background:'rgba(15,26,46,0.06)', margin:'6px 0' }} />;
  return (
    <div style={{ marginTop: 20, background: '#FAFAF7', borderRadius: 20, border: '1px solid rgba(15,26,46,0.06)', padding: isMobile ? '18px 16px' : '20px 24px' }}>
      <div style={sectionLabelStyle}>Entrenamiento</div>
      <div style={{ marginTop: 6 }}>
        <PrefToggle
          label="Animar ejercicios"
          hint="Alterna las dos posiciones de cada ejercicio (inicio↔fin) para dar sensación de movimiento. Si notas tirones, desactívalo para ver imágenes estáticas."
          checked={animateEx}
          onChange={v => actions.setPref('animateExercises', v)}
        />
        {divider}
        <PrefToggle
          label="Mantener pantalla activa"
          hint="Evita que la pantalla se apague entre series durante el entrenamiento."
          checked={keepAwake}
          onChange={v => actions.setPref('keepAwake', v)}
        />
      </div>
    </div>
  );
}

function StatCard({ label, value, unit, color, icon }) {
  return (
    <div style={{
      padding: '20px 22px', borderRadius: 20,
      background: '#FAFAF7', border: '1px solid rgba(15,26,46,0.06)',
    }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 10 }}>
        <span style={{ fontFamily: '"Inter",system-ui', fontSize: 11, fontWeight: 700, color: '#6B7280', letterSpacing: 0.4, textTransform: 'uppercase' }}>
          {label}
        </span>
        <span style={{ fontSize: 18 }}>{icon}</span>
      </div>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 4 }}>
        <span style={{ fontFamily: '"Inter",system-ui', fontSize: 34, fontWeight: 800, color, letterSpacing: -1.5, lineHeight: 1 }}>
          {value}
        </span>
        {unit && (
          <span style={{ fontFamily: '"Inter",system-ui', fontSize: 14, color: '#6B7280', fontWeight: 500 }}>
            {unit}
          </span>
        )}
      </div>
    </div>
  );
}

function DashProgressChart({ data }) {
  const w = 400, h = 120;
  const max = Math.max(...data, 1);
  const min = 0;
  const n = data.length;
  const px = (i) => n <= 1 ? w / 2 : (i / (n - 1)) * w;
  const py = (v) => h - ((v - min) / (max - min || 1)) * h;

  if (n < 2) {
    return (
      <div style={{ height: 140, display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#6B7280' }}>
        <span style={{ fontFamily: '"Inter",system-ui', fontSize: 13 }}>Registra sesiones para ver tu progresión</span>
      </div>
    );
  }

  const path = data.map((v, i) => `${i === 0 ? 'M' : 'L'} ${px(i)} ${py(v)}`).join(' ');
  const areaPath = `${path} L ${px(n - 1)} ${h} L ${px(0)} ${h} Z`;

  return (
    <svg viewBox={`0 0 ${w} ${h + 20}`} style={{ width: '100%', height: 140, marginTop: 10 }}>
      <defs>
        <linearGradient id="dashChartGrad" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0" stopColor="#0F1A2E" stopOpacity="0.1" />
          <stop offset="1" stopColor="#0F1A2E" stopOpacity="0" />
        </linearGradient>
      </defs>
      {[0, 0.25, 0.5, 0.75, 1].map((frac, i) => (
        <line key={i} x1="0" y1={h * frac} x2={w} y2={h * frac} stroke="rgba(15,26,46,0.06)" strokeDasharray="2 6" />
      ))}
      <path d={areaPath} fill="url(#dashChartGrad)" />
      <path d={path} fill="none" stroke="#0F1A2E" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" />
      {data.map((v, i) => (
        <circle key={i} cx={px(i)} cy={py(v)} r="3.5" fill="#0F1A2E" />
      ))}
    </svg>
  );
}

const sectionLabelStyle = {
  fontFamily: 'ui-monospace,Menlo,monospace', fontSize: 11, fontWeight: 700,
  color: '#6B7280', letterSpacing: 0.6, textTransform: 'uppercase',
};

// Tarjeta en Perfil que invita al coaching online (revisión de técnica).
function CoachTechReviewCard({ navigate }) {
  const isMobile = useIsMobile();
  // 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={{ marginTop: 20, background: '#0F1A2E', borderRadius: 20, border: '1px solid rgba(15,26,46,0.06)', padding: isMobile ? '20px 18px' : '24px 28px', 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 : 18, fontWeight: 800, color: '#FAFAF7', letterSpacing: -0.3, lineHeight: 1.25, marginBottom: 6 }}>
          ¿Quieres que un coach revise tu técnica?
        </div>
        <p style={{ fontFamily: '"Inter",system-ui', fontSize: isMobile ? 13.5 : 13, color: 'rgba(250,250,247,0.6)', lineHeight: 1.55, margin: 0 }}>
          La app te da el plan; un coach revisa cómo lo ejecutas, ajusta el programa a ti y te acompaña.
        </p>
      </div>
      <button
        onClick={() => navigate('/coach-online')}
        className="wp-press"
        style={{ flexShrink: 0, width: isMobile ? '100%' : 'auto', minHeight: isMobile ? 46 : 44, padding: '0 22px', borderRadius: 11, border: 'none', cursor: 'pointer', background: '#2563EB', color: '#fff', fontFamily: '"Inter",system-ui', fontSize: isMobile ? 15 : 14, fontWeight: 700 }}
      >
        Entrena con un coach
      </button>
    </div>
  );
}


Object.assign(window, { DashboardSection });
