
// ── Food Log Screen — Responsive ─────────────────────────────────────────────
const { useState: useStateFL, useRef: useRefFL } = React;

const MEAL_TYPES   = ['Desayuno', 'Almuerzo', 'Comida', 'Merienda', 'Cena'];
const MEAL_ICONS_FL = { Desayuno: '🌅', Almuerzo: '☕', Comida: '🍽', Merienda: '🍎', Cena: '🌙' };

const CAT_OPTS_FL = ['Proteína','Carbohidrato','Verdura','Fruta','Grasa saludable','Lácteo','Legumbre','Otro'];

// ── AI Estimate Button ────────────────────────────────────────────────────────
function AIEstimateBtn({ name, grams, onResult }) {
  const [loading, setLoading] = React.useState(false);
  const [msg, setMsg]         = React.useState('');

  const handleEstimate = async () => {
    if (!name || name.trim().length < 2) {
      setMsg('Escribe primero el nombre');
      setTimeout(() => setMsg(''), 2000);
      return;
    }
    setLoading(true); setMsg('');
    try {
      const data = await api.estimateNutrition(name.trim(), parseFloat(grams) || 100);
      onResult({
        cal:   data.cal_100,
        prot:  data.prot_100,
        carbs: data.carbs_100,
        fat:   data.fat_100,
        cat:   data.cat,
      });
      setMsg('✓ Estimado con IA');
    } catch(e) {
      setMsg('Error: ' + e.message);
    } finally {
      setLoading(false);
      setTimeout(() => setMsg(''), 3000);
    }
  };

  return (
    <div style={{ display:'flex', flexDirection:'column', alignItems:'flex-end', gap:4, flexShrink:0 }}>
      <button onClick={handleEstimate} disabled={loading} style={{
        background: loading ? '#F0F0F0' : 'linear-gradient(135deg,#7C3AED,#6D28D9)',
        color: loading ? '#8E8E93' : '#fff', border:'none', borderRadius:10,
        padding:'10px 12px', fontWeight:700, fontSize:13,
        cursor: loading ? 'not-allowed' : 'pointer', whiteSpace:'nowrap',
      }}>
        {loading ? '⏳' : '✨'} {loading ? 'Calculando…' : 'IA'}
      </button>
      {msg && <div style={{ fontSize:11, color: msg.startsWith('✓') ? '#16A34A' : '#FF3B30', fontWeight:600 }}>{msg}</div>}
    </div>
  );
}

// ── Add Food Modal ────────────────────────────────────────────────────────────
function OFFSearch({ query, onSelect }) {
  const [results, setResults] = useStateFL([]);
  const [loading, setLoading] = useStateFL(false);
  const timerRef = React.useRef(null);

  React.useEffect(() => {
    if (query.length < 2) { setResults([]); return; }
    clearTimeout(timerRef.current);
    timerRef.current = setTimeout(async () => {
      setLoading(true);
      try {
        const url = `https://world.openfoodfacts.org/cgi/search.pl?search_terms=${encodeURIComponent(query)}&search_simple=1&action=process&json=1&page_size=6&lc=es`;
        const res = await fetch(url);
        const data = await res.json();
        const items = (data.products || [])
          .filter(p => p.nutriments && p.nutriments['energy-kcal_100g'])
          .map(p => ({
            id: null, // se guardará al añadir
            name: p.product_name_es || p.product_name || p.product_name_en || 'Sin nombre',
            cal:   Math.round(p.nutriments['energy-kcal_100g'] || 0),
            prot:  Math.round((p.nutriments.proteins_100g  || 0) * 10) / 10,
            carbs: Math.round((p.nutriments.carbohydrates_100g || 0) * 10) / 10,
            fat:   Math.round((p.nutriments.fat_100g || 0) * 10) / 10,
            cat:   'Otro',
            _fromOFF: true,
          }));
        setResults(items);
      } catch(e) {
        setResults([]);
      } finally { setLoading(false); }
    }, 500);
    return () => clearTimeout(timerRef.current);
  }, [query]);

  if (!loading && results.length === 0) return null;

  return (
    <div>
      <div style={{ fontSize:11, fontWeight:700, color:'#8E8E93', textTransform:'uppercase', letterSpacing:.5, margin:'4px 0 6px', display:'flex', alignItems:'center', gap:6 }}>
        🌍 Open Food Facts
        {loading && <span style={{ fontSize:11, color:'#AEAEB2' }}>Buscando…</span>}
      </div>
      {results.map((f, i) => (
        <div key={i} className="list-row" style={{ cursor:'pointer', padding:'10px 8px', background:'#FFFDF5' }} onClick={() => onSelect(f)}>
          <div style={{ flex:1 }}>
            <div style={{ fontWeight:600, fontSize:14 }}>{f.name}</div>
            <div style={{ fontSize:11, color:'#8E8E93' }}>P:{f.prot}g · C:{f.carbs}g · G:{f.fat}g</div>
          </div>
          <div style={{ textAlign:'right' }}>
            <div style={{ fontWeight:700, color:'#FF9500', fontSize:14 }}>{f.cal}</div>
            <div style={{ fontSize:10, color:'#8E8E93' }}>kcal/100g</div>
          </div>
        </div>
      ))}
    </div>
  );
}

