// Pau Fit — Detail screens (DetalleReto, DetalleReceta, Paywall)

const { useState: useS2, useEffect: useE2 } = React;

// ═════════════════════════════════════════════════════════════
// DETALLE RETO — la pantalla estrella
// ═════════════════════════════════════════════════════════════
function DetalleRetoScreen({ retoId, theme, isPremium, nav, onComplete }) {
  const T = theme;
  const reto = RETOS.find(r => r.id === retoId);
  const isLocked = reto.tag === 'PRO' && !isPremium;

  const [selectedDay, setSelectedDay] = useS2(reto.currentDay || 1);
  const [doneVideos, setDoneVideos] = useS2(new Set());
  const [confetti, setConfetti] = useS2(false);
  const [myReview, setMyReview] = useS2(null);
  const [localCompleted, setLocalCompleted] = useS2(new Set(reto.completed || []));

  const videos = VIDEOS_BY_DAY[selectedDay] || VIDEOS_BY_DAY[5];
  const completed = Array.from(localCompleted);
  const allDone = videos.every(v => doneVideos.has(v.id));
  const progress = completed.length / reto.days;
  const totalMinutes = videos.reduce((a, v) => a + v.minutes, 0);

  function completeDay() {
    setLocalCompleted(prev => {
      const next = new Set(prev);
      next.add(selectedDay);
      return next;
    });
    setDoneVideos(new Set());
    // Avanza al siguiente día si existe
    if (selectedDay < reto.days) {
      setTimeout(() => setSelectedDay(selectedDay + 1), 250);
    }
  }

  function toggleVideo(id) {
    setDoneVideos(prev => {
      const next = new Set(prev);
      if (next.has(id)) next.delete(id);
      else next.add(id);
      if (videos.every(v => next.has(v.id))) {
        setConfetti(true);
        setTimeout(() => setConfetti(false), 1800);
      }
      return next;
    });
  }

  function markVideoDone(id) {
    setDoneVideos(prev => {
      if (prev.has(id)) return prev;
      const next = new Set(prev);
      next.add(id);
      if (videos.every(v => next.has(v.id))) {
        setConfetti(true);
        setTimeout(() => setConfetti(false), 1800);
      }
      return next;
    });
  }

  function openPlayer(v) {
    nav.openModal(<VideoPlayer
      video={v} reto={reto} T={T} isPremium={isPremium}
      onClose={() => nav.closeModal()}
      onFinish={() => markVideoDone(v.id)}
    />);
  }

  function openShare() {
    nav.openModal(<SharePhotoCard
      open reto={reto} day={selectedDay} totalMinutes={totalMinutes}
      T={T} accent={reto.color}
      onClose={() => nav.closeModal()}
    />);
  }

  function openRateThenShare() {
    nav.openModal(<RateWorkoutModal
      open target={`Día ${selectedDay} · ${reto.title}`}
      T={T} accent={T.accent} retoColor={reto.color}
      onClose={() => { nav.closeModal(); completeDay(); openShare(); }}
      onSave={(r) => {
        nav.closeModal();
        nav.toast('Puntuación guardada 💗', { icon: '✓' });
        completeDay();
        setTimeout(() => openShare(), 200);
      }}
    />);
  }

  function openWriteReview() {
    nav.openModal(<WriteReviewModal
      open target={reto.title} T={T} accent={reto.color}
      onClose={() => nav.closeModal()}
      onSubmit={(r) => {
        setMyReview({ ...r, date: 'ahora', initials: 'P', user: STATS.name });
        nav.closeModal();
      }}
    />);
  }

  if (isLocked) return <PaywallScreen theme={T} nav={nav} fromReto={reto} onComplete={onComplete}/>;

  return (
    <div style={{ paddingBottom: 110, position: 'relative' }}>
      <Confetti show={confetti}/>

      {/* Hero header */}
      <div style={{
        background: `linear-gradient(160deg, ${reto.bg} 0%, ${reto.color}40 100%)`,
        padding: '12px 22px 24px',
        borderBottomLeftRadius: 32, borderBottomRightRadius: 32,
        position: 'relative', overflow: 'hidden',
      }}>
        <div style={{
          position: 'absolute', top: -30, right: -40, width: 180, height: 180,
          borderRadius: '50%', background: `${reto.color}30`,
        }}/>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', position: 'relative' }}>
          <BackBtn onClick={() => nav.back()}/>
          <div style={{ display: 'flex', gap: 8 }}>
            <RoundBtn onClick={() => nav.toast('Enlace copiado 💗', { icon: '↗' })}>{Icon.share('#2D2A26')}</RoundBtn>
            <RoundBtn onClick={() => nav.toast('Guardado en favoritos 💗', { icon: '❤️' })}>{Icon.heart('#2D2A26')}</RoundBtn>
          </div>
        </div>
        <div style={{ marginTop: 16, position: 'relative' }}>
          <div style={{ fontSize: 56, lineHeight: 1 }}>{reto.emoji}</div>
          <div style={{ marginTop: 12 }}>
            <RetoBadge tag={reto.tag} isPremium={isPremium}/>
          </div>
          <div style={{ fontFamily: 'Poppins', fontSize: 28, fontWeight: 600, color: '#2D2A26', marginTop: 8, letterSpacing: -0.6, lineHeight: 1.1 }}>{reto.title}</div>
          <div style={{ fontFamily: 'Poppins', fontSize: 13, color: 'rgba(45,42,38,0.7)', marginTop: 6, lineHeight: 1.4 }}>{reto.desc}</div>
        </div>
        {/* Progress */}
        <div style={{ marginTop: 18, padding: '14px 16px', background: 'rgba(255,255,255,0.5)', backdropFilter: 'blur(10px)', borderRadius: 16 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
            <span style={{ fontFamily: 'Poppins', fontSize: 11, fontWeight: 600, color: '#2D2A26', letterSpacing: 0.4, textTransform: 'uppercase' }}>Tu progreso</span>
            <span style={{ fontFamily: 'Poppins', fontSize: 13, fontWeight: 600, color: '#2D2A26' }}>{completed.length}/{reto.days} días</span>
          </div>
          <div style={{ marginTop: 8, height: 6, background: 'rgba(45,42,38,0.1)', borderRadius: 999, overflow: 'hidden' }}>
            <div style={{ width: `${progress*100}%`, height: '100%', background: '#2D2A26', borderRadius: 999, transition: 'width 600ms ease' }}/>
          </div>
        </div>
      </div>

      {/* Stats row */}
      <div style={{ display: 'flex', justifyContent: 'space-around', padding: '20px 18px 0' }}>
        <SmallStat v={reto.days} l="días" T={T}/>
        <SmallStat v={`~${reto.minPerDay}`} l="min/día" T={T}/>
        <SmallStat v={reto.intensity.split(' ')[0]} l="intensidad" T={T}/>
      </div>

      {/* Day selector */}
      <div style={{
        margin: '24px 0 0', padding: '0 22px',
        fontFamily: 'Poppins', fontSize: 18, fontWeight: 600, color: T.text, letterSpacing: -0.3,
      }}>Día {selectedDay}</div>
      <div style={{
        display: 'flex', gap: 8, padding: '12px 18px 4px',
        overflowX: 'auto', scrollSnapType: 'x mandatory',
      }} className="hide-scroll">
        {Array.from({ length: reto.days }, (_, i) => i + 1).map(d => {
          const isCompleted = completed.includes(d);
          const isSelected = d === selectedDay;
          const isToday = d === reto.currentDay;
          const isLocked = d > 1 && !completed.includes(d - 1) && d !== reto.currentDay;
          return (
            <button key={d} onClick={() => !isLocked && setSelectedDay(d)} disabled={isLocked} style={{
              flexShrink: 0, width: 52, height: 64,
              cursor: isLocked ? 'not-allowed' : 'pointer', borderRadius: 16,
              background: isSelected ? reto.color : (isCompleted ? T.subtle : T.card),
              color: isSelected ? '#fff' : (isCompleted ? '#5C7A56' : (isLocked ? T.muted : T.text)),
              display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 2,
              fontFamily: 'Poppins', position: 'relative',
              border: isToday && !isSelected ? `1.5px solid ${reto.color}` : (isLocked ? `1.5px dashed ${T.muted}40` : T.border),
              opacity: isLocked ? 0.55 : 1,
              transition: 'all 200ms ease',
            }}>
              <span style={{ fontSize: 10, fontWeight: 500, opacity: 0.7, letterSpacing: 0.3, textTransform: 'uppercase' }}>Día</span>
              <span style={{ fontSize: 18, fontWeight: 600, letterSpacing: -0.3 }}>{d}</span>
              {isCompleted && !isSelected && (
                <div style={{
                  position: 'absolute', top: 6, right: 6,
                  width: 14, height: 14, borderRadius: 999, background: '#A8C5A0',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                }}>{Icon.check('#fff', 10)}</div>
              )}
              {isLocked && (
                <div style={{
                  position: 'absolute', top: 6, right: 6,
                  width: 14, height: 14, borderRadius: 999,
                  background: T.muted, opacity: 0.5,
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                }}>{Icon.lock('#fff', 8)}</div>
              )}
            </button>
          );
        })}
      </div>

      <div style={{ padding: '6px 22px 0', fontFamily: 'Poppins', fontSize: 11, color: T.muted, lineHeight: 1.4 }}>
        Los días se desbloquean al completar el anterior 🔒
      </div>

      {/* Videos list */}
      <div style={{ padding: '20px 18px 0', display: 'flex', flexDirection: 'column', gap: 10 }}>
        {videos.map(v => {
          const done = doneVideos.has(v.id);
          return (
            <div key={v.id} onClick={() => openPlayer(v)} style={{
              background: T.card, borderRadius: 18, padding: 14,
              display: 'flex', alignItems: 'center', gap: 12, cursor: 'pointer',
              border: T.border,
              opacity: done ? 0.65 : 1, transition: 'opacity 200ms ease',
            }}>
              <button onClick={(e) => { e.stopPropagation(); toggleVideo(v.id); }} style={{
                width: 28, height: 28, borderRadius: 999, flexShrink: 0,
                border: done ? 'none' : (T.dark ? '1.5px solid rgba(255,255,255,0.25)' : '1.5px solid rgba(0,0,0,0.15)'),
                background: done ? '#A8C5A0' : 'transparent',
                cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center',
                transition: 'all 200ms ease',
              }}>{done && Icon.check('#fff', 14)}</button>
              <div style={{
                width: 56, height: 40, borderRadius: 10, flexShrink: 0,
                background: `linear-gradient(135deg, ${reto.bg}, ${reto.color}80)`,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                position: 'relative',
              }}>
                <div style={{ width: 24, height: 24, borderRadius: 999, background: 'rgba(255,255,255,0.9)', display: 'flex', alignItems: 'center', justifyContent: 'center', paddingLeft: 2 }}>
                  {Icon.play('#2D2A26')}
                </div>
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontFamily: 'Poppins', fontSize: 10, color: T.muted, fontWeight: 500, letterSpacing: 0.5, textTransform: 'uppercase' }}>{v.kind}</div>
                <div style={{
                  fontFamily: 'Poppins', fontSize: 14, fontWeight: 600, color: T.text,
                  marginTop: 1, letterSpacing: -0.2,
                  textDecoration: done ? 'line-through' : 'none',
                  textDecorationColor: T.muted,
                }}>{v.title}</div>
                <div style={{ fontFamily: 'Poppins', fontSize: 11, color: T.muted, marginTop: 1 }}>{v.minutes} min</div>
              </div>
            </div>
          );
        })}
      </div>

      {/* Complete day button */}
      <div style={{ padding: '20px 18px 0' }}>
        <button disabled={!allDone} onClick={() => allDone && openRateThenShare()} style={{
          width: '100%', padding: '16px',
          border: 'none', borderRadius: 16, cursor: allDone ? 'pointer' : 'not-allowed',
          background: allDone ? reto.color : T.subtle,
          color: allDone ? '#fff' : T.muted,
          fontFamily: 'Poppins', fontSize: 15, fontWeight: 600, letterSpacing: -0.1,
          transition: 'all 200ms ease',
          boxShadow: allDone ? `0 6px 18px ${reto.color}55` : 'none',
        }}>
          {allDone ? `✓ Completar día ${selectedDay} · ${totalMinutes} min` : `Marca todos los videos para completar`}
        </button>
      </div>

      {/* Reviews */}
      <ReviewsSection
        id={reto.id} T={T} accent={reto.color}
        myReview={myReview}
        onWrite={openWriteReview}
      />
    </div>
  );
}

