// Pau Fit — Modals interactivos: Anotar comida + Rate workout + Mood text

const { useState: useS5 } = React;

// ═════════════════════════════════════════════════════════════
// Add Meal Modal — estilo Silvy: 1 tap, simple, guarda REAL en Supabase
// ═════════════════════════════════════════════════════════════
function AddMealModal({ open, onClose, onSave, T, accent, prefill }) {
  const mealTypes = [
    { id: 'desayuno', label: 'Desayuno', emoji: '🌅' },
    { id: 'snack',    label: 'Snack',    emoji: '☕' },
    { id: 'almuerzo', label: 'Almuerzo', emoji: '🥗' },
    { id: 'cena',     label: 'Cena',     emoji: '🌙' },
  ];
  const [mealType, setMealType] = useS5(prefill?.mealType || detectMealType());
  const [name, setName] = useS5(prefill?.name || '');
  // Hora actual en formato HH:MM (editable por la usuaria)
  const [hhmm, setHhmm] = useS5(() => {
    const now = new Date();
    return `${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`;
  });
  const [saving, setSaving] = useS5(false);
  const [photoFile, setPhotoFile] = useS5(null);
  const [photoPreview, setPhotoPreview] = useS5(prefill?.imageUrl || null);
  const photoInputRef = React.useRef(null);
  // Si viene prefill desde el plan, marcar para que la UI lo diga
  const fromPlan = !!prefill?.fromPlan;

  // Macros detectados por IA o introducidos manualmente
  const [aiKcal, setAiKcal] = useS5(prefill?.kcal ?? '');
  const [aiProtein, setAiProtein] = useS5(prefill?.protein_g ?? '');
  const [aiCarbs, setAiCarbs] = useS5(prefill?.carbs_g ?? '');
  const [aiFat, setAiFat] = useS5(prefill?.fat_g ?? '');
  const [aiAnalyzing, setAiAnalyzing] = useS5(false);
  const [aiResult, setAiResult] = useS5(null); // { confidence, notes }
  // Corrección: "es banana bread de avena" → re-analiza con esa pista
  const [aiHint, setAiHint] = useS5('');

  async function analyzeWithAI(hintText) {
    if (!photoFile && !photoPreview) {
      if (window.__pauNav?.toast) window.__pauNav.toast('Añade primero una foto de la comida', { icon: '📸' });
      return;
    }
    setAiAnalyzing(true);
    try {
      // Convertir el archivo (o data URL) a base64
      let imageBase64 = photoPreview;
      if (photoFile && !imageBase64) {
        imageBase64 = await new Promise((res, rej) => {
          const r = new FileReader();
          r.onload = () => res(r.result);
          r.onerror = rej;
          r.readAsDataURL(photoFile);
        });
      }
      const sb = window.__PAU_SUPABASE;
      const headers = { 'Content-Type': 'application/json' };
      try {
        const { data: session } = await sb.auth.getSession();
        const token = session?.session?.access_token;
        if (token) headers['Authorization'] = 'Bearer ' + String(token).trim().replace(/[^\x21-\x7E]/g, '');
      } catch {}
      const res = await fetch('/api/meals/analyze-photo', {
        method: 'POST', headers,
        body: JSON.stringify({ imageBase64, mimeType: 'image/jpeg', hint: (hintText || '').trim() || undefined }),
      });
      const j = await res.json();
      if (!j.ok) {
        if (window.__pauNav?.toast) window.__pauNav.toast(j.error || 'No se pudo analizar', { icon: '⚠️' });
        setAiAnalyzing(false);
        return;
      }
      // Con corrección de la usuaria, el nombre nuevo manda
      if (j.name && (!name || hintText)) setName(j.name);
      if (j.kcal != null) setAiKcal(String(j.kcal));
      if (j.protein_g != null) setAiProtein(String(j.protein_g));
      if (j.carbs_g != null) setAiCarbs(String(j.carbs_g));
      if (j.fat_g != null) setAiFat(String(j.fat_g));
      setAiResult({ confidence: j.confidence, notes: j.notes });
      if (window.__pauNav?.toast) window.__pauNav.toast('¡Analizado! Revisa los números 💗', { icon: '✨' });
    } catch (e) {
      if (window.__pauNav?.toast) window.__pauNav.toast('Error: ' + (e?.message || e), { icon: '⚠️' });
    }
    setAiAnalyzing(false);
  }

  // autoPhoto: abrir el selector de foto/cámara nada más entrar
  // (flujo estrella estilo Cal AI: foto → IA rellena calorías y macros)
  React.useEffect(() => {
    if (open && prefill?.autoPhoto && !photoPreview && photoInputRef.current) {
      const t = setTimeout(() => { try { photoInputRef.current.click(); } catch {} }, 380);
      return () => clearTimeout(t);
    }
  }, [open]);

  if (!open) return null;

  // Detecta tipo de comida según la hora actual
  function detectMealType() {
    const h = new Date().getHours();
    if (h < 11) return 'desayuno';
    if (h < 13) return 'snack';
    if (h < 17) return 'almuerzo';
    if (h < 21) return 'snack';
    return 'cena';
  }

  // Comprime la foto en el teléfono ANTES de usarla:
  // - fotos de iPhone (HEIC, 3-12 MB) fallaban en el análisis IA (límite del
  //   servidor ~4.5 MB) y tardaban una eternidad en subir
  // - canvas la convierte SIEMPRE a JPEG ~200-400 KB máx 1200px
  async function compressPhoto(file, maxSide = 1200, quality = 0.82) {
    const bitmap = await createImageBitmap(file); // Safari iOS decodifica HEIC nativo
    const scale = Math.min(1, maxSide / Math.max(bitmap.width, bitmap.height));
    const w = Math.round(bitmap.width * scale);
    const h = Math.round(bitmap.height * scale);
    const canvas = document.createElement('canvas');
    canvas.width = w; canvas.height = h;
    canvas.getContext('2d').drawImage(bitmap, 0, 0, w, h);
    const dataUrl = canvas.toDataURL('image/jpeg', quality);
    const blob = await new Promise((res) => canvas.toBlob(res, 'image/jpeg', quality));
    return { dataUrl, blob };
  }

  async function handlePhoto(e) {
    const file = e.target.files && e.target.files[0];
    if (!file) return;
    try {
      const { dataUrl, blob } = await compressPhoto(file);
      setPhotoFile(blob);
      setPhotoPreview(dataUrl);
    } catch (err1) {
      // Plan B: decodificar vía <img> (algunos navegadores no soportan
      // createImageBitmap con ciertos formatos)
      try {
        const url = URL.createObjectURL(file);
        const img = new Image();
        await new Promise((res, rej) => { img.onload = res; img.onerror = rej; img.src = url; });
        const maxSide = 1200;
        const scale = Math.min(1, maxSide / Math.max(img.naturalWidth, img.naturalHeight));
        const canvas = document.createElement('canvas');
        canvas.width = Math.round(img.naturalWidth * scale);
        canvas.height = Math.round(img.naturalHeight * scale);
        canvas.getContext('2d').drawImage(img, 0, 0, canvas.width, canvas.height);
        URL.revokeObjectURL(url);
        const dataUrl = canvas.toDataURL('image/jpeg', 0.82);
        const blob = await new Promise((res) => canvas.toBlob(res, 'image/jpeg', 0.82));
        setPhotoFile(blob);
        setPhotoPreview(dataUrl);
      } catch (err2) {
        // Si el navegador NO puede leer el formato (ej. HEIC en Chrome de
        // escritorio), NO enviamos el archivo crudo — fallaría en la IA.
        console.warn('[photo] formato no decodificable:', err1?.message, err2?.message);
        if (window.__pauNav?.toast) window.__pauNav.toast('Ese formato de foto no es compatible — usa JPG o PNG', { icon: '📷' });
        e.target.value = '';
      }
    }
  }

  async function submit() {
    if (!name.trim()) {
      if (window.__pauNav?.toast) window.__pauNav.toast('Escribe qué comiste 💗', { icon: '✏️' });
      return;
    }
    setSaving(true);
    const toast = (msg, icon) => { if (window.__pauNav?.toast) window.__pauNav.toast(msg, { icon }); };
    const sb = window.__PAU_SUPABASE;
    try {
      if (!sb) throw new Error('Sin conexión con el servidor');
      // 1) Verificar sesión PRIMERO — si expiró, avisar claro (antes fallaba
      //    en silencio y decía "anotada" sin guardar nada)
      const { data: { user } } = await sb.auth.getUser();
      if (!user) {
        setSaving(false);
        toast('Tu sesión expiró — cierra sesión y vuelve a entrar', '🔒');
        return;
      }
      // 2) Subir foto (si hay) — ya viene comprimida a JPEG
      let photoUrl = null;
      if (photoFile) {
        const fname = `${Date.now()}-${Math.random().toString(36).slice(2,8)}.jpg`;
        const path = `${user.id}/${fname}`;
        const { error: upErr } = await sb.storage.from('meal-photos').upload(path, photoFile, {
          cacheControl: '3600', upsert: false, contentType: 'image/jpeg',
        });
        if (upErr) {
          console.warn('[meal-photos]', upErr.message);
        } else {
          const { data: urlData } = sb.storage.from('meal-photos').getPublicUrl(path);
          photoUrl = urlData?.publicUrl || null;
        }
      }
      if (!photoUrl && prefill?.imageUrl) photoUrl = prefill.imageUrl;
      // 3) Timestamp con HOY + hora elegida
      let loggedAt = new Date();
      const m = (hhmm || '').match(/^(\d{1,2}):(\d{2})$/);
      if (m) loggedAt.setHours(parseInt(m[1], 10), parseInt(m[2], 10), 0, 0);
      // 4) Guardar — y si falla, DECIRLO (no fingir éxito)
      const parseN = (v) => {
        if (v === '' || v == null) return null;
        const n = parseInt(v, 10);
        return isFinite(n) ? n : null;
      };
      const row = {
        user_id: user.id,
        meal_name: name.trim(),
        meal_type: mealType,
        photo_url: photoUrl,
        logged_at: loggedAt.toISOString(),
        kcal: parseN(aiKcal) ?? prefill?.kcal ?? null,
        protein_g: parseN(aiProtein) ?? prefill?.protein_g ?? null,
        carbs_g: parseN(aiCarbs) ?? prefill?.carbs_g ?? null,
        fat_g: parseN(aiFat) ?? prefill?.fat_g ?? null,
      };
      const { error: dbErr } = prefill?.editId
        ? await sb.from('meal_logs').update(row).eq('id', prefill.editId).eq('user_id', user.id)
        : await sb.from('meal_logs').insert(row);
      if (dbErr) throw dbErr;
      // 5) Éxito REAL → cerrar y refrescar toda la app
      setSaving(false);
      onSave && onSave({ meal: mealType, text: name.trim(), photo: !!photoUrl, photoUrl, saved: true, time: hhmm });
      window.dispatchEvent(new CustomEvent('pau:cache-updated'));
      onClose();
    } catch (e) {
      setSaving(false);
      console.warn('[meal_logs] error real:', e?.message || e);
      toast('No se pudo guardar: ' + (e?.message || 'error desconocido'), '⚠️');
      // El modal se queda abierto para no perder lo escrito
    }
  }

  return (
    <div style={{
      position: 'absolute', inset: 0, zIndex: 310, 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: '14px 22px 32px', animation: 'slide-up 300ms cubic-bezier(.2,.8,.2,1)',
        maxHeight: '88%', overflowY: 'auto', position: 'relative',
      }}>
        <div style={{ width: 40, height: 4, borderRadius: 999, background: 'rgba(0,0,0,0.15)', margin: '4px auto 18px' }}/>

        {/* Título — sin subtítulo, minimal */}
        <div className="pf-display" style={{
          fontSize: 22, fontWeight: 600, color: T.text, letterSpacing: -0.5, lineHeight: 1.1,
          textAlign: 'center',
        }}>
          {fromPlan ? '¡Hecha!' : 'Añadir comida'}
        </div>

        {/* Banner discreto cuando viene de "Marcar como hecha" del plan */}
        {fromPlan && (
          <div style={{
            marginTop: 12, padding: '9px 14px',
            background: `${accent}15`, borderRadius: 14,
            fontSize: 12, color: T.text, fontWeight: 600,
            display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
          }}>
            <span style={{ fontSize: 14 }}>✨</span>
            <span>Registrar comida de tu plan</span>
          </div>
        )}

        {/* Input file oculto — lo abre el área de foto (y el flujo autoPhoto) */}
        <input
          ref={photoInputRef}
          type="file"
          accept="image/*"
          capture="environment"
          style={{ display: 'none' }}
          onChange={handlePhoto}
        />

        {/* FOTO protagonista */}
        {photoPreview ? (
          <div style={{
            marginTop: 16, position: 'relative',
            borderRadius: 20, overflow: 'hidden',
            aspectRatio: '16 / 10',
          }}>
            <img src={photoPreview} alt="comida" style={{
              position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover',
            }}/>
            <button onClick={() => { setPhotoFile(null); setPhotoPreview(null); }} style={{
              position: 'absolute', top: 10, right: 10,
              width: 28, height: 28, borderRadius: 999, border: 'none',
              background: 'rgba(0,0,0,0.55)', color: '#fff', cursor: 'pointer',
              fontSize: 14, lineHeight: 1,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}>✕</button>
          </div>
        ) : (
          <button onClick={() => photoInputRef.current && photoInputRef.current.click()} style={{
            marginTop: 16, width: '100%', aspectRatio: '16 / 10',
            border: 'none', background: T.subtle, borderRadius: 20, cursor: 'pointer',
            display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 8,
          }}>
            <span style={{ fontSize: 32 }}>📷</span>
            <span style={{ fontSize: 13, fontWeight: 600, color: T.muted }}>Foto de tu comida</span>
          </button>
        )}

        {/* Detectar con IA — solo con foto y si NO viene del plan */}
        {!fromPlan && (photoPreview || photoFile) && (
          <button onClick={() => analyzeWithAI()} disabled={aiAnalyzing} style={{
            marginTop: 10, width: '100%', padding: '13px',
            border: 'none', borderRadius: 999, cursor: aiAnalyzing ? 'wait' : 'pointer',
            background: `${accent}15`, color: accent,
            fontSize: 13, fontWeight: 700,
            display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
            opacity: aiAnalyzing ? 0.7 : 1,
          }}>
            {aiAnalyzing && (
              <span style={{
                width: 14, height: 14, border: `2px solid ${accent}33`,
                borderTopColor: accent, borderRadius: 999,
                animation: 'spin 700ms linear infinite',
              }}/>
            )}
            {aiAnalyzing ? 'Analizando…' : '✨ Detectar con IA'}
          </button>
        )}

        {/* ¿La IA se equivocó de plato? Corrígela y re-analiza con tu pista */}
        {!fromPlan && aiResult && (
          <div style={{ marginTop: 8, display: 'flex', gap: 6 }}>
            <input
              value={aiHint}
              onChange={(e) => setAiHint(e.target.value)}
              onKeyDown={(e) => { if (e.key === 'Enter' && aiHint.trim()) analyzeWithAI(aiHint); }}
              placeholder="¿No acertó? Ej: banana bread de avena"
              style={{
                flex: 1, border: 'none', background: T.subtle, borderRadius: 14,
                padding: '11px 14px', fontSize: 12,
                color: T.text, outline: 'none',
              }}
            />
            <button onClick={() => aiHint.trim() && analyzeWithAI(aiHint)} disabled={aiAnalyzing || !aiHint.trim()} style={{
              padding: '11px 14px', border: 'none', borderRadius: 14,
              cursor: aiAnalyzing || !aiHint.trim() ? 'default' : 'pointer',
              background: aiHint.trim() ? accent : T.subtle,
              color: aiHint.trim() ? '#fff' : T.muted,
              fontSize: 11, fontWeight: 800, letterSpacing: 0.3,
            }}>CORREGIR</button>
          </div>
        )}

        {/* Nombre — un solo input grande y limpio */}
        <input
          value={name}
          onChange={(e) => setName(e.target.value)}
          placeholder="Ej: avena con plátano y café"
          style={{
            marginTop: 14, width: '100%', padding: '15px 16px',
            border: 'none', borderRadius: 14, background: T.subtle,
            fontSize: 16, fontWeight: 500, color: T.text, outline: 'none',
            letterSpacing: -0.2,
          }}
          onKeyDown={(e) => { if (e.key === 'Enter') submit(); }}
        />

        {/* Nutrición: 4 tiles editables, sin encabezado */}
        {!fromPlan && (aiKcal || aiProtein || aiCarbs || aiFat || photoPreview) && (
          <div style={{ marginTop: 12 }}>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 8 }}>
              {[
                { label: 'kcal', val: aiKcal, setVal: setAiKcal, color: T.text },
                { label: 'P (g)', val: aiProtein, setVal: setAiProtein, color: '#E89B7A' },
                { label: 'C (g)', val: aiCarbs, setVal: setAiCarbs, color: '#C5B57F' },
                { label: 'G (g)', val: aiFat, setVal: setAiFat, color: '#9AB394' },
              ].map((f, i) => (
                <div key={i} style={{ textAlign: 'center' }}>
                  <input
                    type="number" inputMode="numeric" min="0"
                    value={f.val} onChange={(e) => f.setVal(e.target.value)}
                    style={{
                      width: '100%', border: 'none', background: T.subtle, borderRadius: 14,
                      padding: '11px 4px',
                      fontSize: 16, fontWeight: 800,
                      color: T.text, textAlign: 'center', outline: 'none',
                    }}
                  />
                  <div style={{ fontSize: 9, fontWeight: 700, color: f.color, letterSpacing: 0.3, marginTop: 4,  }}>{f.label}</div>
                </div>
              ))}
            </div>
            {aiResult?.confidence != null && (
              <div style={{ marginTop: 6, fontSize: 10, color: T.muted, fontWeight: 600, textAlign: 'right' }}>
                IA · {aiResult.confidence}% confianza
              </div>
            )}
          </div>
        )}

        {/* Macros de solo lectura cuando viene del plan — mismo estilo de tiles */}
        {fromPlan && (prefill?.kcal || prefill?.protein_g || prefill?.carbs_g || prefill?.fat_g) && (
          <div style={{ marginTop: 12, display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 8 }}>
            {[
              { label: 'kcal', v: prefill.kcal, color: T.text },
              { label: 'P (g)', v: prefill.protein_g, color: '#E89B7A' },
              { label: 'C (g)', v: prefill.carbs_g, color: '#C5B57F' },
              { label: 'G (g)', v: prefill.fat_g, color: '#9AB394' },
            ].map((f, i) => (
              <div key={i} style={{ textAlign: 'center' }}>
                <div style={{
                  background: T.subtle, borderRadius: 14, padding: '11px 4px',
                  fontSize: 16, fontWeight: 800, color: T.text,
                }}>{f.v != null ? f.v : '—'}</div>
                <div style={{ fontSize: 9, fontWeight: 700, color: f.color, letterSpacing: 0.3, marginTop: 4,  }}>{f.label}</div>
              </div>
            ))}
          </div>
        )}

        {/* Tipo + hora: fila compacta, sin títulos */}
        <div style={{ marginTop: 14, display: 'flex', gap: 6 }}>
          {mealTypes.map(m => {
            const sel = mealType === m.id;
            return (
              <button key={m.id} onClick={() => setMealType(m.id)} style={{
                flex: 1, padding: '9px 2px', cursor: 'pointer',
                border: sel ? `1.5px solid ${accent}` : '1.5px solid transparent',
                background: sel ? `${accent}15` : T.subtle,
                borderRadius: 999,
                display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 4,
                whiteSpace: 'nowrap',
              }}>
                <span style={{ fontSize: 12 }}>{m.emoji}</span>
                <span style={{
                  fontSize: 10, fontWeight: 600, color: sel ? accent : T.text,
                  letterSpacing: 0.2,
                }}>{m.label}</span>
              </button>
            );
          })}
        </div>
        <div style={{ marginTop: 8, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <span style={{ fontSize: 12, color: T.muted, fontWeight: 600 }}>Hora</span>
          <input
            type="time"
            value={hhmm}
            onChange={(e) => setHhmm(e.target.value)}
            style={{
              border: 'none', borderRadius: 999, background: T.subtle,
              padding: '8px 14px',
              fontSize: 13, fontWeight: 600, color: T.text, outline: 'none',
            }}
          />
        </div>

        {/* CTA único */}
        <button onClick={submit} disabled={saving} style={{
          marginTop: 20, width: '100%', padding: '16px',
          border: 'none', borderRadius: 999, cursor: saving ? 'wait' : 'pointer',
          background: name.trim() ? accent : T.subtle,
          color: name.trim() ? '#fff' : T.muted,
          fontSize: 15, fontWeight: 700, letterSpacing: 0.2,
          opacity: saving ? 0.7 : 1,
          transition: 'all 180ms ease',
        }}>
          {saving ? 'Guardando…' : 'Guardar'}
        </button>
        <button onClick={onClose} style={{
          marginTop: 6, width: '100%', padding: '12px',
          border: 'none', background: 'transparent', cursor: 'pointer',
          fontSize: 13, fontWeight: 600, color: T.muted,
        }}>Cancelar</button>
      </div>
    </div>
  );
}

function initTime() {
  const d = new Date();
  return `${String(d.getHours()).padStart(2,'0')}:${String(d.getMinutes()).padStart(2,'0')}`;
}

// ─────────────────────────────────────────────────────────────
// Frequent Meals Sheet — sub-modal sobre AddMealModal
// ─────────────────────────────────────────────────────────────
function FrequentMealsSheet({ onClose, onPick, T, accent }) {
  const [showAll, setShowAll] = useS5(false);
  const visible = showAll ? FREQUENT_MEALS : FREQUENT_MEALS.slice(0, 5);

  return (
    <div style={{
      position: 'absolute', inset: 0, zIndex: 320, display: 'flex', alignItems: 'flex-end',
      background: 'rgba(0,0,0,0.45)', 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: '70%', overflowY: 'auto',
      }}>
        <div style={{ width: 40, height: 4, borderRadius: 999, background: 'rgba(0,0,0,0.15)', margin: '4px auto 18px' }}/>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <div>
            <div style={{ fontFamily: 'Poppins', fontSize: 11, color: T.muted, fontWeight: 500, letterSpacing: 0.5,  }}>Mis frecuentes</div>
            <div style={{ fontFamily: 'Poppins', fontSize: 18, fontWeight: 600, color: T.text, marginTop: 2, letterSpacing: -0.3 }}>
              {showAll ? `Todas (${FREQUENT_MEALS.length})` : 'Más recientes'}
            </div>
          </div>
          <button onClick={onClose} style={{
            width: 32, height: 32, borderRadius: 999, border: 'none',
            background: T.subtle, cursor: 'pointer',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}>{Icon.close(T.text)}</button>
        </div>

        <div style={{ marginTop: 16, display: 'flex', flexDirection: 'column', gap: 8 }}>
          {visible.map(f => (
            <button key={f.id} onClick={() => onPick(f)} style={{
              padding: '12px 16px', cursor: 'pointer',
              border: T.border, background: T.card,
              borderRadius: 16, textAlign: 'left',
              display: 'flex', alignItems: 'center', gap: 12,
            }}>
              <div style={{
                width: 40, height: 40, borderRadius: 12, flexShrink: 0,
                background: T.subtle,
                display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 22,
              }}>{f.emoji}</div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontFamily: 'Poppins', fontSize: 9, color: accent, fontWeight: 700, letterSpacing: 0.6,  }}>{f.meal}</div>
                <div style={{ fontFamily: 'Poppins', fontSize: 14, fontWeight: 600, color: T.text, marginTop: 1, letterSpacing: -0.2 }}>{f.title}</div>
              </div>
              {Icon.chevR(T.muted, 8)}
            </button>
          ))}
        </div>

        {!showAll && FREQUENT_MEALS.length > 5 && (
          <button onClick={() => setShowAll(true)} style={{
            marginTop: 12, width: '100%', padding: '12px',
            border: T.border, background: 'transparent', cursor: 'pointer',
            borderRadius: 12,
            fontFamily: 'Poppins', fontSize: 13, fontWeight: 600, color: accent,
          }}>Ver todo ({FREQUENT_MEALS.length})</button>
        )}

        {FREQUENT_MEALS.length === 0 && (
          <div style={{ textAlign: 'center', padding: 24, fontFamily: 'Poppins', fontSize: 13, color: T.muted }}>
            Aún no tienes comidas guardadas. Marca alguna como frecuente al anotarla 💗
          </div>
        )}
      </div>
    </div>
  );
}