function AddFoodModal({ mealType, onClose, onSave }) {
  const { state, addFood } = useSalud();
  const [search, setSearch]       = useStateFL('');
  const [selected, setSelected]   = useStateFL(null);
  const [grams, setGrams]         = useStateFL('100');
  const [view, setView]           = useStateFL('search'); // 'search' | 'grams' | 'new'
  const [newFood, setNewFood]     = useStateFL({ name:'', cal:'', prot:'', carbs:'', fat:'', cat:'Proteína' });
  const [newGrams, setNewGrams]   = useStateFL('150');
  const [savingFood, setSaving]   = useStateFL(false);

  const filtered = state.foods.filter(f => f.name.toLowerCase().includes(search.toLowerCase())).slice(0, 40);
  const preview  = selected ? {
    kcal:  selected.cal   * (+grams||0) / 100,
    prot:  selected.prot  * (+grams||0) / 100,
    carbs: selected.carbs * (+grams||0) / 100,
    fat:   selected.fat   * (+grams||0) / 100,
  } : null;

  const openNew = () => { setNewFood(f => ({ ...f, name: search })); setView('new'); };

  const handleCreateAndSelect = async () => {
    if (!newFood.name || !newFood.cal) return;
    setSaving(true);
    const created = await addFood({ ...newFood, cal:+newFood.cal, prot:+newFood.prot||0, carbs:+newFood.carbs||0, fat:+newFood.fat||0 });
    setSaving(false);
    if (created) { setSelected(created); setView('grams'); }
  };

  const pickFood = async (f) => {
    // Si viene de OFF, guardarlo primero en la biblioteca
    if (f._fromOFF) {
      setSaving(true);
      const created = await addFood({ name:f.name, cal:f.cal, prot:f.prot, carbs:f.carbs, fat:f.fat, cat:f.cat });
      setSaving(false);
      setSelected(created || f);
    } else {
      setSelected(f);
    }
    setView('grams');
  };
  const setNF = k => e => setNewFood(f => ({ ...f, [k]: e.target.value }));

  return (
    <div className="modal-overlay" onClick={e => e.target === e.currentTarget && onClose()}>
      <div className="modal">
        <div className="modal-handle" />
        <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:16 }}>
          <div className="modal-title" style={{ marginBottom:0 }}>
            {view === 'new' ? 'Nuevo alimento' : `Añadir a ${mealType}`}
          </div>
          <button className="btn-ghost" onClick={onClose}>Cancelar</button>
        </div>

        {/* ── Search view ── */}
        {view === 'search' && (
          <>
            <div className="search-wrap" style={{ marginBottom:12 }}>
              <span className="search-icon">🔍</span>
              <input className="search-input" placeholder="Buscar alimento…" value={search}
                onChange={e => setSearch(e.target.value)} autoFocus />
            </div>

            {/* Siempre visible: buscar en Open Food Facts */}
            {search.length > 1 && (
              <OFFSearch query={search} onSelect={food => { setSelected(food); setView('grams'); }} />
            )}

            {/* Biblioteca local */}
            {filtered.length > 0 && (
              <>
                <div style={{ fontSize:11, fontWeight:700, color:'#8E8E93', textTransform:'uppercase', letterSpacing:.5, margin:'12px 0 6px' }}>Tu biblioteca</div>
                <div style={{ maxHeight:220, overflowY:'auto' }}>
                  {filtered.map(f => (
                    <div key={f.id} className="list-row" style={{ cursor:'pointer', padding:'10px 8px' }} onClick={() => pickFood(f)}>
                      <div style={{ flex:1 }}>
                        <div style={{ fontWeight:600, fontSize:15 }}>{f.name}</div>
                        <div style={{ fontSize:12, color:'#8E8E93' }}>{f.cat}</div>
                      </div>
                      <div style={{ textAlign:'right' }}>
                        <div style={{ fontWeight:700, color:'#FF6B35' }}>{f.cal}</div>
                        <div style={{ fontSize:11, color:'#8E8E93' }}>kcal/100g</div>
                      </div>
                    </div>
                  ))}
                </div>
              </>
            )}

            {/* Siempre: botón añadir a mano */}
            <div style={{ padding:'12px 0 0', borderTop:'1px solid #F2F2F7', marginTop:8 }}>
              <button className="btn-ghost" style={{ width:'100%', color:'#FF6B35', borderColor:'#FFD6C4' }}
                onClick={openNew}>
                ✏️ Añadir alimento a mano{search.length > 1 ? ` "${search}"` : ''}
              </button>
            </div>
          </>
        )}

        {/* ── Grams view ── */}
        {view === 'grams' && selected && (
          <>
            <div style={{ fontWeight:700, fontSize:17, marginBottom:16 }}>{selected.name}</div>
            <div className="form-group">
              <label className="form-label">Gramos</label>
              <div style={{ display:'flex', gap:8, alignItems:'center' }}>
                <button className="btn-secondary" onClick={() => setGrams(g => String(Math.max(5,+g-10)))}>−</button>
                <input className="form-input" type="number" value={grams} onChange={e => setGrams(e.target.value)} style={{ textAlign:'center', fontWeight:700, fontSize:18 }} />
                <button className="btn-secondary" onClick={() => setGrams(g => String(+g+10))}>+</button>
                <span style={{ color:'#8E8E93', fontSize:14 }}>g</span>
              </div>
            </div>
            {preview && (
              <div style={{ background:'#FFF5F0', borderRadius:12, padding:'12px', display:'flex', justifyContent:'space-around', marginBottom:16 }}>
                {[['kcal',Math.round(preview.kcal)],['prot',Math.round(preview.prot)+'g'],['carbs',Math.round(preview.carbs)+'g'],['grasa',Math.round(preview.fat)+'g']].map(([l,v]) => (
                  <div key={l} style={{ textAlign:'center' }}>
                    <div style={{ fontWeight:700, fontSize:17, color:'#FF6B35' }}>{v}</div>
                    <div style={{ fontSize:11, color:'#8E8E93' }}>{l}</div>
                  </div>
                ))}
              </div>
            )}
            <div style={{ display:'flex', gap:10 }}>
              <button className="btn-secondary" style={{ flex:1 }} onClick={() => setView('search')}>← Volver</button>
              <button className="btn-primary" style={{ flex:2 }} onClick={() => { onSave(selected.id, +grams); onClose(); }}>
                Añadir {grams}g
              </button>
            </div>
          </>
        )}

        {/* ── New food view ── */}
        {view === 'new' && (
          <>
            <div className="form-group">
              <label className="form-label">Nombre del alimento</label>
              <div style={{ display:'flex', gap:8 }}>
                <input className="form-input" value={newFood.name} onChange={setNF('name')}
                  placeholder="Ej: Tortilla de patatas" autoFocus style={{ flex:1 }} />
              </div>
            </div>
            <div className="form-row">
              <div className="form-group" style={{ flex:2 }}>
                <label className="form-label">Gramos de la porción</label>
                <input className="form-input" type="number" value={newGrams}
                  onChange={e => setNewGrams(e.target.value)} placeholder="150" />
              </div>
              <div className="form-group" style={{ flex:1, display:'flex', flexDirection:'column', justifyContent:'flex-end' }}>
                <label className="form-label" style={{ opacity:0 }}>IA</label>
                <AIEstimateBtn name={newFood.name} grams={newGrams}
                  onResult={r => setNewFood(f => ({ ...f, cal:r.cal, prot:r.prot, carbs:r.carbs, fat:r.fat, cat:r.cat }))} />
              </div>
            </div>

            {/* Preview total si ya hay datos */}
            {newFood.cal && newGrams && (
              <div style={{ background:'#FFF5F0', borderRadius:10, padding:'10px 14px', display:'flex', justifyContent:'space-around', marginBottom:12 }}>
                {[
                  ['kcal', Math.round(newFood.cal * +newGrams / 100)],
                  ['prot', Math.round(newFood.prot * +newGrams / 100 * 10)/10 + 'g'],
                  ['carbs', Math.round(newFood.carbs * +newGrams / 100 * 10)/10 + 'g'],
                  ['grasa', Math.round(newFood.fat * +newGrams / 100 * 10)/10 + 'g'],
                ].map(([l,v]) => (
                  <div key={l} style={{ textAlign:'center' }}>
                    <div style={{ fontWeight:700, fontSize:16, color:'#FF6B35' }}>{v}</div>
                    <div style={{ fontSize:10, color:'#8E8E93' }}>{l} en {newGrams}g</div>
                  </div>
                ))}
              </div>
            )}

            <div className="card-title" style={{ marginTop:4 }}>Valores por 100g (editables)</div>
            <div className="form-row" style={{ marginBottom:4 }}>
              <div className="form-group">
                <label className="form-label">Kcal</label>
                <input className="form-input" type="number" value={newFood.cal} onChange={setNF('cal')} placeholder="kcal" />
              </div>
              <div className="form-group">
                <label className="form-label">Prot g</label>
                <input className="form-input" type="number" value={newFood.prot} onChange={setNF('prot')} />
              </div>
              <div className="form-group">
                <label className="form-label">Carbs g</label>
                <input className="form-input" type="number" value={newFood.carbs} onChange={setNF('carbs')} />
              </div>
              <div className="form-group">
                <label className="form-label">Grasa g</label>
                <input className="form-input" type="number" value={newFood.fat} onChange={setNF('fat')} />
              </div>
            </div>

            <div className="form-group">
              <label className="form-label">Categoría</label>
              <div style={{ display:'flex', flexWrap:'wrap', gap:6, marginBottom:16 }}>
                {CAT_OPTS_FL.map(c => (
                  <button key={c} className="chip"
                    style={{ background:newFood.cat===c?'#FF6B35':'#F0F0F0', color:newFood.cat===c?'#fff':'#8E8E93', fontSize:12 }}
                    onClick={() => setNewFood(f => ({ ...f, cat:c }))}>{c}</button>
                ))}
              </div>
            </div>

            <div style={{ display:'flex', gap:10 }}>
              <button className="btn-secondary" style={{ flex:1 }} onClick={() => setView('search')}>← Volver</button>
              <button className="btn-primary" style={{ flex:2 }} onClick={async () => {
                if (!newFood.name || !newFood.cal) return;
                setSaving(true);
                const created = await addFood({ ...newFood, cal:+newFood.cal, prot:+newFood.prot||0, carbs:+newFood.carbs||0, fat:+newFood.fat||0 });
                setSaving(false);
                if (created) {
                  setSelected(created);
                  setGrams(newGrams);
                  setView('grams');
                }
              }} disabled={savingFood}>
                {savingFood ? 'Guardando…' : '+ Crear y añadir'}
              </button>
            </div>
          </>
        )}
      </div>
    </div>
  );
}