function BackBtn({ onClick }) {
  return (
    <button onClick={onClick} style={{
      width: 36, height: 36, borderRadius: 999, border: 'none',
      background: 'rgba(255,255,255,0.6)', backdropFilter: 'blur(10px)',
      cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center',
    }}>{Icon.back('#2D2A26')}</button>
  );
}

function RoundBtn({ children, onClick }) {
  return (
    <button onClick={onClick || (() => window.__pauNav && window.__pauNav.toast('Próximamente', { icon: '⏳' }))} style={{
      width: 36, height: 36, borderRadius: 999, border: 'none',
      background: 'rgba(255,255,255,0.6)', backdropFilter: 'blur(10px)',
      cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center',
    }}>{children}</button>
  );
}

function SmallStat({ v, l, T }) {
  return (
    <div style={{ textAlign: 'center', flex: 1 }}>
      <div style={{ fontFamily: 'Poppins', fontSize: 20, fontWeight: 700, color: T.text, letterSpacing: -0.5 }}>{v}</div>
      <div style={{ fontFamily: 'Poppins', fontSize: 10, color: T.muted, marginTop: 2, fontWeight: 500, letterSpacing: 0.5, textTransform: 'uppercase' }}>{l}</div>
    </div>
  );
}

function SocialChip({ emoji, value }) {
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 4,
      padding: '5px 10px', borderRadius: 999,
      background: 'rgba(255,255,255,0.55)', backdropFilter: 'blur(8px)',
      fontFamily: 'Poppins', fontSize: 11, fontWeight: 600, color: '#2D2A26',
    }}>
      <span style={{ fontSize: 12 }}>{emoji}</span>
      {value}
    </span>
  );
}

