// Pau Fit — Sub-screens (Logros, Progreso, Historial, Rutina detail)

const { useState: useS3, useEffect: useE3 } = React;

// ═════════════════════════════════════════════════════════════
// LOGROS
// ═════════════════════════════════════════════════════════════
function LogrosScreen({ theme, nav }) {
  const T = theme;
  const unlocked = LOGROS.filter(l => l.unlocked).length;
  const total = LOGROS.length;
  const pct = unlocked / total;

  return (
    <div style={{ paddingBottom: 110 }}>
      <div style={{
        background: `linear-gradient(160deg, ${T.subtle}, ${T.accent}40)`,
        padding: '12px 22px 26px',
        borderBottomLeftRadius: 32, borderBottomRightRadius: 32,
      }}>
        <BackBtn onClick={() => nav.back()}/>
        <div style={{ marginTop: 14, textAlign: 'center' }}>
          <div style={{ fontSize: 56, lineHeight: 1 }}>🏆</div>
          <div style={{ fontFamily: 'Poppins', fontSize: 26, fontWeight: 600, color: '#2D2A26', marginTop: 8, letterSpacing: -0.5 }}>Mis logros</div>
          <div style={{ fontFamily: 'Poppins', fontSize: 13, color: 'rgba(45,42,38,0.65)', marginTop: 4 }}>
            {unlocked} de {total} desbloqueados
          </div>
          <div style={{ marginTop: 14, padding: '0 20px' }}>
            <div style={{ height: 6, background: 'rgba(45,42,38,0.1)', borderRadius: 999, overflow: 'hidden' }}>
              <div style={{ width: `${pct*100}%`, height: '100%', background: '#2D2A26', borderRadius: 999, transition: 'width 600ms ease' }}/>
            </div>
          </div>
        </div>
      </div>

      <div style={{ padding: '20px 18px 0', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
        {LOGROS.map(l => (
          <div key={l.id} style={{
            padding: 14, background: T.card, borderRadius: 18, border: T.border,
            display: 'flex', flexDirection: 'column', gap: 6,
            opacity: l.unlocked ? 1 : 0.5,
            position: 'relative', overflow: 'hidden',
          }}>
            {l.unlocked && (
              <div style={{
                position: 'absolute', top: -10, right: -10, width: 60, height: 60,
                borderRadius: '50%', background: `radial-gradient(circle, ${T.accent}30, transparent 70%)`,
              }}/>
            )}
            <div style={{
              fontSize: 36, filter: l.unlocked ? 'none' : 'grayscale(1)',
              position: 'relative',
            }}>{l.emoji}</div>
            <div style={{ fontFamily: 'Poppins', fontSize: 13, fontWeight: 600, color: T.text, letterSpacing: -0.2, lineHeight: 1.2 }}>{l.title}</div>
            <div style={{ fontFamily: 'Poppins', fontSize: 11, color: T.muted, lineHeight: 1.3 }}>{l.desc}</div>
            {!l.unlocked && (
              <div style={{ marginTop: 4 }}>
                <div style={{ height: 4, background: T.subtle, borderRadius: 999, overflow: 'hidden' }}>
                  <div style={{ width: `${l.progress*100}%`, height: '100%', background: T.accent }}/>
                </div>
              </div>
            )}
            {l.unlocked && (
              <div style={{
                marginTop: 4, fontFamily: 'Poppins', fontSize: 9, fontWeight: 700,
                color: '#5C7A56', letterSpacing: 0.6, textTransform: 'uppercase',
              }}>✓ Desbloqueado</div>
            )}
          </div>
        ))}
      </div>
    </div>
  );
}

// ═════════════════════════════════════════════════════════════
// PROGRESO — fotos + medidas
// ═════════════════════════════════════════════════════════════
function ProgresoScreen({ theme, nav }) {
  const T = theme;
  const [tab, setTab] = useS3('fotos');
  const latest = MEDIDAS[0];
  const prev = MEDIDAS[MEDIDAS.length - 1];

  return (
    <div style={{ paddingBottom: 110 }}>
      <div style={{
        background: `linear-gradient(160deg, ${T.subtle}, ${T.accent}30)`,
        padding: '12px 22px 24px',
        borderBottomLeftRadius: 32, borderBottomRightRadius: 32,
      }}>
        <div style={{ display: 'flex', justifyContent: 'space-between' }}>
          <BackBtn onClick={() => nav.back()}/>
          <div style={{ display: 'flex', gap: 8 }}>
            <RoundBtn>{Icon.share('#2D2A26')}</RoundBtn>
          </div>
        </div>
        <div style={{ marginTop: 8 }}>
          <div style={{ fontFamily: 'Poppins', fontSize: 11, fontWeight: 600, color: 'rgba(45,42,38,0.7)', letterSpacing: 0.6, textTransform: 'uppercase' }}>Mi progreso</div>
          <div style={{ fontFamily: 'Poppins', fontSize: 26, fontWeight: 600, color: '#2D2A26', marginTop: 4, letterSpacing: -0.5 }}>Tu transformación 💗</div>
          <div style={{ fontFamily: 'Poppins', fontSize: 12, color: 'rgba(45,42,38,0.6)', marginTop: 6, lineHeight: 1.4 }}>Lleva tu propio registro privado. Solo tú decides qué compartir.</div>
        </div>
      </div>

      {/* Segmented */}
      <div style={{
        margin: '18px 18px 0', padding: 4,
        background: T.subtle, borderRadius: 12, display: 'flex', position: 'relative',
      }}>
        <div style={{
          position: 'absolute', top: 4, bottom: 4,
          left: tab === 'fotos' ? 4 : 'calc(50% + 0px)',
          width: 'calc(50% - 4px)', background: T.card, borderRadius: 9,
          boxShadow: '0 1px 3px rgba(0,0,0,0.06)',
          transition: 'left 240ms cubic-bezier(.2,.8,.2,1)',
        }}/>
        {[
          { id: 'fotos', label: 'Fotos' },
          { id: 'medidas', label: 'Medidas' },
        ].map(s => (
          <button key={s.id} onClick={() => setTab(s.id)} style={{
            flex: 1, padding: '8px', border: 'none', background: 'transparent', cursor: 'pointer',
            position: 'relative', zIndex: 1,
            fontFamily: 'Poppins', fontSize: 12, fontWeight: 600,
            color: tab === s.id ? T.text : T.muted, letterSpacing: -0.1,
          }}>{s.label}</button>
        ))}
      </div>

      {tab === 'fotos' ? <FotosTab T={T}/> : <MedidasTab T={T} latest={latest} prev={prev}/>}
    </div>
  );
}

function FotosTab({ T }) {
  return (
    <div>
      <div style={{ padding: '18px 22px 4px', display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
        <span style={{ fontFamily: 'Poppins', fontSize: 11, color: T.muted, fontWeight: 600, letterSpacing: 0.5, textTransform: 'uppercase' }}>Tu timeline</span>
        <button onClick={() => window.__pauNav && window.__pauNav.toast('Subiendo foto al timeline 📸', { icon: '↗' })} style={{
          padding: '6px 12px', border: 'none', borderRadius: 999, cursor: 'pointer',
          background: T.accent, color: '#fff',
          fontFamily: 'Poppins', fontSize: 11, fontWeight: 600,
        }}>＋ Nueva foto</button>
      </div>

      <div style={{ padding: '12px 18px 0', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
        {FOTOS_PROGRESO.map(p => (
          <div key={p.id} style={{
            aspectRatio: '3 / 4', borderRadius: 16, position: 'relative', overflow: 'hidden',
            background: `linear-gradient(160deg, ${p.color}, ${T.accent}50)`,
          }}>
            <div style={{
              position: 'absolute', inset: 0,
              background: 'repeating-linear-gradient(45deg, rgba(255,255,255,0.15) 0px, rgba(255,255,255,0.15) 2px, transparent 2px, transparent 10px)',
            }}/>
            <div style={{
              position: 'absolute', top: '45%', left: '50%', transform: 'translate(-50%,-50%)',
              fontSize: 40, opacity: 0.7,
            }}>📸</div>
            <div style={{
              position: 'absolute', top: 8, left: 8, padding: '3px 8px',
              background: 'rgba(45,42,38,0.7)', backdropFilter: 'blur(8px)', borderRadius: 999,
              fontFamily: 'Poppins', fontSize: 9, color: '#fff', fontWeight: 600, letterSpacing: 0.4, textTransform: 'uppercase',
            }}>{p.tag}</div>
            <div style={{
              position: 'absolute', top: 8, right: 8,
              padding: '3px 8px', borderRadius: 999, backdropFilter: 'blur(8px)',
              background: p.shared ? 'rgba(217,71,126,0.85)' : 'rgba(45,42,38,0.7)',
              fontFamily: 'Poppins', fontSize: 9, color: '#fff', fontWeight: 600,
              display: 'flex', alignItems: 'center', gap: 3,
            }}>{p.shared ? '👥 Pública' : '🔒 Privada'}</div>
            <div style={{
              position: 'absolute', bottom: 8, left: 8, right: 8,
              fontFamily: 'Poppins', fontSize: 11, fontWeight: 600, color: '#fff',
              textShadow: '0 1px 4px rgba(0,0,0,0.4)',
            }}>{p.date}</div>
          </div>
        ))}
      </div>

      {/* Compare CTA */}
      <div style={{
        margin: '20px 18px 0', padding: '16px',
        background: T.card, borderRadius: 18, border: T.border,
        display: 'flex', alignItems: 'center', gap: 12,
      }}>
        <span style={{ fontSize: 28 }}>⚖️</span>
        <div style={{ flex: 1 }}>
          <div style={{ fontFamily: 'Poppins', fontSize: 13, fontWeight: 600, color: T.text }}>Compara antes y después</div>
          <div style={{ fontFamily: 'Poppins', fontSize: 11, color: T.muted, marginTop: 1 }}>Slider lado a lado de dos fotos</div>
        </div>
        <button onClick={() => window.__pauNav && window.__pauNav.toast('Selecciona 2 fotos para comparar', { icon: '⚖️' })} style={{
          padding: '8px 14px', border: 'none', borderRadius: 999, cursor: 'pointer',
          background: T.subtle, color: T.text,
          fontFamily: 'Poppins', fontSize: 12, fontWeight: 600,
        }}>Comparar</button>
      </div>

      <div style={{
        margin: '14px 18px 0', padding: '14px 16px',
        background: 'rgba(168,197,160,0.12)', borderRadius: 14,
        display: 'flex', alignItems: 'center', gap: 10,
      }}>
        <span style={{ fontSize: 16 }}>🔒</span>
        <span style={{ fontFamily: 'Poppins', fontSize: 11, color: T.text, lineHeight: 1.4 }}>
          Tus fotos son <b>privadas por defecto</b>. Solo se publican en la comunidad si tú decides marcarlas como públicas.
        </span>
      </div>
    </div>
  );
}

function MedidasTab({ T, latest, prev }) {
  const fields = [
    { k: 'peso',    l: 'Peso',     u: 'kg' },
    { k: 'cintura', l: 'Cintura',  u: 'cm' },
    { k: 'cadera',  l: 'Cadera',   u: 'cm' },
    { k: 'brazo',   l: 'Brazo',    u: 'cm' },
    { k: 'muslo',   l: 'Muslo',    u: 'cm' },
  ];

  return (
    <div>
      <div style={{ padding: '18px 22px 4px', display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
        <span style={{ fontFamily: 'Poppins', fontSize: 11, color: T.muted, fontWeight: 600, letterSpacing: 0.5, textTransform: 'uppercase' }}>Última medición · {latest.date.toLowerCase()}</span>
        <button onClick={() => window.__pauNav && window.__pauNav.toast('Tomando medidas hoy 📏', { icon: '✏️' })} style={{
          padding: '6px 12px', border: 'none', borderRadius: 999, cursor: 'pointer',
          background: T.accent, color: '#fff',
          fontFamily: 'Poppins', fontSize: 11, fontWeight: 600,
        }}>＋ Medir hoy</button>
      </div>

      <div style={{ padding: '14px 18px 0', display: 'flex', flexDirection: 'column', gap: 10 }}>
        {fields.map(f => {
          const cur = latest[f.k];
          const before = prev[f.k];
          const delta = cur - before;
          const better = delta < 0; // pérdida = mejor (interpretación simple)
          return (
            <div key={f.k} style={{
              padding: '14px 18px', background: T.card, borderRadius: 16, border: T.border,
              display: 'flex', alignItems: 'center', gap: 14,
            }}>
              <div style={{ flex: 1 }}>
                <div style={{ fontFamily: 'Poppins', fontSize: 12, color: T.muted, fontWeight: 500 }}>{f.l}</div>
                <div style={{ display: 'flex', alignItems: 'baseline', gap: 4, marginTop: 2 }}>
                  <span style={{ fontFamily: 'Poppins', fontSize: 22, fontWeight: 700, color: T.text, letterSpacing: -0.5 }}>{cur}</span>
                  <span style={{ fontFamily: 'Poppins', fontSize: 12, color: T.muted, fontWeight: 500 }}>{f.u}</span>
                </div>
              </div>
              <div style={{
                padding: '6px 10px', borderRadius: 999,
                background: better ? 'rgba(168,197,160,0.18)' : T.subtle,
                color: better ? '#5C7A56' : T.muted,
                fontFamily: 'Poppins', fontSize: 11, fontWeight: 600,
              }}>{delta > 0 ? '+' : ''}{delta.toFixed(1)} {f.u}</div>
            </div>
          );
        })}
      </div>

      <div style={{ padding: '24px 22px 8px' }}>
        <span style={{ fontFamily: 'Poppins', fontSize: 11, color: T.muted, fontWeight: 600, letterSpacing: 0.5, textTransform: 'uppercase' }}>Histórico</span>
      </div>
      <div style={{ margin: '0 18px', background: T.card, borderRadius: 18, overflow: 'hidden', border: T.border }}>
        {MEDIDAS.map((m, i, arr) => (
          <div key={i} style={{
            padding: '12px 16px',
            display: 'flex', alignItems: 'center', justifyContent: 'space-between',
            borderBottom: i < arr.length-1 ? (T.dark ? '0.5px solid rgba(255,255,255,0.06)' : '0.5px solid rgba(0,0,0,0.05)') : 'none',
          }}>
            <span style={{ fontFamily: 'Poppins', fontSize: 12, fontWeight: 500, color: T.text }}>{m.date}</span>
            <span style={{ fontFamily: 'Poppins', fontSize: 11, color: T.muted }}>{m.peso}kg · {m.cintura}cm cintura</span>
          </div>
        ))}
      </div>
    </div>
  );
}

// ═════════════════════════════════════════════════════════════
// HISTORIAL
// ═════════════════════════════════════════════════════════════
function HistorialScreen({ theme, nav }) {
  const T = theme;
  const [filter, setFilter] = useS3('todo');
  const filtered = HISTORIAL.filter(h => filter === 'todo' || h.kind === filter);
  const kindColor = { rutina: T.accent, reto: '#C9956B', receta: '#A8C5A0' };
  const kindLabel = { rutina: 'Rutina', reto: 'Reto', receta: 'Receta' };

  return (
    <div style={{ paddingBottom: 110 }}>
      <div style={{
        background: T.subtle, padding: '12px 22px 24px',
        borderBottomLeftRadius: 32, borderBottomRightRadius: 32,
      }}>
        <BackBtn onClick={() => nav.back()}/>
        <div style={{ marginTop: 10 }}>
          <div style={{ fontFamily: 'Poppins', fontSize: 11, fontWeight: 600, color: T.muted, letterSpacing: 0.6, textTransform: 'uppercase' }}>Tu actividad</div>
          <div style={{ fontFamily: 'Poppins', fontSize: 26, fontWeight: 600, color: T.text, marginTop: 4, letterSpacing: -0.5 }}>Historial completo</div>
          <div style={{ fontFamily: 'Poppins', fontSize: 12, color: T.muted, marginTop: 4 }}>Todo lo que has completado</div>
        </div>
      </div>

      <div style={{ display: 'flex', gap: 8, padding: '18px 22px 4px', overflowX: 'auto' }} className="hide-scroll">
        {['todo', 'rutina', 'reto', 'receta'].map(f => (
          <Pill key={f} active={filter===f} onClick={() => setFilter(f)} dark={T.dark} color={T.accent}>
            {f === 'todo' ? 'Todo' : kindLabel[f] + 's'}
          </Pill>
        ))}
      </div>

      <div style={{ padding: '14px 18px 0', display: 'flex', flexDirection: 'column', gap: 10 }}>
        {filtered.map((h, i) => (
          <div key={i} style={{
            padding: '14px 16px', background: T.card, borderRadius: 16, border: T.border,
            display: 'flex', alignItems: 'center', gap: 12,
          }}>
            <div style={{
              width: 44, height: 44, borderRadius: 12, flexShrink: 0,
              background: `${kindColor[h.kind]}18`,
              display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 22,
            }}>{h.emoji}</div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                <span style={{
                  fontFamily: 'Poppins', fontSize: 9, fontWeight: 700, letterSpacing: 0.6, textTransform: 'uppercase',
                  color: kindColor[h.kind],
                }}>{kindLabel[h.kind]}</span>
                <span style={{ fontFamily: 'Poppins', fontSize: 10, color: T.muted }}>· {h.when}</span>
              </div>
              <div style={{ fontFamily: 'Poppins', fontSize: 14, fontWeight: 600, color: T.text, marginTop: 2, letterSpacing: -0.2, lineHeight: 1.2 }}>{h.title}</div>
              <div style={{ fontFamily: 'Poppins', fontSize: 11, color: T.muted, marginTop: 2 }}>{h.meta}</div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

// ═════════════════════════════════════════════════════════════
// RUTINA DETAIL — rutina suelta
// ═════════════════════════════════════════════════════════════
function RutinaDetailScreen({ rutinaId, theme, isPremium, nav }) {
  const T = theme;
  const r = RUTINAS.find(x => x.id === rutinaId);

  function openPlayer() {
    const mockVideo = { id: r.id, title: r.title, minutes: r.minutes, kind: r.muscle };
    const mockReto = { title: 'Rutinas sueltas', emoji: r.emoji, color: T.accent, bg: T.subtle, days: 1 };
    nav.openModal(<VideoPlayer
      video={mockVideo} reto={mockReto} T={T} isPremium={isPremium}
      onClose={() => { nav.closeModal(); openRate(); }}
      onFinish={() => {}}
    />);
  }

  function openRate() {
    nav.openModal(<RateWorkoutModal
      open target={`${r.title} · ${r.minutes} min`}
      T={T} accent={T.accent} retoColor={T.accent}
      onClose={() => nav.closeModal()}
      onSave={() => {
        nav.closeModal();
        nav.toast('Rutina puntuada 💗 +1 a tu historial', { icon: '✓' });
      }}
    />);
  }

  return (
    <div style={{ paddingBottom: 110 }}>
      <div style={{
        background: `linear-gradient(160deg, ${T.subtle}, ${T.accent}50)`,
        padding: '12px 22px 30px',
        borderBottomLeftRadius: 32, borderBottomRightRadius: 32,
        position: 'relative', overflow: 'hidden',
      }}>
        <div style={{
          position: 'absolute', top: -30, right: -40, width: 180, height: 180,
          borderRadius: '50%', background: `${T.accent}25`,
        }}/>
        <div style={{ display: 'flex', justifyContent: 'space-between', position: 'relative' }}>
          <BackBtn onClick={() => nav.back()}/>
          <div style={{ display: 'flex', gap: 8 }}>
            <RoundBtn>{Icon.share('#2D2A26')}</RoundBtn>
            <RoundBtn>{Icon.heart('#2D2A26')}</RoundBtn>
          </div>
        </div>
        <div style={{ marginTop: 14, position: 'relative' }}>
          <div style={{ fontSize: 64, lineHeight: 1 }}>{r.emoji}</div>
          <div style={{ marginTop: 12 }}><RetoBadge tag={r.tag} isPremium={isPremium}/></div>
          <div style={{ fontFamily: 'Poppins', fontSize: 28, fontWeight: 600, color: '#2D2A26', marginTop: 8, letterSpacing: -0.6, lineHeight: 1.1 }}>{r.title}</div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: 8 }}>
            <span style={{ fontFamily: 'Poppins', fontSize: 12, color: 'rgba(45,42,38,0.7)', fontWeight: 600 }}>{r.minutes} min</span>
            <span style={{ fontFamily: 'Poppins', fontSize: 12, color: 'rgba(45,42,38,0.7)' }}>· {r.muscle}</span>
            <span style={{ fontFamily: 'Poppins', fontSize: 12, color: 'rgba(45,42,38,0.7)' }}>· {r.level}</span>
          </div>
          <div style={{ fontFamily: 'Poppins', fontSize: 11, color: 'rgba(45,42,38,0.55)', marginTop: 4 }}>{r.equipment} · {r.views} vistas</div>
        </div>
      </div>

      <div style={{ padding: '20px 18px 0' }}>
        <button onClick={openPlayer} style={{
          width: '100%', padding: '18px',
          border: 'none', borderRadius: 16, cursor: 'pointer',
          background: T.accent, color: '#fff',
          fontFamily: 'Poppins', fontSize: 15, fontWeight: 600,
          display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
          boxShadow: `0 6px 18px ${T.accent}55`,
        }}>▶ Empezar rutina · {r.minutes} min</button>
      </div>

      <div style={{ padding: '20px 22px 0' }}>
        <div style={{ fontFamily: 'Poppins', fontSize: 13, color: T.text, lineHeight: 1.6 }}>
          Rutina suelta para hacer cuando tengas un rato libre. Sin compromiso, sin reto, simplemente activa el cuerpo 💗
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { LogrosScreen, ProgresoScreen, HistorialScreen, RutinaDetailScreen });