function ScreenFoodLog() {
  const { state, loadMealsForDate, addMeal, updateMeal, deleteMeal, calcMealNutrition, calcDayNutrition } = useSalud();
  const [selDate, setSelDate] = useStateFL(new Date().toISOString().split('T')[0]);
  const [addModal, setAddModal] = useStateFL(null);
  const [expanded, setExpanded] = useStateFL({});
  const [loadingDate, setLoadingDate] = useStateFL(false);

  const meals = state.meals.filter(m => m.date === selDate);
  const dayNutrition = calcDayNutrition(selDate);
  const { goals } = state;

  const shiftDate = async (n) => {
    const d = new Date(selDate + 'T12:00'); d.setDate(d.getDate() + n);
    const newDate = d.toISOString().split('T')[0];
    setSelDate(newDate);
    setLoadingDate(true);
    await loadMealsForDate(newDate);
    setLoadingDate(false);
  };

  const handleSaveFood = async (mealType, foodId, grams) => {
    const existing = meals.find(m => m.type === mealType);
    if (existing) {
      const newItems = [...(existing.items||[]).map(i => ({ foodId: i.food_id || i.foodId, grams: i.grams })), { foodId, grams }];
      await updateMeal({ ...existing, date: selDate, type: mealType, items: newItems });
    } else {
      await addMeal({ date: selDate, type: mealType, items: [{ foodId, grams }] });
    }
  };

  const handleRemoveItem = async (meal, itemIdx) => {
    const newItems = (meal.items||[]).filter((_, i) => i !== itemIdx).map(i => ({ foodId: i.food_id || i.foodId, grams: i.grams }));
    if (newItems.length === 0) await deleteMeal(meal.id, meal.date);
    else await updateMeal({ ...meal, items: newItems });
  };

  const isToday = selDate === new Date().toISOString().split('T')[0];
  const dateLabel = new Date(selDate + 'T12:00').toLocaleDateString('es-ES', { weekday: 'long', day: 'numeric', month: 'long' });
  const MEAL_ORDER = ['Desayuno', 'Almuerzo', 'Comida', 'Merienda', 'Cena'];

  return (
    <div className="page">
      <div className="page-header">
        <h1>Registro de comidas</h1>
      </div>

      {/* Date nav */}
      <div className="card" style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '14px 20px' }}>
        <button className="btn-ghost" style={{ padding: '8px 14px' }} onClick={() => shiftDate(-1)}>‹</button>
        <div style={{ flex: 1, textAlign: 'center' }}>
          <div style={{ fontWeight: 700, fontSize: 16, textTransform: 'capitalize' }}>{isToday ? 'Hoy' : dateLabel}</div>
          {!isToday && <div style={{ fontSize: 12, color: '#8E8E93', textTransform: 'capitalize' }}>{dateLabel}</div>}
        </div>
        <button className="btn-ghost" style={{ padding: '8px 14px' }} onClick={() => shiftDate(1)}>›</button>
        {!isToday && <button className="btn-secondary" style={{ fontSize: 13 }} onClick={async () => { const t = new Date().toISOString().split('T')[0]; setSelDate(t); await loadMealsForDate(t); }}>Hoy</button>}
      </div>

      {/* Macro summary */}
      <div className="grid-4" style={{ marginBottom: 16 }}>
        {[
          ['Kcal', Math.round(dayNutrition.kcal), goals.kcal, ''],
          ['Proteína', Math.round(dayNutrition.prot), goals.prot, 'g'],
          ['Carbos', Math.round(dayNutrition.carbs), goals.carbs, 'g'],
          ['Grasa', Math.round(dayNutrition.fat), goals.fat, 'g'],
        ].map(([label, val, goal, unit]) => (
          <div key={label} className="stat-card">
            <div className="stat-val" style={{ fontSize: 20 }}>{val}{unit}</div>
            <div className="stat-label">/ {goal}{unit} {label}</div>
            <div className="prog-bar" style={{ marginTop: 8 }}>
              <div className="prog-fill" style={{ width: `${Math.min(val/goal*100,100)}%`, background: '#FF6B35' }} />
            </div>
          </div>
        ))}
      </div>

      {/* Meals */}
      {loadingDate ? (
        <div className="empty"><div className="empty-icon">⏳</div><div className="empty-title">Cargando…</div></div>
      ) : MEAL_ORDER.map(type => {
        const meal = meals.find(m => m.type === type);
        const n = meal ? calcMealNutrition(meal) : null;
        const isExp = expanded[type] !== false;
        return (
          <div key={type} className="card" style={{ padding: 0, overflow: 'hidden' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '14px 20px', cursor: 'pointer' }}
              onClick={() => setExpanded(e => ({ ...e, [type]: !isExp }))}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                <span style={{ fontSize: 20 }}>{MEAL_ICONS_FL[type]}</span>
                <div>
                  <div style={{ fontWeight: 700, fontSize: 16 }}>{type}</div>
                  {meal && <div style={{ fontSize: 12, color: '#8E8E93' }}>{meal.items?.length || 0} alimentos</div>}
                </div>
              </div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                {n && <span style={{ fontWeight: 700, color: '#FF6B35', fontSize: 15 }}>{Math.round(n.kcal)} kcal</span>}
                <span style={{ color: '#AEAEB2', fontSize: 12 }}>{isExp ? '▲' : '▼'}</span>
              </div>
            </div>
            {isExp && (
              <div style={{ borderTop: '1px solid #F2F2F7' }}>
                {meal && (meal.items||[]).map((item, idx) => {
                  const foodName = item.name || state.foods.find(f => f.id === (item.food_id||item.foodId))?.name || '—';
                  const cal  = item.cal  || state.foods.find(f => f.id === (item.food_id||item.foodId))?.cal  || 0;
                  const prot = item.prot || state.foods.find(f => f.id === (item.food_id||item.foodId))?.prot || 0;
                  const itemKcal = cal * item.grams / 100;
                  const itemProt = prot * item.grams / 100;
                  return (
                    <div key={idx} className="list-row" style={{ padding: '10px 20px' }}>
                      <div style={{ flex: 1 }}>
                        <div style={{ fontWeight: 500, fontSize: 15 }}>{foodName}</div>
                        <div style={{ fontSize: 12, color: '#8E8E93' }}>{item.grams}g · {Math.round(itemProt)}g prot</div>
                      </div>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                        <div style={{ textAlign: 'right' }}>
                          <div style={{ fontWeight: 600, color: '#8E8E93', fontSize: 14 }}>{Math.round(itemKcal)} kcal</div>
                        </div>
                        <button style={{ background: 'none', border: 'none', color: '#FF3B30', fontSize: 18, cursor: 'pointer', padding: '0 4px', lineHeight: 1 }}
                          onClick={() => handleRemoveItem(meal, idx)}>×</button>
                      </div>
                    </div>
                  );
                })}
                <div style={{ padding: '10px 20px', borderTop: meal && meal.items?.length ? '1px solid #F2F2F7' : 'none' }}>
                  <button className="btn-ghost" style={{ width: '100%', color: '#FF6B35', borderColor: '#FFD6C4' }}
                    onClick={() => setAddModal({ type })}>
                    + Añadir alimento
                  </button>
                </div>
              </div>
            )}
          </div>
        );
      })}

      {addModal && (
        <AddFoodModal mealType={addModal.type} onClose={() => setAddModal(null)}
          onSave={(foodId, grams) => handleSaveFood(addModal.type, foodId, grams)} />
      )}
    </div>
  );
}

Object.assign(window, { ScreenFoodLog });