// ═════════════════════════════════════════════════════════════
// Video Player (mocked)
// ═════════════════════════════════════════════════════════════
function VideoPlayer({ video, reto, onClose, onFinish, T, isPremium = false }) {
  const [time, setTime] = useS2(0);
  const [finishedNotice, setFinishedNotice] = useS2(false);
  const [audioMode, setAudioMode] = useS2('full'); // full | voice | silent
  useE2(() => {
    const total = video.minutes * 60;
    const i = setInterval(() => setTime(t => {
      const next = Math.min(t + 8, total);  // accelerated for demo
      if (next >= total && t < total) {
        // just finished
        onFinish && onFinish();
        setFinishedNotice(true);
      }
      return next;
    }), 1000);
    return () => clearInterval(i);
  }, [video]);
  const pct = (time / (video.minutes * 60)) * 100;
  const fmt = (s) => `${Math.floor(s/60)}:${String(s%60).padStart(2,'0')}`;
  const finished = time >= video.minutes * 60;

  const audioModes = [
    { id: 'full',   label: 'Música Pau', sub: 'Música + voz Pau', icon: '🎵' },
    { id: 'voice',  label: 'Solo voz',   sub: 'Pon tu música',     icon: '🎙️' },
    { id: 'silent', label: 'Silencio',   sub: 'Sin audio',          icon: '🔇' },
  ];

  return (
    <div style={{
      position: 'absolute', inset: 0, background: '#000', zIndex: 200,
      display: 'flex', flexDirection: 'column',
      animation: 'fade-in 240ms ease',
    }}>
      {/* Top bar */}
      <div style={{
        padding: '50px 18px 12px', display: 'flex', alignItems: 'center', gap: 12,
      }}>
        <button onClick={onClose} style={{
          width: 36, height: 36, borderRadius: 999, border: 'none',
          background: 'rgba(255,255,255,0.15)', cursor: 'pointer',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>{Icon.close('#fff')}</button>
        <div style={{ flex: 1 }}>
          <div style={{ fontFamily: 'Poppins', fontSize: 10, color: 'rgba(255,255,255,0.5)', fontWeight: 500, letterSpacing: 0.6, textTransform: 'uppercase' }}>{reto.title}</div>
          <div style={{ fontFamily: 'Poppins', fontSize: 14, fontWeight: 600, color: '#fff', marginTop: 2 }}>{video.title}</div>
        </div>
      </div>
      {/* Video area */}
      <div style={{
        flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center',
        background: `radial-gradient(circle at 50% 50%, ${reto.color}40, #000 70%)`,
        position: 'relative',
      }}>
        <div style={{ fontSize: 90, opacity: 0.7 }}>{reto.emoji}</div>
        <div style={{
          position: 'absolute', bottom: 80, left: '50%', transform: 'translateX(-50%)',
          fontFamily: 'Poppins', fontSize: 11, color: 'rgba(255,255,255,0.5)', letterSpacing: 1, textTransform: 'uppercase',
        }}>YouTube embed · {video.kind}</div>

        {finished && finishedNotice && (
          <div style={{
            position: 'absolute', top: 24, left: '50%', transform: 'translateX(-50%)',
            padding: '10px 16px', borderRadius: 999,
            background: 'rgba(168,197,160,0.95)',
            display: 'flex', alignItems: 'center', gap: 8,
            animation: 'slide-down 360ms cubic-bezier(.2,.8,.2,1)',
          }}>
            <div style={{
              width: 22, height: 22, borderRadius: 999, background: '#fff',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}>{Icon.check('#5C7A56', 14)}</div>
            <span style={{ fontFamily: 'Poppins', fontSize: 13, fontWeight: 600, color: '#2D2A26' }}>Marcado automático · ¡Bien hecho!</span>
          </div>
        )}
      </div>

      {/* Audio modes (premium) */}
      <div style={{ padding: '0 18px 12px' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 8 }}>
          <span style={{ fontFamily: 'Poppins', fontSize: 10, color: 'rgba(255,255,255,0.5)', fontWeight: 600, letterSpacing: 0.6, textTransform: 'uppercase' }}>Audio</span>
          {!isPremium && (
            <span style={{
              padding: '2px 6px', borderRadius: 5, background: '#C9956B',
              fontFamily: 'Poppins', fontSize: 8, fontWeight: 700, color: '#2D2A26', letterSpacing: 0.6,
            }}>PRO</span>
          )}
        </div>
        <div style={{ display: 'flex', gap: 6 }}>
          {audioModes.map(m => {
            const locked = !isPremium && m.id !== 'full';
            const sel = audioMode === m.id;
            return (
              <button key={m.id} onClick={() => !locked && setAudioMode(m.id)}
                disabled={locked} style={{
                flex: 1, padding: '10px 8px',
                border: sel ? '1.5px solid #fff' : '1.5px solid rgba(255,255,255,0.12)',
                background: sel ? 'rgba(255,255,255,0.14)' : 'rgba(255,255,255,0.04)',
                borderRadius: 12, cursor: locked ? 'not-allowed' : 'pointer',
                opacity: locked ? 0.45 : 1,
                position: 'relative',
                display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 2,
              }}>
                <span style={{ fontSize: 16 }}>{m.icon}</span>
                <span style={{ fontFamily: 'Poppins', fontSize: 10, fontWeight: 600, color: '#fff' }}>{m.label}</span>
                <span style={{ fontFamily: 'Poppins', fontSize: 8, color: 'rgba(255,255,255,0.55)' }}>{m.sub}</span>
                {locked && (
                  <div style={{ position: 'absolute', top: 6, right: 6 }}>{Icon.lock('rgba(255,255,255,0.6)', 9)}</div>
                )}
              </button>
            );
          })}
        </div>
      </div>

      {/* Controls */}
      <div style={{ padding: '0 22px 50px' }}>
        <div style={{ height: 3, background: 'rgba(255,255,255,0.2)', borderRadius: 999, overflow: 'hidden' }}>
          <div style={{ width: `${pct}%`, height: '100%', background: finished ? '#A8C5A0' : '#fff', transition: 'background 240ms ease' }}/>
        </div>
        <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 8 }}>
          <span style={{ fontFamily: 'Poppins', fontSize: 11, color: 'rgba(255,255,255,0.7)' }}>{fmt(time)}</span>
          <span style={{ fontFamily: 'Poppins', fontSize: 11, color: 'rgba(255,255,255,0.7)' }}>{fmt(video.minutes * 60)}</span>
        </div>
        <div style={{ display: 'flex', justifyContent: 'center', gap: 28, marginTop: 14, alignItems: 'center' }}>
          <button style={{ background: 'transparent', border: 'none', cursor: 'pointer', color: '#fff', fontFamily: 'Poppins', fontSize: 13 }}>−15s</button>
          <div style={{
            width: 64, height: 64, borderRadius: 999, background: '#fff',
            display: 'flex', alignItems: 'center', justifyContent: 'center', paddingLeft: 4,
          }}>
            {finished ? Icon.check('#000', 24) : <svg width="22" height="22" viewBox="0 0 22 22"><path d="M5 3l13 8-13 8V3z" fill="#000"/></svg>}
          </div>
          <button style={{ background: 'transparent', border: 'none', cursor: 'pointer', color: '#fff', fontFamily: 'Poppins', fontSize: 13 }}>+15s</button>
        </div>
        {finished && (
          <button onClick={onClose} style={{
            marginTop: 14, width: '100%', padding: '14px',
            border: 'none', borderRadius: 14, cursor: 'pointer',
            background: '#A8C5A0', color: '#2D2A26',
            fontFamily: 'Poppins', fontSize: 14, fontWeight: 600,
          }}>✓ Volver al reto</button>
        )}
      </div>
    </div>
  );
}

// ═════════════════════════════════════════════════════════════
// DETALLE RECETA
// ═════════════════════════════════════════════════════════════
function DetalleRecetaScreen({ recetaId, theme, nav }) {
  const T = theme;
  const r = RECETAS.find(x => x.id === recetaId);
  const [checked, setChecked] = useS2(new Set());
  const [fav, setFav] = useS2(false);
  const [myReview, setMyReview] = useS2(null);

  function toggle(i) {
    setChecked(prev => {
      const next = new Set(prev);
      if (next.has(i)) next.delete(i); else next.add(i);
      return next;
    });
  }

  function openWriteReview() {
    nav.openModal(<WriteReviewModal
      open target={r.title} T={T} accent={T.accent}
      onClose={() => nav.closeModal()}
      onSubmit={(rev) => {
        setMyReview({ ...rev, date: 'ahora', initials: 'P', user: STATS.name });
        nav.closeModal();
      }}
    />);
  }

  return (
    <div style={{ paddingBottom: 110 }}>
      {/* Hero — usa imagen real si la tiene */}
      {r.image ? (
        <div style={{ position: 'relative' }}>
          <div style={{
            height: 320, backgroundImage: `url(${r.image})`,
            backgroundSize: 'cover', backgroundPosition: 'center',
            borderBottomLeftRadius: 32, borderBottomRightRadius: 32,
          }}/>
          <div style={{
            position: 'absolute', inset: 0,
            background: 'linear-gradient(180deg, rgba(0,0,0,0.18) 0%, transparent 30%, rgba(0,0,0,0.55) 100%)',
            borderBottomLeftRadius: 32, borderBottomRightRadius: 32,
          }}/>
          <div style={{
            position: 'absolute', top: 12, left: 22, right: 22,
            display: 'flex', justifyContent: 'space-between',
          }}>
            <BackBtn onClick={() => nav.back()}/>
            <div style={{ display: 'flex', gap: 8 }}>
              <RoundBtn onClick={() => nav.toast('Enlace copiado 💗', { icon: '↗' })}>{Icon.share('#2D2A26')}</RoundBtn>
              <RoundBtn onClick={() => setFav(!fav)}>{Icon.heart(fav ? '#D4847A' : '#2D2A26', fav)}</RoundBtn>
            </div>
          </div>
          <div style={{
            position: 'absolute', bottom: 18, left: 22, right: 22,
          }}>
            <span style={{
              display: 'inline-block',
              fontFamily: 'Poppins', fontSize: 9, fontWeight: 700, letterSpacing: 1, textTransform: 'uppercase',
              color: '#2D2A26', background: 'rgba(255,255,255,0.95)', padding: '4px 8px', borderRadius: 6,
            }}>{r.category} · sync paufit.co</span>
            <div style={{ fontFamily: 'Poppins', fontSize: 26, fontWeight: 600, color: '#fff', marginTop: 8, letterSpacing: -0.6, lineHeight: 1.15, textShadow: '0 1px 8px rgba(0,0,0,0.3)' }}>{r.title}</div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 6 }}>
              <span style={{ fontFamily: 'Poppins', fontSize: 12, fontWeight: 700, color: '#F5E6C8' }}>💗 {recommendsPercent(r.id) || 96}% lo recomienda</span>
              <span style={{ fontFamily: 'Poppins', fontSize: 11, color: 'rgba(255,255,255,0.7)' }}>· {testimoniesFor(r.id).length || 0} testimonios</span>
            </div>
          </div>
        </div>
      ) : (
        <div style={{
          background: T.dark ? 'linear-gradient(160deg, #3B2F26, #2A2520)' : 'linear-gradient(160deg, #F5E6C8, #FAF3EE)',
          padding: '12px 22px 26px',
          borderBottomLeftRadius: 32, borderBottomRightRadius: 32,
          position: 'relative',
        }}>
          <div style={{ display: 'flex', justifyContent: 'space-between' }}>
            <BackBtn onClick={() => nav.back()}/>
            <div style={{ display: 'flex', gap: 8 }}>
              <RoundBtn onClick={() => nav.toast('Enlace copiado 💗', { icon: '↗' })}>{Icon.share('#2D2A26')}</RoundBtn>
              <RoundBtn onClick={() => setFav(!fav)}>{Icon.heart(fav ? '#D4847A' : '#2D2A26', fav)}</RoundBtn>
            </div>
          </div>
          <div style={{ textAlign: 'center', marginTop: 12 }}>
            <div style={{ fontSize: 80, lineHeight: 1 }}>{r.emoji}</div>
          </div>
          <div style={{ marginTop: 14 }}>
            <span style={{
              fontFamily: 'Poppins', fontSize: 10, fontWeight: 600, letterSpacing: 1, textTransform: 'uppercase',
              color: T.dark ? '#F5E6C8' : '#9C7340',
            }}>{r.category}</span>
            <div style={{ fontFamily: 'Poppins', fontSize: 26, fontWeight: 600, color: T.dark ? '#fff' : '#2D2A26', marginTop: 6, letterSpacing: -0.6, lineHeight: 1.15 }}>{r.title}</div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 6 }}>
              <span style={{ fontFamily: 'Poppins', fontSize: 12, fontWeight: 700, color: T.accent }}>💗 {recommendsPercent(r.id) || 96}% lo recomienda</span>
              <span style={{ fontFamily: 'Poppins', fontSize: 11, color: T.muted }}>· {testimoniesFor(r.id).length || 0} testimonios</span>
            </div>
          </div>
        </div>
      )}

      {/* Description */}
      <div style={{ padding: '20px 22px 0', fontFamily: 'Poppins', fontSize: 13, color: T.muted, lineHeight: 1.5 }}>{r.desc}</div>

      {/* Macros */}
      <div style={{ display: 'flex', justifyContent: 'space-around', padding: '16px 18px 0' }}>
        <SmallStat v={`${r.kcal}`} l="kcal" T={T}/>
        <SmallStat v={`${r.minutes}'`} l="prep" T={T}/>
        <SmallStat v={`${r.macros.p}g`} l="proteína" T={T}/>
        <SmallStat v={`${r.macros.c}g`} l="carbos" T={T}/>
      </div>

      {/* Ingredients */}
      <div style={{ padding: '24px 22px 0' }}>
        <div style={{ fontFamily: 'Poppins', fontSize: 18, fontWeight: 600, color: T.text, letterSpacing: -0.3 }}>Ingredientes</div>
      </div>
      <div style={{ margin: '12px 18px 0', background: T.card, borderRadius: 18, padding: 6, border: T.border }}>
        {r.ingredients.map((ing, i) => {
          const isChecked = checked.has(i);
          return (
            <button key={i} onClick={() => toggle(i)} style={{
              width: '100%', display: 'flex', alignItems: 'center', gap: 12,
              padding: '12px 14px', border: 'none', background: 'transparent', cursor: 'pointer', textAlign: 'left',
              borderRadius: 12,
            }}>
              <div style={{
                width: 22, height: 22, borderRadius: 6, flexShrink: 0,
                border: isChecked ? 'none' : (T.dark ? '1.5px solid rgba(255,255,255,0.2)' : '1.5px solid rgba(0,0,0,0.15)'),
                background: isChecked ? '#A8C5A0' : 'transparent',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
              }}>{isChecked && Icon.check('#fff', 12)}</div>
              <span style={{
                fontFamily: 'Poppins', fontSize: 14, color: T.text, fontWeight: 500,
                textDecoration: isChecked ? 'line-through' : 'none',
                opacity: isChecked ? 0.5 : 1,
              }}>{ing}</span>
            </button>
          );
        })}
      </div>

      {/* Steps */}
      <div style={{ padding: '24px 22px 0' }}>
        <div style={{ fontFamily: 'Poppins', fontSize: 18, fontWeight: 600, color: T.text, letterSpacing: -0.3 }}>Preparación</div>
      </div>
      <div style={{ margin: '12px 18px 0', display: 'flex', flexDirection: 'column', gap: 10 }}>
        {r.steps.map((s, i) => (
          <div key={i} style={{
            display: 'flex', gap: 14, padding: 14, background: T.card, borderRadius: 16, border: T.border,
          }}>
            <div style={{
              width: 26, height: 26, borderRadius: 999, background: T.accent, color: '#fff',
              display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
              fontFamily: 'Poppins', fontSize: 12, fontWeight: 700,
            }}>{i + 1}</div>
            <div style={{ fontFamily: 'Poppins', fontSize: 14, color: T.text, fontWeight: 500, lineHeight: 1.5 }}>{s}</div>
          </div>
        ))}
      </div>

      {/* Reviews */}
      <ReviewsSection
        id={r.id} T={T} accent={T.accent}
        myReview={myReview}
        onWrite={openWriteReview}
      />
    </div>
  );
}