// ═════════════════════════════════════════════════════════════
// Rate Workout Modal — después de completar día o rutina suelta
// ═════════════════════════════════════════════════════════════
function RateWorkoutModal({ open, onClose, onSave, target, T, accent, retoColor }) {
  const [rating, setRating] = useS5(null);
  const [comment, setComment] = useS5('');
  if (!open) return null;

  function submit() {
    onSave({ rating, comment });
    onClose();
  }

  const color = retoColor || accent;

  return (
    <div style={{
      position: 'absolute', inset: 0, zIndex: 310, 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)',
      }}>
        <div style={{ width: 40, height: 4, borderRadius: 999, background: 'rgba(0,0,0,0.15)', margin: '4px auto 18px' }}/>

        {/* Hero */}
        <div style={{ textAlign: 'center', marginTop: 4 }}>
          <div style={{ fontSize: 44 }}>🎉</div>
          <div style={{ fontFamily: 'Poppins', fontSize: 22, fontWeight: 600, color: T.text, marginTop: 8, letterSpacing: -0.4, lineHeight: 1.2 }}>¡Bien hecho!</div>
          <div style={{ fontFamily: 'Poppins', fontSize: 13, color: T.muted, marginTop: 4, lineHeight: 1.4 }}>{target}</div>
        </div>

        <div style={{ marginTop: 22, fontFamily: 'Poppins', fontSize: 13, fontWeight: 600, color: T.text, textAlign: 'center', letterSpacing: -0.1 }}>
          ¿Cómo te fue el entreno?
        </div>

        {/* Rating buttons */}
        <div style={{ display: 'flex', gap: 6, marginTop: 14, justifyContent: 'space-between' }}>
          {WORKOUT_RATINGS.map(r => {
            const sel = rating === r.id;
            return (
              <button key={r.id} onClick={() => setRating(r.id)} style={{
                flex: 1, padding: '14px 4px',
                border: sel ? `1.5px solid ${color}` : T.border,
                background: sel ? `${color}15` : T.card,
                borderRadius: 16, cursor: 'pointer',
                display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4,
                transition: 'all 200ms ease',
                transform: sel ? 'scale(1.05)' : 'scale(1)',
              }}>
                <span style={{ fontSize: 28, filter: rating && !sel ? 'grayscale(0.4) opacity(0.6)' : 'none' }}>{r.emoji}</span>
                <span style={{
                  fontFamily: 'Poppins', fontSize: 9, fontWeight: 500,
                  color: sel ? color : T.muted, letterSpacing: 0.2,
                }}>{r.label}</span>
              </button>
            );
          })}
        </div>

        <textarea
          value={comment} onChange={(e) => setComment(e.target.value)}
          placeholder="¿Algún comentario? (opcional)"
          style={{
            marginTop: 14, width: '100%', minHeight: 70, padding: '12px',
            border: T.border, borderRadius: 16, background: T.card,
            fontFamily: 'Poppins', fontSize: 13, color: T.text, resize: 'none', outline: 'none',
          }}/>

        <button onClick={submit} disabled={!rating} style={{
          marginTop: 14, width: '100%', padding: '16px',
          border: 'none', borderRadius: 16, cursor: rating ? 'pointer' : 'not-allowed',
          background: rating ? color : T.subtle,
          color: rating ? '#fff' : T.muted,
          fontFamily: 'Poppins', fontSize: 14, fontWeight: 600, letterSpacing: -0.1,
          transition: 'all 200ms ease',
        }}>Guardar puntuación</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,
        }}>Saltar</button>
      </div>
    </div>
  );
}

Object.assign(window, { AddMealModal, RateWorkoutModal });
