
// ── History Screen — Responsive ───────────────────────────────────────────────
const { useState: useStateHist } = React;

function MiniCalendar({ year, month, selectedDate, onSelect, hasMeal, hasWorkout }) {
  const firstDay = new Date(year, month, 1).getDay();
  const daysInMonth = new Date(year, month+1, 0).getDate();
  const today = new Date().toISOString().split('T')[0];
  const days = [];
  const startOffset = (firstDay+6)%7;
  for (let i=0; i<startOffset; i++) days.push(null);
  for (let d=1; d<=daysInMonth; d++) days.push(d);

  return (
    <div>
      <div style={{ display:'grid', gridTemplateColumns:'repeat(7,1fr)', gap:2, marginBottom:4 }}>
        {['L','M','X','J','V','S','D'].map(d => <div key={d} style={{ textAlign:'center', fontSize:11, color:'#8E8E93', fontWeight:600, padding:'4px 0' }}>{d}</div>)}
        {days.map((d,i) => {
          if (!d) return <div key={i}/>;
          const key = `${year}-${String(month+1).padStart(2,'0')}-${String(d).padStart(2,'0')}`;
          const isSel = key===selectedDate, isT = key===today;
          const meal = hasMeal(key), wk = hasWorkout(key);
          return (
            <div key={i} style={{ textAlign:'center', padding:'6px 2px', borderRadius:8, fontSize:13,
              fontWeight:isT?700:400, background:isSel?'#FF6B35':'transparent',
              color:isSel?'#fff':isT?'#FF6B35':'#1C1C1E', cursor:'pointer' }}
              onClick={() => onSelect(key)}>
              {d}
              <div style={{ display:'flex', justifyContent:'center', gap:2, marginTop:1 }}>
                {meal && <div style={{ width:4, height:4, borderRadius:2, background:isSel?'#fff':'#FF6B35' }}/>}
                {wk   && <div style={{ width:4, height:4, borderRadius:2, background:isSel?'#fff':'#34C759' }}/>}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

function ScreenHistory() {
  const { state, getMealsForDate, getWorkoutsForDate, calcDayNutrition, calcMealNutrition, loadMealsForDate } = useSalud();
  const now = new Date();
  const [year, setYear]     = useStateHist(now.getFullYear());
  const [month, setMonth]   = useStateHist(now.getMonth());
  const [selDate, setSelDate] = useStateHist(now.toISOString().split('T')[0]);

  const hasMeal    = date => state.meals.some(m => m.date===date);
  const hasWorkout = date => state.workouts.some(w => w.date===date);

  const handleSelect = async (date) => { setSelDate(date); await loadMealsForDate(date); };

  const meals    = getMealsForDate(selDate);
  const workouts = getWorkoutsForDate(selDate);
  const nutrition = calcDayNutrition(selDate);
  const burned = workouts.reduce((a,w)=>a+w.kcal,0);
  const MEAL_ORDER = ['Desayuno','Almuerzo','Comida','Merienda','Cena'];
  const sortedMeals = [...meals].sort((a,b)=>MEAL_ORDER.indexOf(a.type)-MEAL_ORDER.indexOf(b.type));
  const WK_ICONS_H = { Fuerza:'🏋️', Cardio:'🏃', HIIT:'⚡', Yoga:'🧘', Natación:'🏊', Ciclismo:'🚴', Otro:'💪' };

  const shiftMonth = n => {
    let m=month+n, y=year;
    if(m<0){m=11;y--;} if(m>11){m=0;y++;}
    setMonth(m); setYear(y);
  };

  const monthName = new Date(year,month,1).toLocaleDateString('es-ES',{month:'long',year:'numeric'});
  const selLabel  = new Date(selDate+'T12:00').toLocaleDateString('es-ES',{weekday:'long',day:'numeric',month:'long'});

  return (
    <div className="page">
      <div className="page-header"><h1>Historial</h1></div>

      <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:16, alignItems:'start' }}>
        {/* Calendar */}
        <div className="card">
          <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:12 }}>
            <button className="btn-ghost" style={{ padding:'6px 12px' }} onClick={()=>shiftMonth(-1)}>‹</button>
            <div style={{ fontWeight:700, textTransform:'capitalize', fontSize:15 }}>{monthName}</div>
            <button className="btn-ghost" style={{ padding:'6px 12px' }} onClick={()=>shiftMonth(1)}>›</button>
          </div>
          <MiniCalendar year={year} month={month} selectedDate={selDate} onSelect={handleSelect} hasMeal={hasMeal} hasWorkout={hasWorkout} />
          <div style={{ display:'flex', gap:14, marginTop:10 }}>
            {[['#FF6B35','Comida'],['#34C759','Entreno']].map(([c,l])=>(
              <div key={l} style={{ display:'flex', alignItems:'center', gap:5, fontSize:11, color:'#8E8E93' }}>
                <div style={{ width:8, height:8, borderRadius:4, background:c }}/>
                {l}
              </div>
            ))}
          </div>
        </div>

        {/* Day detail */}
        <div>
          <div className="card">
            <div style={{ fontWeight:700, fontSize:16, marginBottom:12, textTransform:'capitalize' }}>{selLabel}</div>
            {meals.length===0 && workouts.length===0 ? (
              <div className="empty" style={{ padding:'20px 0' }}>
                <div style={{ fontSize:32, marginBottom:8 }}>📅</div>
                <div className="empty-title">Sin datos</div>
              </div>
            ) : (
              <>
                <div style={{ display:'flex', justifyContent:'space-around', background:'#FFF5F0', borderRadius:10, padding:'10px', marginBottom:12 }}>
                  {[['kcal',Math.round(nutrition.kcal),'#FF6B35'],['quemadas',burned,'#34C759'],['prot',Math.round(nutrition.prot)+'g','#007AFF']].map(([l,v,c])=>(
                    <div key={l} style={{ textAlign:'center' }}>
                      <div style={{ fontWeight:700, fontSize:18, color:c }}>{v}</div>
                      <div style={{ fontSize:10, color:'#8E8E93' }}>{l}</div>
                    </div>
                  ))}
                </div>
                {sortedMeals.map(meal => {
                  const n = calcMealNutrition(meal);
                  return (
                    <div key={meal.id} style={{ marginBottom:10 }}>
                      <div style={{ fontSize:12, fontWeight:700, color:'#FF6B35', textTransform:'uppercase', marginBottom:4 }}>{meal.type} · {Math.round(n.kcal)} kcal</div>
                      {(meal.items||[]).map((item,i) => {
                        const name = item.name || state.foods.find(f=>f.id===(item.food_id||item.foodId))?.name || '—';
                        return <div key={i} style={{ display:'flex', justifyContent:'space-between', fontSize:13, padding:'4px 0', borderBottom:'1px solid #F2F2F7' }}>
                          <span>{name}</span><span style={{ color:'#8E8E93' }}>{item.grams}g</span>
                        </div>;
                      })}
                    </div>
                  );
                })}
                {workouts.map(w => (
                  <div key={w.id} style={{ display:'flex', gap:8, alignItems:'center', padding:'8px 0', borderTop:'1px solid #F2F2F7' }}>
                    <span style={{ fontSize:20 }}>{WK_ICONS_H[w.type]||'💪'}</span>
                    <div style={{ flex:1 }}><div style={{ fontWeight:600 }}>{w.type}</div>{w.notes&&<div style={{ fontSize:12, color:'#8E8E93' }}>{w.notes}</div>}</div>
                    <div style={{ fontWeight:700, color:'#34C759' }}>{w.kcal} kcal</div>
                  </div>
                ))}
              </>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { ScreenHistory });
