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

const { useState: useS5 } = React;

// ═════════════════════════════════════════════════════════════
// Add Meal Modal — anotar comida + foto opcional + guardar frecuente
// ═════════════════════════════════════════════════════════════
function AddMealModal({ open, onClose, onSave, T, accent }) {
  const meals = ['Desayuno', 'Snack', 'Almuerzo', 'Cena'];
  const [meal, setMeal] = useS5('Snack');
  const [text, setText] = useS5('');
  const [hasPhoto, setHasPhoto] = useS5(false);
  const [saveFav, setSaveFav] = useS5(false);
  const [time, setTime] = useS5(initTime());
  const [showFreq, setShowFreq] = useS5(false);

  if (!open) return null;

  function submit() {
    onSave({ meal, text: text || 'Sin descripción', photo: hasPhoto, saved: saveFav, time });
    onClose();
  }

  function pickFav(f) {
    setText(f.title);
    setMeal(f.meal);
    setShowFreq(false);
  }

  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)',
        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' }}/>
        <div style={{ fontFamily: 'Poppins', fontSize: 11, color: T.muted, fontWeight: 500, letterSpacing: 0.5, textTransform: 'uppercase' }}>Anotar comida</div>
        <div style={{ fontFamily: 'Poppins', fontSize: 20, fontWeight: 600, color: T.text, marginTop: 4, letterSpacing: -0.4 }}>¿Qué comiste?</div>

        {/* Tipo de comida + Hora */}
        <div style={{ display: 'flex', gap: 8, marginTop: 16, alignItems: 'stretch' }}>
          <div style={{ flex: 1, display: 'flex', gap: 4 }}>
            {meals.map(m => (
              <button key={m} onClick={() => setMeal(m)} style={{
                flex: 1, padding: '8px 4px', cursor: 'pointer',
                border: meal === m ? `1.5px solid ${accent}` : T.border,
                background: meal === m ? `${accent}10` : T.card,
                borderRadius: 12,
                fontFamily: 'Poppins', fontSize: 11, fontWeight: 600, color: meal === m ? accent : T.text,
              }}>{m}</button>
            ))}
          </div>
        </div>

        {/* Hora picker */}
        <div style={{
          marginTop: 8, padding: '10px 14px',
          background: T.card, borderRadius: 12, border: T.border,
          display: 'flex', alignItems: 'center', gap: 10,
        }}>
          <span style={{ fontSize: 18 }}>🕐</span>
          <span style={{ flex: 1, fontFamily: 'Poppins', fontSize: 12, fontWeight: 500, color: T.text }}>Hora</span>
          <input type="time" value={time} onChange={(e) => setTime(e.target.value)} style={{
            border: 'none', background: T.subtle, borderRadius: 8,
            padding: '6px 10px', fontFamily: 'Poppins', fontSize: 13, fontWeight: 600,
            color: T.text, outline: 'none', letterSpacing: -0.2,
          }}/>
        </div>

        {/* Frecuentes button */}
        <button onClick={() => setShowFreq(true)} style={{
          marginTop: 10, width: '100%', padding: '12px 14px',
          border: T.border, background: T.card,
          borderRadius: 12, cursor: 'pointer',
          fontFamily: 'Poppins', fontSize: 13, fontWeight: 500, color: T.text,
          display: 'flex', alignItems: 'center', gap: 10,
        }}>
          <span style={{ fontSize: 16 }}>⭐</span>
          <span style={{ flex: 1, textAlign: 'left' }}>Mis frecuentes</span>
          {Icon.chevR(T.muted, 8)}
        </button>

        {/* Descripción */}
        <textarea
          value={text} onChange={(e) => setText(e.target.value)}
          placeholder="Bowl de avena con frutas, café con leche…"
          style={{
            marginTop: 10, width: '100%', minHeight: 70, padding: '12px',
            border: T.border, borderRadius: 14, background: T.card,
            fontFamily: 'Poppins', fontSize: 14, color: T.text, resize: 'none', outline: 'none',
          }}/>

        {/* Foto opcional */}
        <button onClick={() => setHasPhoto(!hasPhoto)} style={{
          marginTop: 10, width: '100%', padding: '14px',
          border: hasPhoto ? `1.5px solid ${accent}` : `1.5px dashed ${T.muted}55`,
          borderRadius: 14, 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' : '📷 Foto del plato (opcional)'}
        </button>

        {/* Guardar como frecuente */}
        <div style={{
          marginTop: 10, padding: '12px 14px',
          background: T.card, borderRadius: 14, 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 }}>Guardar como frecuente</div>
            <div style={{ fontFamily: 'Poppins', fontSize: 10, color: T.muted, marginTop: 1 }}>Para anotarla de un tap próxima vez</div>
          </div>
          <button onClick={() => setSaveFav(!saveFav)} style={{
            width: 40, height: 23, borderRadius: 999, border: 'none', cursor: 'pointer',
            background: saveFav ? accent : 'rgba(0,0,0,0.12)', position: 'relative',
            transition: 'background 200ms ease',
          }}>
            <div style={{
              position: 'absolute', top: 3, left: saveFav ? 20 : 3,
              width: 17, height: 17, borderRadius: 999, background: '#fff',
              transition: 'left 200ms ease', boxShadow: '0 1px 3px rgba(0,0,0,0.15)',
            }}/>
          </button>
        </div>

        <button onClick={submit} style={{
          marginTop: 14, width: '100%', padding: '16px',
          border: 'none', borderRadius: 14, cursor: 'pointer',
          background: accent, color: '#fff',
          fontFamily: 'Poppins', fontSize: 14, fontWeight: 600, letterSpacing: -0.1,
        }}>Anotar</button>

        {/* Frecuentes sheet (overlay sobre modal) */}
        {showFreq && <FrequentMealsSheet onClose={() => setShowFreq(false)} onPick={pickFav} T={T} accent={accent}/>}
      </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, textTransform: 'uppercase' }}>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: 14, 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, textTransform: 'uppercase' }}>{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: 14, 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: 14, 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 });
