// Pau Fit — Testimonios + Share-photo card + Cover composer
// (Antes "reviews". Mantengo nombres de export como alias para compat.)

const { useState: useStateX, useEffect: useEffectX, useRef: useRefX } = React;

// ─────────────────────────────────────────────────────────────
// Testimonios — sección
// Sin estrellas. Stats sociales (% recomienda + total). Foto opcional.
// ─────────────────────────────────────────────────────────────
function TestimoniesSection({ id, T, accent, onWrite, myTestimony }) {
  const items = testimoniesFor(id);
  const pct = recommendsPercent(id);
  const total = items.length;

  // SOLO se puede dejar testimonio si se completó el reto
  // (cache.activeReto con completed_at no null, o user_retos histórico)
  // Pasamos id del reto y comprobamos en cache.activeReto si está completado.
  const cache = (typeof window !== 'undefined' && window.__pauCache) || {};
  const activeReto = cache.activeReto;
  // Si el id es de plan ("xxx-plan"), eliminar sufijo
  const cleanId = (id || '').replace('-plan', '');
  const retoCompleted = activeReto && activeReto.reto_id === cleanId && activeReto.completed_at != null;
  // También permitir si tiene este reto en historial completado (no implementado aquí, futuro)
  const canWrite = !!retoCompleted;

  return (
    <div>
      <div style={{ padding: '24px 20px 0', display: 'flex', alignItems: 'baseline', justifyContent: 'space-between' }}>
        <div style={{ fontFamily: 'Poppins', fontSize: 18, fontWeight: 600, color: T.text, letterSpacing: -0.3 }}>Testimonios</div>
        {canWrite && (
          <button onClick={onWrite} style={{
            border: 'none', background: 'transparent', cursor: 'pointer',
            fontFamily: 'Poppins', fontSize: 12, fontWeight: 600, color: accent,
          }}>+ Tu testimonio</button>
        )}
        {!canWrite && (
          <span style={{
            fontFamily: 'Poppins', fontSize: 10, color: T.muted, fontWeight: 600,
            letterSpacing: 0.3,
          }}>🔒 Completa el reto para opinar</span>
        )}
      </div>

      {/* Aggregate */}
      {total > 0 && (
        <div style={{ margin: '12px 18px 0', padding: '16px 20px', background: T.card, borderRadius: 16, border: T.border, display: 'flex', alignItems: 'center', gap: 16 }}>
          <div style={{
            width: 56, height: 56, borderRadius: 999, background: `${accent}15`,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}>
            <span style={{ fontFamily: 'Poppins', fontSize: 16, fontWeight: 700, color: accent, letterSpacing: -0.4 }}>{pct}%</span>
          </div>
          <div style={{ flex: 1 }}>
            <div style={{ fontFamily: 'Poppins', fontSize: 14, fontWeight: 600, color: T.text, letterSpacing: -0.2 }}>lo recomienda 💗</div>
            <div style={{ fontFamily: 'Poppins', fontSize: 11, color: T.muted, marginTop: 2 }}>basado en {total} testimonio{total === 1 ? '' : 's'} de la comunidad</div>
          </div>
        </div>
      )}

      {/* Mi testimonio */}
      {myTestimony && (
        <div style={{
          margin: '10px 18px 0', padding: '14px 16px',
          background: `${accent}10`, borderRadius: 16,
          border: `0.5px solid ${accent}40`,
        }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
            <span style={{
              fontFamily: 'Poppins', fontSize: 11, fontWeight: 700,
              color: accent, letterSpacing: 0.6, 
            }}>Tu testimonio</span>
            <span style={{ fontSize: 14 }}>💗</span>
          </div>
          <div style={{ marginTop: 6, fontFamily: 'Poppins', fontSize: 13, color: T.text, lineHeight: 1.4 }}>{myTestimony.text}</div>
          {myTestimony.recommends && (
            <div style={{ marginTop: 4, fontFamily: 'Poppins', fontSize: 11, color: accent, fontWeight: 600 }}>💗 Lo recomendaste · Gracias por compartir</div>
          )}
        </div>
      )}

      {/* Lista */}
      <div style={{ padding: '10px 18px 0', display: 'flex', flexDirection: 'column', gap: 10 }}>
        {items.slice(0, 4).map(t => (
          <TestimonyCard key={t.id} t={t} T={T} accent={accent}/>
        ))}
        {items.length > 4 && (
          <button style={{
            background: T.card, padding: '12px', borderRadius: 16, cursor: 'pointer',
            fontFamily: 'Poppins', fontSize: 13, fontWeight: 500, color: accent, border: T.border,
          }}>Ver los {items.length} testimonios</button>
        )}
        {items.length === 0 && (
          <div style={{ textAlign: 'center', padding: 16, fontFamily: 'Poppins', fontSize: 13, color: T.muted }}>Sé la primera en compartir 💗</div>
        )}
      </div>
    </div>
  );
}

function TestimonyCard({ t, T, accent }) {
  return (
    <div style={{
      padding: '14px 16px', background: T.card, borderRadius: 16, border: T.border,
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
        <div style={{
          width: 36, height: 36, borderRadius: 999,
          background: t.avatar_url ? '#fff' : `linear-gradient(135deg, ${accent}, ${accent}99)`,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontFamily: 'Poppins', fontSize: 13, fontWeight: 700, color: '#fff',
          overflow: 'hidden',
        }}>
          {t.avatar_url
            ? <img src={t.avatar_url} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }}/>
            : (t.initials && t.initials !== 'P' && t.initials !== '?')
              ? t.initials
              : <img src="/branding/logo.png" alt="Pau Fit" style={{ width: 22, height: 22, objectFit: 'contain' }}/>
          }
        </div>
        <div style={{ flex: 1 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
            <span style={{ fontFamily: 'Poppins', fontSize: 13, fontWeight: 600, color: T.text }}>{t.user}</span>
            {t.recommends && (
              <span style={{
                display: 'inline-flex', alignItems: 'center', gap: 3,
                fontFamily: 'Poppins', fontSize: 9, fontWeight: 700,
                color: accent, padding: '2px 6px', borderRadius: 5,
                background: `${accent}18`, letterSpacing: 0.3,
              }}>💗 LO RECOMIENDA</span>
            )}
          </div>
          <span style={{ fontFamily: 'Poppins', fontSize: 10, color: T.muted }}>{t.date} · verificada</span>
        </div>
      </div>
      <div style={{ marginTop: 10, fontFamily: 'Poppins', fontSize: 13, color: T.text, lineHeight: 1.5 }}>{t.text}</div>
      {t.photo && (
        <div style={{
          marginTop: 10, height: 120, borderRadius: 12,
          background: `linear-gradient(135deg, ${accent}33, ${accent}11)`,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          position: 'relative', overflow: 'hidden',
        }}>
          <span style={{ fontSize: 48, opacity: 0.7 }}>📸</span>
          <span style={{
            position: 'absolute', bottom: 8, left: 10,
            fontFamily: 'Poppins', fontSize: 9, color: T.muted, fontWeight: 500, letterSpacing: 0.5, 
          }}>Foto del testimonio</span>
        </div>
      )}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Reseñas REALES (tabla public.reviews en Supabase)
// ReviewsSection es autosuficiente: carga, muestra y permite
// escribir/editar la reseña de la usuaria actual.
// ─────────────────────────────────────────────────────────────

// ¿El error indica que la tabla reviews aún no existe?
function reviewsTableMissing(error) {
  if (!error) return false;
  const code = error.code || '';
  const msg = (error.message || '').toLowerCase();
  return code === 'PGRST205' || code === '42P01' || msg.includes('reviews');
}

// Fecha relativa simple en español neutro: "hace 3 días"
function timeAgoEs(iso) {
  if (!iso) return '';
  const secs = Math.floor((Date.now() - new Date(iso).getTime()) / 1000);
  if (!isFinite(secs) || secs < 0) return 'hace un momento';
  if (secs < 60) return 'hace un momento';
  const mins = Math.floor(secs / 60);
  if (mins < 60) return mins === 1 ? 'hace 1 minuto' : `hace ${mins} minutos`;
  const hours = Math.floor(mins / 60);
  if (hours < 24) return hours === 1 ? 'hace 1 hora' : `hace ${hours} horas`;
  const days = Math.floor(hours / 24);
  if (days < 30) return days === 1 ? 'hace 1 día' : `hace ${days} días`;
  const months = Math.floor(days / 30);
  if (months < 12) return months === 1 ? 'hace 1 mes' : `hace ${months} meses`;
  const years = Math.floor(months / 12);
  return years === 1 ? 'hace 1 año' : `hace ${years} años`;
}

// Fila de 5 estrellas (solo lectura)
function StarsRow({ rating, accent, muted, size = 12 }) {
  return (
    <span style={{ display: 'inline-flex', gap: 1, fontSize: size, lineHeight: 1 }}>
      {[1, 2, 3, 4, 5].map(n => (
        <span key={n} style={{ color: n <= rating ? accent : muted, opacity: n <= rating ? 1 : 0.35 }}>★</span>
      ))}
    </span>
  );
}

function ReviewCard({ review, profile, T, accent, isMine }) {
  const name = (profile && (profile.full_name || profile.username)) || 'Usuaria Pau Fit';
  const avatarUrl = profile && profile.avatar_url;
  const initial = (name.trim()[0] || '').toUpperCase();
  return (
    <div style={{
      padding: '14px 16px', background: isMine ? `${accent}10` : T.card, borderRadius: 20,
      border: isMine ? `0.5px solid ${accent}40` : T.border,
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
        <div style={{
          width: 36, height: 36, borderRadius: 999,
          background: avatarUrl ? '#fff' : `linear-gradient(135deg, ${accent}, ${accent}99)`,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontSize: 13, fontWeight: 700, color: '#fff', overflow: 'hidden', flexShrink: 0,
        }}>
          {avatarUrl
            ? <img src={avatarUrl} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }}/>
            : initial || '💗'}
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
            <span style={{ fontSize: 13, fontWeight: 600, color: T.text, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{name}</span>
            {isMine && (
              <span style={{
                fontSize: 9, fontWeight: 700, color: accent, padding: '2px 6px',
                borderRadius: 999, background: `${accent}18`, letterSpacing: 0.3, flexShrink: 0,
              }}>TU RESEÑA</span>
            )}
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 2 }}>
            <StarsRow rating={review.rating || 0} accent={accent} muted={T.muted} size={11}/>
            <span style={{ fontSize: 10, color: T.muted }}>{timeAgoEs(review.created_at)}</span>
          </div>
        </div>
      </div>
      {review.content && (
        <div style={{ marginTop: 10, fontSize: 13, color: T.text, lineHeight: 1.5 }}>{review.content}</div>
      )}
    </div>
  );
}

function ReviewsSection({ type, id, T, accent }) {
  const targetId = String(id == null ? '' : id);
  const [loading, setLoading] = useStateX(true);
  const [rows, setRows] = useStateX([]);
  const [profiles, setProfiles] = useStateX({});
  const [tableMissing, setTableMissing] = useStateX(false);
  const [refreshKey, setRefreshKey] = useStateX(0);

  useEffectX(() => {
    let alive = true;
    (async () => {
      const sb = window.__PAU_SUPABASE;
      if (!sb || !type || !targetId) { if (alive) setLoading(false); return; }
      setLoading(true);
      const { data, error } = await sb
        .from('reviews')
        .select('*')
        .eq('target_type', type)
        .eq('target_id', targetId)
        .order('created_at', { ascending: false })
        .limit(20);
      if (!alive) return;
      if (error) {
        setRows([]); setProfiles({});
        setTableMissing(reviewsTableMissing(error));
        setLoading(false);
        if (!reviewsTableMissing(error)) {
          window.__pauNav && window.__pauNav.toast && window.__pauNav.toast('No se pudieron cargar las reseñas', { icon: '⚠️' });
        }
        return;
      }
      const list = data || [];
      const ids = Array.from(new Set(list.map(r => r.user_id).filter(Boolean)));
      let profMap = {};
      if (ids.length > 0) {
        const { data: profs } = await sb
          .from('profiles')
          .select('id, username, full_name, avatar_url')
          .in('id', ids);
        (profs || []).forEach(p => { profMap[p.id] = p; });
      }
      if (!alive) return;
      setRows(list); setProfiles(profMap);
      setTableMissing(false); setLoading(false);
    })();
    return () => { alive = false; };
  }, [type, targetId, refreshKey]);

  const myId = (window.__pauCache && window.__pauCache.profile && window.__pauCache.profile.id) || null;
  const myReview = myId ? rows.find(r => r.user_id === myId) : null;
  const total = rows.length;
  const avg = total > 0 ? (rows.reduce((s, r) => s + (r.rating || 0), 0) / total) : 0;

  function openWrite() {
    const navRef = window.__pauNav;
    if (!myId) {
      navRef && navRef.toast && navRef.toast('Tu sesión expiró — cierra sesión y vuelve a entrar', { icon: '🔒' });
      return;
    }
    if (!navRef || !navRef.openModal) return;
    navRef.openModal(<WriteReviewModal
      open
      type={type} id={targetId}
      T={T} accent={accent}
      existing={myReview ? { rating: myReview.rating, content: myReview.content } : null}
      onClose={() => navRef.closeModal()}
      onSaved={() => { navRef.closeModal(); setRefreshKey(k => k + 1); }}
    />);
  }

  const canWrite = !loading && !tableMissing;

  return (
    <div>
      <div style={{ padding: '24px 20px 0', display: 'flex', alignItems: 'baseline', justifyContent: 'space-between' }}>
        <div style={{ fontSize: 18, fontWeight: 600, color: T.text, letterSpacing: -0.3 }}>Reseñas</div>
        {canWrite && (
          <button onClick={openWrite} style={{
            border: 'none', background: 'transparent', cursor: 'pointer',
            fontSize: 12, fontWeight: 600, color: accent,
          }}>{myReview ? 'Editar tu reseña' : 'Escribir reseña'}</button>
        )}
      </div>

      {/* Tabla aún no disponible */}
      {tableMissing && (
        <div style={{ margin: '12px 18px 0', padding: '18px 20px', background: T.card, borderRadius: 20, border: T.border, textAlign: 'center' }}>
          <div style={{ fontSize: 13, color: T.muted, lineHeight: 1.5 }}>Muy pronto podrás dejar tu reseña 💗</div>
        </div>
      )}

      {/* Cargando */}
      {loading && !tableMissing && (
        <div style={{ padding: '16px 20px', fontSize: 12, color: T.muted, textAlign: 'center' }}>Cargando reseñas…</div>
      )}

      {/* Promedio */}
      {!loading && !tableMissing && total > 0 && (
        <div style={{ margin: '12px 18px 0', padding: '16px 20px', background: T.card, borderRadius: 20, border: T.border, display: 'flex', alignItems: 'center', gap: 14 }}>
          <div style={{
            width: 56, height: 56, borderRadius: 999, background: `${accent}15`, flexShrink: 0,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}>
            <span style={{ fontSize: 16, fontWeight: 700, color: accent, letterSpacing: -0.4 }}>{avg.toFixed(1)}</span>
          </div>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 14, fontWeight: 600, color: T.text, letterSpacing: -0.2 }}>{avg.toFixed(1)} ★ · {total} reseña{total === 1 ? '' : 's'}</div>
            <div style={{ fontSize: 11, color: T.muted, marginTop: 2 }}>opiniones reales de la comunidad</div>
          </div>
        </div>
      )}

      {/* Lista / vacío */}
      {!loading && !tableMissing && (
        <div style={{ padding: '10px 18px 0', display: 'flex', flexDirection: 'column', gap: 10 }}>
          {rows.map(r => (
            <ReviewCard key={r.id || `${r.user_id}-${r.created_at}`} review={r} profile={profiles[r.user_id]} T={T} accent={accent} isMine={myId && r.user_id === myId}/>
          ))}
          {total === 0 && (
            <div style={{ padding: '18px 16px', background: T.card, borderRadius: 20, border: T.border, textAlign: 'center' }}>
              <div style={{ fontSize: 13, color: T.muted, lineHeight: 1.5 }}>Sé la primera en dejar tu reseña 💗</div>
              <button onClick={openWrite} style={{
                marginTop: 10, padding: '10px 18px', border: 'none', borderRadius: 999, cursor: 'pointer',
                background: accent, color: '#fff', fontSize: 12, fontWeight: 600,
              }}>Escribir reseña</button>
            </div>
          )}
        </div>
      )}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Write Testimony Modal — recomienda toggle + foto opcional
// ─────────────────────────────────────────────────────────────
function WriteTestimonyModal({ open, onClose, onSubmit, target, T, accent }) {
  const [recommends, setRecommends] = useStateX(true);
  const [text, setText] = useStateX('');
  const [hasPhoto, setHasPhoto] = useStateX(false);
  if (!open) return null;

  return (
    <div style={{
      position: 'absolute', inset: 0, zIndex: 300, display: 'flex', alignItems: 'flex-end',
      background: 'rgba(0,0,0,0.4)', animation: 'fade-in 200ms ease',
    }} onClick={onClose}>
      <div onClick={(e) => e.stopPropagation()} style={{
        width: '100%', background: T.bg, borderTopLeftRadius: 28, borderTopRightRadius: 28,
        padding: '16px 22px 36px', animation: 'slide-up 300ms cubic-bezier(.2,.8,.2,1)',
        maxHeight: '88%', overflowY: 'auto',
      }}>
        <div style={{ width: 40, height: 4, borderRadius: 999, background: 'rgba(0,0,0,0.15)', margin: '4px auto 18px' }}/>
        <div style={{ fontFamily: 'Poppins', fontSize: 11, color: T.muted, fontWeight: 500, letterSpacing: 0.5,  }}>Tu testimonio</div>
        <div style={{ fontFamily: 'Poppins', fontSize: 20, fontWeight: 600, color: T.text, marginTop: 4, letterSpacing: -0.4, lineHeight: 1.2 }}>{target}</div>
        <div style={{ fontFamily: 'Poppins', fontSize: 12, color: T.muted, marginTop: 6, lineHeight: 1.4 }}>Cuéntanos cómo te fue. Tu historia ayuda a otras chicas a animarse 💗</div>

        {/* Recomienda toggle */}
        <div style={{
          marginTop: 18, padding: '14px 16px',
          background: T.card, borderRadius: 16, border: T.border,
          display: 'flex', alignItems: 'center', gap: 12,
        }}>
          <span style={{ fontSize: 22 }}>{recommends ? '💗' : '🤔'}</span>
          <div style={{ flex: 1 }}>
            <div style={{ fontFamily: 'Poppins', fontSize: 13, fontWeight: 600, color: T.text }}>¿Lo recomiendas?</div>
            <div style={{ fontFamily: 'Poppins', fontSize: 11, color: T.muted, marginTop: 1 }}>{recommends ? 'Sí, lo recomiendo' : 'Prefiero no recomendarlo'}</div>
          </div>
          <button onClick={() => setRecommends(!recommends)} style={{
            width: 44, height: 26, borderRadius: 999, border: 'none', cursor: 'pointer',
            background: recommends ? accent : 'rgba(0,0,0,0.12)', position: 'relative',
            transition: 'background 200ms ease',
          }}>
            <div style={{
              position: 'absolute', top: 3, left: recommends ? 21 : 3,
              width: 20, height: 20, borderRadius: 999, background: '#fff',
              transition: 'left 200ms ease', boxShadow: '0 1px 3px rgba(0,0,0,0.15)',
            }}/>
          </button>
        </div>

        <textarea
          value={text} onChange={(e) => setText(e.target.value)}
          placeholder="Cuenta tu experiencia…"
          style={{
            marginTop: 12, width: '100%', minHeight: 90, padding: '14px',
            border: T.border, borderRadius: 16, background: T.card,
            fontFamily: 'Poppins', fontSize: 14, color: T.text, resize: 'none', outline: 'none',
          }}/>

        <button onClick={() => setHasPhoto(!hasPhoto)} style={{
          marginTop: 8, width: '100%', padding: '14px',
          border: hasPhoto ? `1.5px solid ${accent}` : `1.5px dashed ${T.muted}55`,
          borderRadius: 16, cursor: 'pointer', background: hasPhoto ? `${accent}08` : 'transparent',
          fontFamily: 'Poppins', fontSize: 13, fontWeight: 500, color: hasPhoto ? accent : T.muted,
          display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
        }}>
          {hasPhoto ? '✓ Foto añadida' : '📷 Añadir foto (opcional)'}
        </button>

        <button onClick={() => onSubmit({
          recommends, text: text || 'Sin comentario', photo: hasPhoto,
        })} style={{
          marginTop: 14, width: '100%', padding: '16px',
          border: 'none', borderRadius: 16, cursor: 'pointer',
          background: accent, color: '#fff',
          fontFamily: 'Poppins', fontSize: 14, fontWeight: 600, letterSpacing: -0.1,
        }}>Publicar testimonio</button>
        <button onClick={onClose} style={{
          marginTop: 8, width: '100%', padding: '12px',
          border: 'none', background: 'transparent', cursor: 'pointer',
          fontFamily: 'Poppins', fontSize: 13, fontWeight: 500, color: T.muted,
        }}>Cancelar</button>
      </div>
    </div>
  );
}
// ─────────────────────────────────────────────────────────────
// Write Review Modal — estrellas 1-5 + texto ≤600, UPSERT real
// en public.reviews. Si falla, el modal NO se cierra.
// ─────────────────────────────────────────────────────────────
function WriteReviewModal({ open, onClose, onSaved, type, id, T, accent, existing }) {
  const [rating, setRating] = useStateX((existing && existing.rating) || 5);
  const [text, setText] = useStateX((existing && existing.content) || '');
  const [saving, setSaving] = useStateX(false);
  if (!open) return null;

  const toast = (msg, opts) => window.__pauNav && window.__pauNav.toast && window.__pauNav.toast(msg, opts);

  async function submit() {
    if (saving) return;
    const sb = window.__PAU_SUPABASE;
    const profile = window.__pauCache && window.__pauCache.profile;
    if (!sb || !profile || !profile.id) {
      toast('Tu sesión expiró — cierra sesión y vuelve a entrar', { icon: '🔒' });
      return;
    }
    const r = Math.min(5, Math.max(1, Math.round(rating) || 0));
    const content = (text || '').trim().slice(0, 600);
    setSaving(true);
    try {
      const { error } = await sb.from('reviews').upsert({
        user_id: profile.id,
        target_type: type,
        target_id: String(id),
        rating: r,
        content,
        updated_at: new Date().toISOString(),
      }, { onConflict: 'user_id,target_type,target_id' });
      setSaving(false);
      if (error) {
        if (reviewsTableMissing(error)) toast('Las reseñas estarán disponibles muy pronto 💗', { icon: '⏳' });
        else toast('No se pudo publicar tu reseña — intenta de nuevo', { icon: '⚠️' });
        return; // el modal se queda abierto
      }
      toast('Reseña publicada 💗', { icon: '✓' });
      if (onSaved) onSaved(); else if (onClose) onClose();
    } catch (e) {
      setSaving(false);
      toast('No se pudo publicar tu reseña — intenta de nuevo', { icon: '⚠️' });
    }
  }

  return (
    <div style={{
      position: 'absolute', inset: 0, zIndex: 300, display: 'flex', alignItems: 'flex-end',
      background: 'rgba(0,0,0,0.4)', animation: 'fade-in 200ms ease',
    }} onClick={onClose}>
      <div onClick={(e) => e.stopPropagation()} style={{
        width: '100%', background: T.bg, borderTopLeftRadius: 28, borderTopRightRadius: 28,
        padding: '16px 22px 36px', animation: 'slide-up 300ms cubic-bezier(.2,.8,.2,1)',
        maxHeight: '88%', overflowY: 'auto',
      }}>
        <div style={{ width: 40, height: 4, borderRadius: 999, background: 'rgba(0,0,0,0.15)', margin: '4px auto 18px' }}/>
        <div style={{ fontSize: 11, color: T.muted, fontWeight: 500, letterSpacing: 0.5,  }}>{existing ? 'Edita tu reseña' : 'Tu reseña'}</div>
        <div style={{ fontSize: 20, fontWeight: 600, color: T.text, marginTop: 4, letterSpacing: -0.4, lineHeight: 1.2 }}>¿Qué te pareció?</div>
        <div style={{ fontSize: 12, color: T.muted, marginTop: 6, lineHeight: 1.4 }}>Tu opinión ayuda a otras chicas a decidirse 💗</div>

        {/* Estrellas */}
        <div style={{
          marginTop: 18, padding: '14px 16px',
          background: T.card, borderRadius: 20, border: T.border,
          display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
        }}>
          {[1, 2, 3, 4, 5].map(n => (
            <button key={n} onClick={() => setRating(n)} style={{
              border: 'none', background: 'transparent', cursor: 'pointer', padding: 4,
              fontSize: 30, lineHeight: 1,
              color: n <= rating ? accent : T.muted,
              opacity: n <= rating ? 1 : 0.35,
              transition: 'color 150ms ease, opacity 150ms ease',
            }}>★</button>
          ))}
        </div>

        <textarea
          value={text} onChange={(e) => setText(e.target.value)} maxLength={600}
          placeholder="Cuenta tu experiencia… (opcional)"
          style={{
            marginTop: 12, width: '100%', minHeight: 90, padding: '14px',
            border: T.border, borderRadius: 20, background: T.card,
            fontSize: 14, color: T.text, resize: 'none', outline: 'none',
          }}/>
        <div style={{ marginTop: 4, fontSize: 10, color: T.muted, textAlign: 'right' }}>{(text || '').length}/600</div>

        <button onClick={submit} disabled={saving} style={{
          marginTop: 14, width: '100%', padding: '16px',
          border: 'none', borderRadius: 20, cursor: saving ? 'default' : 'pointer',
          background: accent, color: '#fff', opacity: saving ? 0.6 : 1,
          fontSize: 14, fontWeight: 600, letterSpacing: -0.1,
        }}>{saving ? 'Publicando…' : (existing ? 'Guardar cambios' : 'Publicar reseña')}</button>
        <button onClick={onClose} disabled={saving} style={{
          marginTop: 8, width: '100%', padding: '12px',
          border: 'none', background: 'transparent', cursor: 'pointer',
          fontSize: 13, fontWeight: 500, color: T.muted,
        }}>Cancelar</button>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Share Photo Card — post-workout (sin cambios sustanciales)
// ─────────────────────────────────────────────────────────────
function SharePhotoCard({ open, onClose, reto, day, totalMinutes, T, accent }) {
  const [filter, setFilter] = useStateX('rose');
  if (!open) return null;

  const filters = {
    rose:   { name: 'Rosé',   over: 'linear-gradient(135deg, rgba(217,71,126,0.35), rgba(245,215,220,0.15))' },
    peach:  { name: 'Peach',  over: 'linear-gradient(160deg, rgba(232,180,160,0.4), rgba(212,132,122,0.18))' },
    gold:   { name: 'Gold',   over: 'linear-gradient(180deg, rgba(201,149,107,0.25), rgba(45,42,38,0.4))' },
    bw:     { name: 'Mono',   over: 'linear-gradient(180deg, rgba(45,42,38,0.18), rgba(45,42,38,0.45))' },
  };
  const f = filters[filter];

  return (
    <div style={{
      position: 'absolute', inset: 0, zIndex: 320, background: '#2D2A26',
      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.12)', 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.8,  }}>Foto del día</div>
          <div style={{ fontFamily: 'Poppins', fontSize: 14, fontWeight: 600, color: '#fff' }}>Comparte tu logro 💗</div>
        </div>
      </div>

      {/* The branded card */}
      <div style={{ flex: 1, padding: '0 26px', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <div style={{
          width: '100%', maxWidth: 320, aspectRatio: '9 / 16',
          borderRadius: 20, overflow: 'hidden', position: 'relative',
          background: `linear-gradient(160deg, ${reto.bg}, ${reto.color})`,
          boxShadow: '0 20px 60px rgba(0,0,0,0.5)',
        }}>
          <div style={{
            position: 'absolute', inset: 0,
            background: `
              radial-gradient(circle at 50% 45%, rgba(255,255,255,0.5) 0%, transparent 50%),
              repeating-linear-gradient(45deg, rgba(0,0,0,0.04) 0px, rgba(0,0,0,0.04) 4px, transparent 4px, transparent 8px)
            `,
          }}/>
          <div style={{
            position: 'absolute', top: '38%', left: '50%', transform: 'translate(-50%,-50%)',
            fontSize: 72, opacity: 0.85,
          }}>📸</div>
          <div style={{
            position: 'absolute', top: '55%', left: '50%', transform: 'translateX(-50%)',
            fontFamily: 'Poppins', fontSize: 10, color: 'rgba(45,42,38,0.55)', fontWeight: 500, letterSpacing: 1,  textAlign: 'center', width: '70%',
          }}>Aquí va tu mirror selfie</div>
          <div style={{ position: 'absolute', inset: 0, background: f.over }}/>
          <div style={{
            position: 'absolute', top: 18, left: 18, right: 18,
            display: 'flex', justifyContent: 'space-between', alignItems: 'center',
          }}>
            <div style={{
              display: 'flex', alignItems: 'center', gap: 6,
              fontFamily: 'Poppins', fontSize: 14, fontWeight: 700, color: '#fff',
              letterSpacing: -0.3, textShadow: '0 1px 4px rgba(0,0,0,0.25)',
            }}>
              <img src="/branding/logo.png" alt="" style={{
                width: 22, height: 22, borderRadius: 6, background: '#fff',
                padding: 2, objectFit: 'contain',
              }}/>
              Pau Fit
            </div>
            <div style={{
              fontFamily: 'Poppins', fontSize: 9, color: 'rgba(255,255,255,0.85)', fontWeight: 600,
              letterSpacing: 0.6, 
              padding: '4px 8px', borderRadius: 999, background: 'rgba(0,0,0,0.2)',
              backdropFilter: 'blur(8px)',
            }}>Día {day} · {reto.title}</div>
          </div>
          <div style={{ position: 'absolute', bottom: 18, left: 18, right: 18 }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', marginBottom: 12 }}>
              <BigStat v={`${totalMinutes}'`} l="entreno" />
              <BigStat v={day} l={`/ ${reto.days}`} />
              <BigStat v="✓" l="completado" />
            </div>
            <div style={{
              fontFamily: 'Poppins', fontSize: 14, fontWeight: 700, fontStyle: 'italic',
              color: '#fff', letterSpacing: 0.2, textShadow: '0 1px 6px rgba(0,0,0,0.3)',
            }}>#YoSiemprePuedo</div>
            <div style={{
              fontFamily: 'Poppins', fontSize: 10, fontWeight: 500,
              color: 'rgba(255,255,255,0.7)', letterSpacing: 0.4, marginTop: 2,
            }}>paufit.co · @paufityt</div>
          </div>
        </div>
      </div>

      <div style={{ padding: '20px 22px 12px', display: 'flex', gap: 8, justifyContent: 'center' }}>
        {Object.entries(filters).map(([k, v]) => (
          <button key={k} onClick={() => setFilter(k)} style={{
            border: filter === k ? '1.5px solid #fff' : '1.5px solid rgba(255,255,255,0.18)',
            background: filter === k ? 'rgba(255,255,255,0.1)' : 'transparent',
            padding: '6px 14px', borderRadius: 999, cursor: 'pointer',
            fontFamily: 'Poppins', fontSize: 11, fontWeight: 500, color: '#fff',
          }}>{v.name}</button>
        ))}
      </div>

      <div style={{ padding: '8px 22px 50px', display: 'flex', gap: 10 }}>
        <button onClick={() => window.__pauNav && window.__pauNav.toast('Arrastra una foto al hero para cambiarla 💗', { icon: '📷' })} style={{
          flex: 1, padding: '14px',
          border: '1px solid rgba(255,255,255,0.18)',
          background: 'rgba(255,255,255,0.08)', color: '#fff',
          borderRadius: 16, cursor: 'pointer',
          fontFamily: 'Poppins', fontSize: 13, fontWeight: 600,
          display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6,
        }}>📷 Cambiar foto</button>
        <button onClick={() => { window.__pauNav && window.__pauNav.toast('Compartido en Instagram 💗', { icon: '↗' }); onClose && onClose(); }} style={{
          flex: 1.6, padding: '14px',
          border: 'none', borderRadius: 16, cursor: 'pointer',
          background: accent, color: '#fff',
          fontFamily: 'Poppins', fontSize: 13, fontWeight: 600,
          display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6,
        }}>↗ Compartir</button>
      </div>
    </div>
  );
}

function BigStat({ v, l }) {
  return (
    <div style={{ flex: 1 }}>
      <div style={{
        fontFamily: 'Poppins', fontSize: 22, fontWeight: 700, color: '#fff', letterSpacing: -0.5,
        textShadow: '0 1px 6px rgba(0,0,0,0.3)', lineHeight: 1,
      }}>{v}</div>
      <div style={{
        fontFamily: 'Poppins', fontSize: 9, color: 'rgba(255,255,255,0.85)', marginTop: 2,
        fontWeight: 500, letterSpacing: 0.6, 
      }}>{l}</div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Covers — with image-slot for real photos
// ─────────────────────────────────────────────────────────────
function RetoCover({ reto, style = {}, large = false }) {
  return (
    <div style={{
      borderRadius: large ? 22 : 16,
      background: `linear-gradient(135deg, ${reto.bg}, ${reto.color}aa)`,
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      position: 'relative', overflow: 'hidden',
      ...style,
    }}>
      {/* User-fillable image */}
      <image-slot
        id={`reto-cover-${reto.id}`}
        placeholder={`Foto ${reto.title}`}
        shape="rect"
        style={{ position: 'absolute', inset: 0 }}
      />
      <div style={{
        position: 'absolute', bottom: 8, right: 8,
        width: 24, height: 24, borderRadius: 999,
        background: 'rgba(42,31,35,0.78)', backdropFilter: 'blur(6px)',
        display: 'flex', alignItems: 'center', justifyContent: 'center', paddingLeft: 2,
        pointerEvents: 'none',
      }}>{Icon.play('#fff')}</div>
    </div>
  );
}

function RecipeImage({ receta, style = {}, T }) {
  if (receta.image) {
    return (
      <div style={{
        borderRadius: 16, overflow: 'hidden',
        backgroundImage: `url(${receta.image})`,
        backgroundSize: 'cover', backgroundPosition: 'center',
        ...style,
      }}/>
    );
  }
  return (
    <div style={{
      borderRadius: 16, position: 'relative', overflow: 'hidden',
      background: T && T.dark ? 'linear-gradient(135deg, #3B2F26, #2A2520)' : `linear-gradient(135deg, ${T?.warm || '#FBE4DA'}, ${T?.subtle || '#F5D7DC'})`,
      ...style,
    }}>
      <image-slot
        id={`receta-${receta.id}`}
        placeholder={`Foto ${receta.title}`}
        shape="rect"
        style={{ position: 'absolute', inset: 0 }}
      />
    </div>
  );
}

Object.assign(window, {
  TestimoniesSection, WriteTestimonyModal,
  ReviewsSection, WriteReviewModal,  // reseñas reales (Supabase public.reviews)
  SharePhotoCard, RetoCover, RecipeImage,
});