// ═════════════════════════════════════════════════════════════
// PAYWALL
// ═════════════════════════════════════════════════════════════
function PaywallScreen({ theme, nav, fromReto, onComplete }) {
  const T = theme;
  const [plan, setPlan] = useS2('annual');

  const benefits = [
    { e: '🚫', t: 'Sin anuncios', d: 'Disfruta sin interrupciones' },
    { e: '🔓', t: 'Todos los retos premium', d: 'Más de 12 retos exclusivos' },
    { e: '🥗', t: 'Planes de alimentación', d: 'Personalizados por objetivo' },
    { e: '💗', t: 'Contenido exclusivo', d: 'Lives, recetas y guías PRO' },
  ];

  return (
    <div style={{
      paddingBottom: 110, background: '#2D2A26', minHeight: '100%',
      color: '#fff', position: 'relative', overflow: 'hidden',
    }}>
      {/* Decorative glow */}
      <div style={{
        position: 'absolute', top: -80, right: -60, width: 280, height: 280,
        borderRadius: '50%', background: 'radial-gradient(circle, rgba(201,149,107,0.4), transparent 70%)',
      }}/>
      <div style={{
        position: 'absolute', top: 60, left: -80, width: 240, height: 240,
        borderRadius: '50%', background: 'radial-gradient(circle, rgba(212,132,122,0.25), transparent 70%)',
      }}/>

      {/* Top */}
      <div style={{ padding: '12px 22px 0', position: 'relative', display: 'flex', justifyContent: 'space-between' }}>
        <button onClick={() => nav.back()} style={{
          width: 36, height: 36, borderRadius: 999, border: 'none',
          background: 'rgba(255,255,255,0.1)', cursor: 'pointer',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>{Icon.close('#fff')}</button>
      </div>

      {/* Hero */}
      <div style={{ padding: '12px 28px 0', position: 'relative', textAlign: 'center' }}>
        <div style={{ display: 'inline-flex', marginTop: 8 }}>{Icon.diamond(48, '#C9956B')}</div>
        <div style={{
          fontFamily: 'Poppins', fontSize: 30, fontWeight: 600, marginTop: 14,
          letterSpacing: -0.7, lineHeight: 1.1,
        }}>Desbloquea<br/>todo Pau Fit</div>
        <div style={{
          fontFamily: 'Poppins', fontSize: 14, color: 'rgba(245,230,200,0.7)', marginTop: 10, lineHeight: 1.4,
        }}>
          {fromReto ? <>Accede a <b style={{color:'#F5E6C8'}}>{fromReto.title}</b> y a todos los retos PRO</> : 'Resultados reales con la app fitness más cálida'}
        </div>
      </div>

      {/* Benefits */}
      <div style={{ padding: '24px 22px 0', display: 'flex', flexDirection: 'column', gap: 10, position: 'relative' }}>
        {benefits.map((b, i) => (
          <div key={i} style={{
            display: 'flex', alignItems: 'center', gap: 14,
            padding: '12px 16px', background: 'rgba(255,255,255,0.06)', borderRadius: 14,
            border: '0.5px solid rgba(245,230,200,0.1)',
          }}>
            <div style={{
              width: 36, height: 36, borderRadius: 10, background: 'rgba(201,149,107,0.18)',
              display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 18,
            }}>{b.e}</div>
            <div style={{ flex: 1 }}>
              <div style={{ fontFamily: 'Poppins', fontSize: 14, fontWeight: 600, color: '#F5E6C8' }}>{b.t}</div>
              <div style={{ fontFamily: 'Poppins', fontSize: 11, color: 'rgba(245,230,200,0.55)', marginTop: 1 }}>{b.d}</div>
            </div>
          </div>
        ))}
      </div>

      {/* Plans */}
      <div style={{ padding: '24px 22px 0', position: 'relative', display: 'flex', flexDirection: 'column', gap: 10 }}>
        <PlanCard
          id="monthly" selected={plan==='monthly'} onClick={() => setPlan('monthly')}
          title="Mensual" price="4,99€" sub="/mes"/>
        <PlanCard
          id="annual" selected={plan==='annual'} onClick={() => setPlan('annual')}
          title="Anual" price="39,99€" sub="/año" badge="AHORRA 33%" highlight/>
        {fromReto && (
          <PlanCard
            id="single" selected={plan==='single'} onClick={() => setPlan('single')}
            title={`Solo ${fromReto.title}`} price="9,99€" sub="pago único" muted/>
        )}
      </div>

      {/* CTA */}
      <div style={{ padding: '24px 22px 0', position: 'relative' }}>
        <button onClick={() => { onComplete && onComplete(); nav.back(); }} style={{
          width: '100%', padding: '18px',
          border: 'none', borderRadius: 16, cursor: 'pointer',
          background: '#C9956B', color: '#2D2A26',
          fontFamily: 'Poppins', fontSize: 15, fontWeight: 700, letterSpacing: -0.1,
          boxShadow: '0 10px 24px rgba(201,149,107,0.35)',
        }}>Empezar prueba gratis de 7 días</button>
        <div style={{
          textAlign: 'center', marginTop: 12, fontFamily: 'Poppins', fontSize: 10,
          color: 'rgba(245,230,200,0.45)', lineHeight: 1.5,
        }}>
          Renovación automática. Cancela cuando quieras desde ajustes.<br/>
          Al continuar aceptas los términos y la política de privacidad.
        </div>
      </div>
    </div>
  );
}

function PlanCard({ selected, onClick, title, price, sub, badge, highlight, muted }) {
  return (
    <button onClick={onClick} style={{
      width: '100%', padding: '16px 18px', cursor: 'pointer', textAlign: 'left',
      borderRadius: 16, position: 'relative',
      background: selected ? 'rgba(201,149,107,0.18)' : 'rgba(255,255,255,0.04)',
      border: selected ? '1.5px solid #C9956B' : '1.5px solid rgba(255,255,255,0.08)',
      transition: 'all 200ms ease',
      display: 'flex', alignItems: 'center', gap: 14,
    }}>
      <div style={{
        width: 22, height: 22, borderRadius: 999, flexShrink: 0,
        border: selected ? 'none' : '1.5px solid rgba(255,255,255,0.25)',
        background: selected ? '#C9956B' : 'transparent',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>{selected && <div style={{ width: 9, height: 9, borderRadius: 999, background: '#2D2A26' }}/>}</div>
      <div style={{ flex: 1 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <span style={{ fontFamily: 'Poppins', fontSize: 15, fontWeight: 600, color: muted ? 'rgba(245,230,200,0.7)' : '#F5E6C8' }}>{title}</span>
          {badge && (
            <span style={{
              fontFamily: 'Poppins', fontSize: 9, fontWeight: 700, letterSpacing: 0.8,
              color: '#2D2A26', background: '#C9956B', padding: '3px 7px', borderRadius: 6,
            }}>{badge}</span>
          )}
        </div>
      </div>
      <div style={{ textAlign: 'right' }}>
        <div style={{ fontFamily: 'Poppins', fontSize: 18, fontWeight: 700, color: '#F5E6C8', letterSpacing: -0.4 }}>{price}</div>
        <div style={{ fontFamily: 'Poppins', fontSize: 10, color: 'rgba(245,230,200,0.5)', marginTop: -2 }}>{sub}</div>
      </div>
    </button>
  );
}

Object.assign(window, { DetalleRetoScreen, DetalleRecetaScreen, PaywallScreen, VideoPlayer, PlanDetailScreen });

// ═════════════════════════════════════════════════════════════
// PLAN DETAIL — plan de alimentación
// ═════════════════════════════════════════════════════════════
function PlanDetailScreen({ planId, theme, isPremium, nav, onComplete }) {
  const T = theme;
  const p = PLANES.find(x => x.id === planId);
  const isLocked = p.tag === 'PRO' && !isPremium;
  const [myReview, setMyReview] = useS2(null);

  if (isLocked) {
    return (
      <PaywallScreen theme={T} nav={nav}
        fromReto={{ title: p.title, days: p.days }}
        onComplete={onComplete}/>
    );
  }

  function openWriteReview() {
    nav.openModal(<WriteReviewModal
      open target={p.title} T={T} accent={p.color}
      onClose={() => nav.closeModal()}
      onSubmit={(r) => {
        setMyReview({ ...r, date: 'ahora', initials: 'P', user: STATS.name });
        nav.closeModal();
      }}
    />);
  }

  return (
    <div style={{ paddingBottom: 110 }}>
      {/* Hero */}
      <div style={{
        background: `linear-gradient(160deg, ${p.bg}, ${p.color}50)`,
        padding: '12px 22px 24px',
        borderBottomLeftRadius: 32, borderBottomRightRadius: 32,
        position: 'relative', overflow: 'hidden',
      }}>
        <div style={{
          position: 'absolute', top: -30, right: -40, width: 180, height: 180,
          borderRadius: '50%', background: `${p.color}30`,
        }}/>
        <div style={{ display: 'flex', justifyContent: 'space-between', position: 'relative' }}>
          <BackBtn onClick={() => nav.back()}/>
          <div style={{ display: 'flex', gap: 8 }}>
            <RoundBtn onClick={() => nav.toast('Enlace copiado 💗', { icon: '↗' })}>{Icon.share('#2D2A26')}</RoundBtn>
            <RoundBtn onClick={() => nav.toast('Guardado en favoritos 💗', { icon: '❤️' })}>{Icon.heart('#2D2A26')}</RoundBtn>
          </div>
        </div>
        <div style={{ marginTop: 16, position: 'relative' }}>
          <div style={{ fontSize: 56, lineHeight: 1 }}>{p.emoji}</div>
          <div style={{ marginTop: 12 }}><RetoBadge tag={p.tag} isPremium={isPremium}/></div>
          <div style={{ fontFamily: 'Poppins', fontSize: 26, fontWeight: 600, color: '#2D2A26', marginTop: 8, letterSpacing: -0.5, lineHeight: 1.15 }}>{p.title}</div>
          <div style={{ fontFamily: 'Poppins', fontSize: 13, color: 'rgba(45,42,38,0.7)', marginTop: 6, lineHeight: 1.4 }}>{p.desc}</div>
        </div>
        <div style={{ marginTop: 14, padding: '12px 16px', background: 'rgba(255,255,255,0.5)', backdropFilter: 'blur(10px)', borderRadius: 14, display: 'flex', justifyContent: 'space-between' }}>
          <PStat v={p.days} l="días"/>
          <PStat v={p.kcalDay} l="kcal/día"/>
          <PStat v={p.meals.length} l="comidas/día"/>
        </div>
      </div>

      {/* Sample day */}
      <div style={{ padding: '24px 22px 0' }}>
        <div style={{ fontFamily: 'Poppins', fontSize: 11, color: T.muted, fontWeight: 500, letterSpacing: 0.5, textTransform: 'uppercase' }}>Día de muestra</div>
        <div style={{ fontFamily: 'Poppins', fontSize: 18, fontWeight: 600, color: T.text, letterSpacing: -0.3, marginTop: 4 }}>Cómo se ve un día</div>
      </div>

      <div style={{ padding: '14px 18px 0', display: 'flex', flexDirection: 'column', gap: 10 }}>
        {p.sampleDay.map((s, i) => {
          const r = RECETAS.find(x => x.id === s.recetaId);
          if (!r) return null;
          return (
            <div key={i} onClick={() => nav.go('receta', r.id)} style={{
              display: 'flex', gap: 12, padding: 10, background: T.card, borderRadius: 16, cursor: 'pointer', border: T.border,
              alignItems: 'center',
            }}>
              <RecipeImage receta={r} T={T} style={{ width: 60, height: 60, borderRadius: 12, flexShrink: 0 }}/>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontFamily: 'Poppins', fontSize: 9, color: p.color, fontWeight: 700, letterSpacing: 0.6, textTransform: 'uppercase' }}>{s.meal}</div>
                <div style={{ fontFamily: 'Poppins', fontSize: 14, fontWeight: 600, color: T.text, marginTop: 1, letterSpacing: -0.2 }}>{r.title}</div>
                <div style={{ fontFamily: 'Poppins', fontSize: 11, color: T.muted, marginTop: 2 }}>{r.kcal} kcal · {r.minutes} min</div>
              </div>
              {Icon.chevR(T.muted, 8)}
            </div>
          );
        })}
      </div>

      {/* Synced with reto */}
      <div style={{
        margin: '20px 18px 0', padding: '14px 16px',
        background: T.card, borderRadius: 16, border: T.border,
        display: 'flex', alignItems: 'center', gap: 10,
      }}>
        <span style={{ fontSize: 18 }}>🔗</span>
        <div style={{ flex: 1 }}>
          <div style={{ fontFamily: 'Poppins', fontSize: 12, fontWeight: 600, color: T.text }}>Sincronizado con reto</div>
          <div style={{ fontFamily: 'Poppins', fontSize: 11, color: T.muted, marginTop: 1 }}>Si activas este plan, tus comidas se ajustan al reto que estés haciendo.</div>
        </div>
      </div>

      {/* CTA */}
      <div style={{ padding: '20px 18px 0' }}>
        <button onClick={() => { nav.toast('Plan iniciado 💗', { icon: '✓' }); setTimeout(() => nav.back(), 700); }} style={{
          width: '100%', padding: '16px',
          border: 'none', borderRadius: 16, cursor: 'pointer',
          background: p.color, color: '#fff',
          fontFamily: 'Poppins', fontSize: 15, fontWeight: 600, letterSpacing: -0.1,
          boxShadow: `0 6px 18px ${p.color}55`,
        }}>Empezar plan · {p.days} días</button>
      </div>

      {/* Reviews */}
      <ReviewsSection id={`${p.id}-plan`} T={T} accent={p.color} myReview={myReview} onWrite={openWriteReview}/>
    </div>
  );
}

function PStat({ v, l }) {
  return (
    <div style={{ textAlign: 'center' }}>
      <div style={{ fontFamily: 'Poppins', fontSize: 18, fontWeight: 700, color: '#2D2A26', letterSpacing: -0.4, lineHeight: 1 }}>{v}</div>
      <div style={{ fontFamily: 'Poppins', fontSize: 9, color: 'rgba(45,42,38,0.55)', marginTop: 4, fontWeight: 500, letterSpacing: 0.5, textTransform: 'uppercase' }}>{l}</div>
    </div>
  );
}
