/* Nutri screens — Home / Calendar / Add / Foods / Progress / MealDetail */

// ─────────────────────────────────────────────────────────────
// HOME — main dashboard (matches refs 2 + 3)
// ─────────────────────────────────────────────────────────────
function HomeScreen({ entries, goals, selectedDate, setSelectedDate, onOpenMeal, macroStyle }) {
  const totals = nutriDayTotals(entries, selectedDate);
  const dayEntries = entries.filter(e => e.date === selectedDate)
    .sort((a,b) => (a.time||'').localeCompare(b.time||''));

  return (
    <div style={{ padding: '12px 18px 24px', display: 'flex', flexDirection: 'column', gap: 16 }}>
      {/* Greeting / brand */}
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', paddingTop: 4 }}>
        <div>
          <div style={{ fontSize: 22, fontWeight: 700, letterSpacing: '-0.02em' }}>Today</div>
          <div style={{ fontSize: 12.5, color: 'var(--muted)', marginTop: 2, fontWeight: 500 }}>
            {prettyDate(selectedDate)}
          </div>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <button className="nutri-icon-btn" style={iconBtn} aria-label="Search">
            <SearchIcon size={18}/>
          </button>
        </div>
      </div>

      {/* Day strip */}
      <DayStrip selected={selectedDate} onSelect={setSelectedDate} days={7}/>

      {/* Hero card */}
      <CalorieHeroCard totals={totals} goals={goals} macroStyle={macroStyle}/>

      {/* Quick action chips */}
      <div style={{ display: 'flex', gap: 10, overflowX: 'auto', paddingBottom: 4, margin: '0 -18px', padding: '0 18px 4px' }}>
        <QuickChip icon={<CameraIcon size={14}/>} label="Scan food"/>
        <QuickChip icon={<BarcodeIcon size={14}/>} label="Barcode"/>
        <QuickChip icon={<EditIcon size={14}/>} label="Quick log"/>
        <QuickChip icon={<TrendUpIcon size={14}/>} label="Weigh in"/>
      </div>

      {/* Recently logged */}
      <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginTop: 4 }}>
        <div style={{ fontSize: 16, fontWeight: 600, letterSpacing: '-0.01em' }}>Recently logged</div>
        <div style={{ fontSize: 12.5, color: 'var(--muted)', fontWeight: 500 }}>{dayEntries.length} meals</div>
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
        {dayEntries.length ? dayEntries.map(e => (
          <MealCard key={e.id} entry={e} onClick={() => onOpenMeal(e)} />
        )) : (
          <EmptyState icon="🍽️" title="Nothing logged yet" subtitle="Tap the + button to log your first meal of the day."/>
        )}
      </div>

      {/* footer space for bottom nav */}
      <div style={{ height: 60 }}/>
    </div>
  );
}

function prettyDate(iso){
  const d = new Date(iso + 'T00:00:00');
  const t = new Date(); t.setHours(0,0,0,0);
  const y = new Date(t); y.setDate(t.getDate()-1);
  if (iso === isoOf(t)) return 'Today · ' + d.toLocaleDateString(undefined,{month:'short', day:'numeric'});
  if (iso === isoOf(y)) return 'Yesterday · ' + d.toLocaleDateString(undefined,{month:'short', day:'numeric'});
  return d.toLocaleDateString(undefined,{weekday:'long', month:'short', day:'numeric'});
}

const iconBtn = {
  width: 36, height: 36, borderRadius: '50%',
  background: 'var(--surface)', border: '1px solid var(--border-2)',
  color: 'var(--text)', display: 'grid', placeItems: 'center', cursor: 'pointer',
};

function QuickChip({ icon, label }) {
  return (
    <button style={{
      display: 'inline-flex', alignItems: 'center', gap: 6,
      padding: '7px 13px', borderRadius: 999,
      background: 'var(--surface-2)', border: '1px solid var(--border)',
      color: 'var(--text)', font: 'inherit', fontSize: 12.5, fontWeight: 500,
      cursor: 'pointer', whiteSpace: 'nowrap',
    }}>
      {icon}<span>{label}</span>
    </button>
  );
}

function EmptyState({ icon, title, subtitle }) {
  return (
    <div style={{
      ...nutriStyles.card, padding: '28px 18px',
      display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6,
      textAlign: 'center',
    }}>
      <div style={{ fontSize: 32, marginBottom: 4 }}>{icon}</div>
      <div style={{ fontWeight: 600, fontSize: 14 }}>{title}</div>
      <div style={{ fontSize: 12.5, color: 'var(--muted)', maxWidth: 240 }}>{subtitle}</div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// CALENDAR — month grid with daily totals
// ─────────────────────────────────────────────────────────────
function CalendarScreen({ entries, goals, onSelectDay }) {
  const today = new Date();
  const [yr, setYr] = React.useState(today.getFullYear());
  const [mo, setMo] = React.useState(today.getMonth()); // 0-11
  const totalsByDay = React.useMemo(() => {
    const m = {};
    entries.forEach(e => {
      m[e.date] = (m[e.date] || 0) + e.calories;
    });
    return m;
  }, [entries]);

  const monthName = new Date(yr, mo, 1).toLocaleString(undefined, { month: 'long', year: 'numeric' });
  const first = new Date(yr, mo, 1).getDay();
  const days = new Date(yr, mo+1, 0).getDate();
  const cells = [];
  for (let i=0; i<first; i++) cells.push(null);
  for (let d=1; d<=days; d++) cells.push(d);

  const todayISO = isoOf(today);
  const [selected, setSelected] = React.useState(todayISO);

  const monthEntries = entries.filter(e => {
    const [y, m] = e.date.split('-').map(Number);
    return y === yr && m-1 === mo;
  });
  const monthAvg = (() => {
    const days = new Set(monthEntries.map(e => e.date));
    if (!days.size) return 0;
    return Math.round(monthEntries.reduce((s,e)=>s+e.calories,0) / days.size);
  })();

  const selectedTotals = nutriDayTotals(entries, selected);
  const selectedEntries = entries.filter(e=>e.date===selected).sort((a,b)=>(a.time||'').localeCompare(b.time||''));

  function shiftMonth(delta){
    let nm = mo + delta, ny = yr;
    if (nm < 0) { nm = 11; ny -= 1; }
    if (nm > 11) { nm = 0; ny += 1; }
    setMo(nm); setYr(ny);
  }

  return (
    <div style={{ padding: '12px 18px 24px', display: 'flex', flexDirection: 'column', gap: 16 }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', paddingTop: 4 }}>
        <div>
          <div style={{ fontSize: 22, fontWeight: 700, letterSpacing: '-0.02em' }}>Calendar</div>
          <div style={{ fontSize: 12.5, color: 'var(--muted)', marginTop: 2, fontWeight: 500 }}>
            Avg this month · <span style={{ color: 'var(--text-2)', fontWeight: 600 }}>{monthAvg.toLocaleString()} kcal</span>
          </div>
        </div>
      </div>

      <div style={{ ...nutriStyles.card, padding: 16 }}>
        {/* month nav */}
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12 }}>
          <button onClick={()=>shiftMonth(-1)} style={iconBtnGhost}>‹</button>
          <div style={{ fontSize: 14, fontWeight: 600 }}>{monthName}</div>
          <button onClick={()=>shiftMonth(1)} style={iconBtnGhost}>›</button>
        </div>
        {/* DOW header */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7,1fr)', gap: 4, marginBottom: 6 }}>
          {['S','M','T','W','T','F','S'].map((d,i)=>(
            <div key={i} style={{ textAlign:'center', fontSize: 10.5, color:'var(--muted)', fontWeight:600, letterSpacing:'0.04em' }}>{d}</div>
          ))}
        </div>
        {/* grid */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7,1fr)', gap: 4 }}>
          {cells.map((d,i) => {
            if (!d) return <div key={i}/>;
            const iso = `${yr}-${String(mo+1).padStart(2,'0')}-${String(d).padStart(2,'0')}`;
            const total = totalsByDay[iso] || 0;
            const isToday = iso === todayISO;
            const isSel = iso === selected;
            const intensity = total ? Math.min(1, total / goals.calories) : 0;
            return (
              <button key={i} onClick={()=>setSelected(iso)} style={{
                aspectRatio: '1 / 1',
                display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
                borderRadius: 10,
                border: isSel ? '1.5px solid var(--text)' : '1px solid var(--border)',
                background: total
                  ? `color-mix(in oklch, var(--c-protein) ${intensity*22}%, var(--surface-2))`
                  : 'var(--surface-2)',
                color: 'var(--text)',
                cursor: 'pointer',
                font: 'inherit',
                gap: 1,
              }}>
                <div style={{ fontSize: 12, fontWeight: isToday ? 700 : 500 }}>{d}</div>
                {total > 0 && (
                  <div style={{ fontSize: 8.5, color: 'var(--muted)', fontWeight: 500 }}>
                    {total >= 1000 ? (total/1000).toFixed(1)+'k' : total}
                  </div>
                )}
              </button>
            );
          })}
        </div>
      </div>

      {/* Selected day detail */}
      <div style={{ fontSize: 16, fontWeight: 600, letterSpacing: '-0.01em' }}>
        {prettyDate(selected)}
      </div>
      <div style={{ ...nutriStyles.card, padding: 16 }}>
        {selectedTotals.calories > 0 ? (
          <>
            <div style={{ display:'flex', alignItems:'center', justifyContent: 'space-between' }}>
              <div>
                <div style={{ fontSize: 28, fontWeight: 600, letterSpacing: '-0.03em' }}>
                  {selectedTotals.calories.toLocaleString()}
                  <span style={{ fontSize: 13, fontWeight: 500, color: 'var(--muted)', marginLeft: 6 }}>/ {goals.calories} kcal</span>
                </div>
                <div style={{ fontSize: 12, color: 'var(--muted)', marginTop: 2 }}>
                  {Math.round((selectedTotals.calories/goals.calories)*100)}% of goal
                </div>
              </div>
              <CalorieRing value={selectedTotals.calories} goal={goals.calories} size={72} stroke={8}/>
            </div>
            <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr 1fr', gap: 12, marginTop: 14 }}>
              {[
                {label:'Protein', val:selectedTotals.protein_g, goal:goals.protein_g, c:'var(--c-protein)'},
                {label:'Carbs', val:selectedTotals.carbs_g, goal:goals.carbs_g, c:'var(--c-carbs)'},
                {label:'Fat', val:selectedTotals.fat_g, goal:goals.fat_g, c:'var(--c-fat)'},
              ].map(m=>(
                <div key={m.label}>
                  <div style={{ fontSize: 14, fontWeight: 600 }}>{m.val}<span style={{color:'var(--muted)', fontWeight:500}}>/{m.goal}g</span></div>
                  <div style={{ fontSize: 11, color:'var(--muted)', marginBottom:6 }}>{m.label}</div>
                  <MacroBar value={m.val} goal={m.goal} color={m.c}/>
                </div>
              ))}
            </div>
          </>
        ) : (
          <div style={{ textAlign:'center', padding: '14px 0', color: 'var(--muted)', fontSize: 13 }}>
            No meals logged on this day
          </div>
        )}
      </div>

      {selectedEntries.length > 0 && (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {selectedEntries.map(e => (
            <MealCard key={e.id} entry={e} onClick={()=>onSelectDay && onSelectDay(e)} compact />
          ))}
        </div>
      )}

      <div style={{ height: 60 }}/>
    </div>
  );
}

const iconBtnGhost = {
  width: 32, height: 32, borderRadius: '50%',
  background: 'transparent', border: '1px solid var(--border)',
  color: 'var(--text)', display: 'grid', placeItems: 'center', cursor: 'pointer',
  fontSize: 18, fontFamily: 'inherit',
};

// ─────────────────────────────────────────────────────────────
// FOODS — food library grid (matches ref 1 — Sweetgreen-style)
// ─────────────────────────────────────────────────────────────
function FoodsScreen({ onPickFood }) {
  const [tab, setTab] = React.useState('all');
  const [q, setQ] = React.useState('');
  const tabs = [
    { id:'all',       label:'ALL' },
    { id:'protein',   label:'PROTEIN' },
    { id:'carb',      label:'CARBS' },
    { id:'fat',       label:'FATS' },
    { id:'fruit',     label:'FRUITS' },
    { id:'snack',     label:'SNACKS' },
  ];
  const filtered = NUTRI_FOODS.filter(f => {
    const matchTab = tab === 'all' || f.tag === tab;
    const matchQ = !q || f.name.toLowerCase().includes(q.toLowerCase());
    return matchTab && matchQ;
  });

  return (
    <div style={{ padding: '12px 18px 24px', display:'flex', flexDirection:'column', gap: 14 }}>
      <div style={{ paddingTop: 4 }}>
        <div style={{ fontSize: 22, fontWeight: 700, letterSpacing: '-0.02em' }}>Foods</div>
        <div style={{ fontSize: 12.5, color: 'var(--muted)', marginTop: 2, fontWeight: 500 }}>
          Library · {NUTRI_FOODS.length} items
        </div>
      </div>

      {/* search */}
      <div style={{
        ...nutriStyles.card,
        display: 'flex', alignItems: 'center', gap: 10,
        padding: '10px 14px', borderRadius: 14,
      }}>
        <SearchIcon size={16}/>
        <input value={q} onChange={e=>setQ(e.target.value)}
          placeholder="Search foods, meals, brands..."
          style={{
            flex: 1, border: 0, background: 'transparent', outline: 'none',
            font: 'inherit', fontSize: 14, color: 'var(--text)',
          }}/>
      </div>

      {/* category tabs — underline style from ref 1 */}
      <div style={{
        display: 'flex', gap: 18, overflowX: 'auto',
        borderBottom: '1px solid var(--border)',
        margin: '0 -18px', padding: '0 18px',
      }}>
        {tabs.map(t => {
          const active = tab === t.id;
          return (
            <button key={t.id} onClick={()=>setTab(t.id)} style={{
              background: 'transparent', border: 0,
              padding: '8px 0 10px',
              fontSize: 11, fontWeight: 600, letterSpacing: '0.08em',
              color: active ? 'var(--text)' : 'var(--muted)',
              borderBottom: active ? '2px solid var(--text)' : '2px solid transparent',
              cursor: 'pointer', font: 'inherit',
            }}>{t.label}</button>
          );
        })}
      </div>

      <div style={{ fontSize: 14, fontWeight: 600, marginTop: 4 }}>
        {tabs.find(t=>t.id===tab).label.toLowerCase()} <span style={{ color:'var(--muted)', fontWeight:500 }}>({filtered.length})</span>
      </div>

      {/* food grid — selectable cards like ref 1 */}
      <div style={{
        display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 10,
      }}>
        {filtered.map(f => (
          <FoodCard key={f.id} food={f} onClick={()=>onPickFood(f)}/>
        ))}
      </div>

      <div style={{ height: 60 }}/>
    </div>
  );
}

function FoodCard({ food, onClick, selected = false }) {
  return (
    <button onClick={onClick} style={{
      background: 'var(--surface-2)',
      border: selected ? '1.5px solid var(--text)' : '1px solid var(--border)',
      borderRadius: 14,
      padding: '12px 8px',
      display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6,
      cursor: 'pointer', font: 'inherit', color: 'var(--text)',
      transition: 'transform .12s ease',
    }}
    onMouseDown={e=>e.currentTarget.style.transform='scale(.97)'}
    onMouseUp={e=>e.currentTarget.style.transform=''}
    onMouseLeave={e=>e.currentTarget.style.transform=''}
    >
      <div style={{ fontSize: 34, lineHeight: 1, marginTop: 4 }}>{food.emoji}</div>
      <div style={{
        fontSize: 11.5, fontWeight: 500, textAlign: 'center',
        lineHeight: 1.2,
        marginTop: 2,
      }}>{food.name}</div>
      <div style={{ fontSize: 10, color: 'var(--muted)', fontWeight: 500 }}>
        {food.cal} cal · {food.qty}
      </div>
    </button>
  );
}

// ─────────────────────────────────────────────────────────────
// ADD — log food sheet (full screen)
// ─────────────────────────────────────────────────────────────
function AddScreen({ onClose, onLog }) {
  const [tab, setTab] = React.useState('search'); // scan / search / quick
  const [q, setQ] = React.useState('');
  const [meal, setMeal] = React.useState('breakfast');
  const filtered = NUTRI_FOODS.filter(f => !q || f.name.toLowerCase().includes(q.toLowerCase()));

  return (
    <div style={{ display:'flex', flexDirection:'column', height:'100%', background:'var(--bg)' }}>
      {/* header */}
      <div style={{ padding: '14px 18px 10px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <button onClick={onClose} style={iconBtn}><XIcon size={18}/></button>
        <div style={{ fontSize: 15, fontWeight: 600 }}>Log food</div>
        <button onClick={onClose} style={{
          background: 'transparent', border: 0, color: 'var(--muted)',
          fontSize: 13, fontWeight: 500, font: 'inherit', cursor: 'pointer',
        }}>Cancel</button>
      </div>

      {/* meal-type segmented */}
      <div style={{ padding: '0 18px 10px' }}>
        <div style={{
          display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: 4,
          background: 'var(--surface-2)', borderRadius: 12, padding: 4, border: '1px solid var(--border)',
        }}>
          {['breakfast','lunch','dinner','snack'].map(m => (
            <button key={m} onClick={()=>setMeal(m)} style={{
              padding: '7px 0', borderRadius: 9,
              border: 0,
              background: meal===m ? 'var(--surface)' : 'transparent',
              color: meal===m ? 'var(--text)' : 'var(--muted)',
              fontSize: 12, fontWeight: 600, cursor: 'pointer', font: 'inherit',
              boxShadow: meal===m ? 'var(--shadow-sm)' : 'none',
              textTransform: 'capitalize',
            }}>{m}</button>
          ))}
        </div>
      </div>

      {/* method tabs */}
      <div style={{ padding: '0 18px', display:'flex', gap: 10 }}>
        {[
          { id:'scan',   label:'Scan',   icon:<CameraIcon size={14}/> },
          { id:'search', label:'Search', icon:<SearchIcon size={14}/> },
          { id:'quick',  label:'Quick log', icon:<EditIcon size={14}/> },
        ].map(t => (
          <button key={t.id} onClick={()=>setTab(t.id)} style={{
            display: 'inline-flex', alignItems: 'center', gap: 6,
            padding: '7px 14px', borderRadius: 999,
            background: tab===t.id ? 'var(--text)' : 'var(--surface)',
            color: tab===t.id ? 'var(--bg)' : 'var(--text)',
            border: tab===t.id ? '1px solid var(--text)' : '1px solid var(--border-2)',
            fontSize: 12.5, fontWeight: 500, cursor: 'pointer', font: 'inherit',
          }}>{t.icon}{t.label}</button>
        ))}
      </div>

      {/* body */}
      <div style={{ flex: 1, overflow: 'auto', padding: '14px 18px 100px' }}>
        {tab === 'search' && (
          <div style={{ display:'flex', flexDirection:'column', gap: 12 }}>
            <div style={{
              ...nutriStyles.card,
              display: 'flex', alignItems: 'center', gap: 10,
              padding: '10px 14px', borderRadius: 14,
            }}>
              <SearchIcon size={16}/>
              <input autoFocus value={q} onChange={e=>setQ(e.target.value)}
                placeholder="Search foods…"
                style={{
                  flex: 1, border: 0, background: 'transparent', outline: 'none',
                  font: 'inherit', fontSize: 14, color: 'var(--text)',
                }}/>
            </div>
            <div style={{ display:'flex', flexDirection:'column', gap: 8 }}>
              {filtered.map(f => (
                <FoodRow key={f.id} food={f} onAdd={()=>onLog({ ...f, meal })}/>
              ))}
            </div>
          </div>
        )}
        {tab === 'scan' && (
          <div style={{
            ...nutriStyles.card, padding: 24,
            display:'flex', flexDirection:'column', alignItems:'center', gap: 14,
            aspectRatio: '3 / 4',
            background: 'linear-gradient(180deg, var(--surface-2), var(--surface))',
          }}>
            <div style={{
              width: '100%', flex: 1, borderRadius: 14, position: 'relative',
              background: 'var(--surface-3)',
              border: '1px solid var(--border)',
              overflow: 'hidden',
            }}>
              {/* corner brackets */}
              {[[8,8,'tl'],[8,8,'tr'],[8,8,'bl'],[8,8,'br']].map(([w,h,p],i)=>{
                const pos = {
                  tl:{top:18,left:18}, tr:{top:18,right:18},
                  bl:{bottom:18,left:18}, br:{bottom:18,right:18},
                }[p];
                const bord = {
                  tl:'2px 0 0 2px', tr:'2px 2px 0 0',
                  bl:'0 0 0 2px', br:'0 2px 0 0',
                };
                const sides = {
                  tl:{borderTop:'2px solid var(--text)',borderLeft:'2px solid var(--text)'},
                  tr:{borderTop:'2px solid var(--text)',borderRight:'2px solid var(--text)'},
                  bl:{borderBottom:'2px solid var(--text)',borderLeft:'2px solid var(--text)'},
                  br:{borderBottom:'2px solid var(--text)',borderRight:'2px solid var(--text)'},
                }[p];
                return <div key={i} style={{ position:'absolute', width:28, height:28, ...pos, ...sides }}/>;
              })}
              <div style={{
                position: 'absolute', inset: 0, display: 'grid', placeItems: 'center',
                color: 'var(--muted)', fontSize: 13,
              }}>
                <div style={{ display:'flex', flexDirection:'column', alignItems:'center', gap:8 }}>
                  <CameraIcon size={28}/>
                  <div>Point camera at your meal</div>
                </div>
              </div>
            </div>
            <div style={{ display:'flex', gap: 10, width: '100%' }}>
              <PillBtn label="Scan food" primary icon={<CameraIcon size={14}/>}/>
              <PillBtn label="Barcode" icon={<BarcodeIcon size={14}/>}/>
            </div>
          </div>
        )}
        {tab === 'quick' && (
          <div style={{ ...nutriStyles.card, padding: 16, display:'flex', flexDirection:'column', gap: 12 }}>
            <Field label="Meal name" placeholder="e.g. Grilled chicken & rice"/>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
              <Field label="Calories" placeholder="0" suffix="kcal"/>
              <Field label="Protein" placeholder="0" suffix="g"/>
              <Field label="Carbs" placeholder="0" suffix="g"/>
              <Field label="Fat" placeholder="0" suffix="g"/>
            </div>
            <PillBtn label={"Log to " + NUTRI_MEAL_LABEL[meal]} primary fullWidth/>
          </div>
        )}
      </div>
    </div>
  );
}

function Field({ label, placeholder, suffix }) {
  return (
    <label style={{ display:'flex', flexDirection:'column', gap: 4 }}>
      <span style={{ fontSize: 11, color: 'var(--muted)', fontWeight: 600, letterSpacing: '0.04em', textTransform: 'uppercase' }}>{label}</span>
      <div style={{
        display: 'flex', alignItems: 'center', gap: 6,
        background: 'var(--surface-2)', border: '1px solid var(--border)',
        borderRadius: 10, padding: '8px 12px',
      }}>
        <input placeholder={placeholder} style={{
          flex: 1, minWidth: 0, border: 0, background: 'transparent', outline: 'none',
          font: 'inherit', fontSize: 14, color: 'var(--text)',
        }}/>
        {suffix && <span style={{ fontSize: 12, color: 'var(--muted)' }}>{suffix}</span>}
      </div>
    </label>
  );
}

function FoodRow({ food, onAdd }) {
  return (
    <div style={{
      ...nutriStyles.card,
      display: 'flex', alignItems: 'center', gap: 12, padding: 10,
    }}>
      <FoodThumb emoji={food.emoji} tint="#D6CFB4" size={42}/>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 14, fontWeight: 600 }}>{food.name}</div>
        <div style={{ fontSize: 12, color: 'var(--muted)' }}>
          {food.cal} cal · {food.qty} · P {food.p}g · C {food.c}g · F {food.f}g
        </div>
      </div>
      <button onClick={onAdd} aria-label="Add"
        style={{
          width: 32, height: 32, borderRadius: '50%',
          background: 'var(--accent)', color: 'var(--on-accent)',
          border: 0, display: 'grid', placeItems: 'center', cursor: 'pointer',
        }}>
        <PlusIcon size={16}/>
      </button>
    </div>
  );
}

function PillBtn({ label, primary, fullWidth, icon, onClick }) {
  return (
    <button onClick={onClick} style={{
      flex: fullWidth ? 1 : undefined,
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 6,
      padding: '12px 22px', borderRadius: 999,
      background: primary ? 'var(--accent)' : 'var(--surface)',
      color: primary ? 'var(--on-accent)' : 'var(--text)',
      border: primary ? '1px solid var(--accent)' : '1px solid var(--border-2)',
      fontSize: 13.5, fontWeight: 600, cursor: 'pointer', font: 'inherit',
      boxShadow: primary ? '0 8px 18px -10px rgba(31,61,46,0.6)' : 'none',
    }}>{icon}{label}</button>
  );
}

// ─────────────────────────────────────────────────────────────
// PROGRESS — charts, weight, breakdown table
// ─────────────────────────────────────────────────────────────
function ProgressScreen({ entries, weights, goals }) {
  // last 7 days calorie totals
  const today = new Date();
  const week = [];
  for (let i=6;i>=0;i--){
    const d = new Date(today); d.setDate(today.getDate()-i);
    const iso = isoOf(d);
    week.push({
      iso,
      label: ['S','M','T','W','T','F','S'][d.getDay()],
      cal: entries.filter(e=>e.date===iso).reduce((s,e)=>s+e.calories,0),
    });
  }
  const maxCal = Math.max(goals.calories, ...week.map(w=>w.cal));

  const weightList = Object.entries(weights).sort((a,b)=>a[0].localeCompare(b[0]));
  const wMin = Math.min(...weightList.map(w=>w[1]));
  const wMax = Math.max(...weightList.map(w=>w[1]));
  const wRange = wMax - wMin || 1;

  const avg = Math.round(week.reduce((s,w)=>s+w.cal,0) / week.length);
  const onTrack = week.filter(w => w.cal > 0 && Math.abs(w.cal - goals.calories) <= goals.calories*0.15).length;

  return (
    <div style={{ padding: '12px 18px 24px', display:'flex', flexDirection:'column', gap: 16 }}>
      <div style={{ paddingTop: 4 }}>
        <div style={{ fontSize: 22, fontWeight: 700, letterSpacing: '-0.02em' }}>Progress</div>
        <div style={{ fontSize: 12.5, color: 'var(--muted)', marginTop: 2, fontWeight: 500 }}>Last 7 days</div>
      </div>

      {/* Stat row */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
        <StatCard label="Avg calories / day" value={avg.toLocaleString()} delta={`Goal ${goals.calories}`}/>
        <StatCard label="Days on track" value={`${onTrack}/7`} delta={onTrack >= 5 ? '↑ Solid week' : 'Keep going'}/>
      </div>

      {/* Weekly calories chart */}
      <div style={{ ...nutriStyles.card, padding: 16 }}>
        <div style={{ display: 'flex', alignItems: 'baseline', justifyContent:'space-between', marginBottom: 14 }}>
          <div style={{ fontSize: 14, fontWeight: 600 }}>Calories this week</div>
          <div style={{ fontSize: 11, color: 'var(--muted)' }}>Goal {goals.calories}</div>
        </div>
        <div style={{ display:'flex', alignItems: 'flex-end', justifyContent:'space-between', gap: 8, height: 140, position: 'relative' }}>
          {/* goal line */}
          <div style={{
            position: 'absolute', left: 0, right: 0,
            bottom: `${(goals.calories/maxCal)*100}%`,
            borderTop: '1.5px dashed var(--border-2)',
          }}/>
          {week.map(w => {
            const h = (w.cal / maxCal) * 100;
            const over = w.cal > goals.calories;
            return (
              <div key={w.iso} style={{
                flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6,
                height: '100%',
              }}>
                <div style={{ flex: 1, width: '100%', display:'flex', alignItems:'flex-end' }}>
                  <div style={{
                    width: '100%',
                    height: `${h}%`,
                    background: over ? 'var(--c-carbs)' : 'var(--text)',
                    borderRadius: 6,
                    transition: 'height .35s ease',
                  }}/>
                </div>
                <div style={{ fontSize: 10, color: 'var(--muted)', fontWeight: 500 }}>{w.label}</div>
              </div>
            );
          })}
        </div>
      </div>

      {/* Weight trend */}
      <div style={{ ...nutriStyles.card, padding: 16 }}>
        <div style={{ display: 'flex', alignItems: 'baseline', justifyContent:'space-between', marginBottom: 6 }}>
          <div style={{ fontSize: 14, fontWeight: 600 }}>Weight</div>
          <div style={{ fontSize: 11, color: 'var(--muted)' }}>kg</div>
        </div>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 6, marginBottom: 12 }}>
          <div style={{ fontSize: 28, fontWeight: 600, letterSpacing: '-0.03em' }}>
            {weightList[weightList.length-1][1].toFixed(1)}
          </div>
          <div style={{ fontSize: 12, color: weightList[weightList.length-1][1] < weightList[0][1] ? 'var(--c-protein)' : 'var(--muted)', fontWeight: 600 }}>
            {(weightList[weightList.length-1][1] - weightList[0][1]).toFixed(1)} kg this week
          </div>
        </div>
        <WeightSpark points={weightList.map(([_,v])=>v)}/>
      </div>

      {/* Daily breakdown table */}
      <div style={{ ...nutriStyles.card, padding: 16 }}>
        <div style={{ fontSize: 14, fontWeight: 600, marginBottom: 12 }}>Daily breakdown</div>
        <div style={{ display:'flex', flexDirection:'column', gap: 1, background: 'var(--border)', borderRadius: 10, overflow:'hidden' }}>
          <div style={{
            display: 'grid', gridTemplateColumns: '1.1fr .8fr .8fr .8fr .8fr',
            background: 'var(--surface-2)', padding: '8px 12px',
            fontSize: 10.5, fontWeight: 600, color:'var(--muted)', letterSpacing: '0.04em', textTransform:'uppercase',
          }}>
            <div>Date</div><div style={{textAlign:'right'}}>Cal</div>
            <div style={{textAlign:'right'}}>P</div><div style={{textAlign:'right'}}>C</div><div style={{textAlign:'right'}}>F</div>
          </div>
          {week.slice().reverse().map(w => {
            const t = nutriDayTotals(entries, w.iso);
            const d = new Date(w.iso+'T00:00:00');
            return (
              <div key={w.iso} style={{
                display: 'grid', gridTemplateColumns: '1.1fr .8fr .8fr .8fr .8fr',
                background: 'var(--surface)', padding: '10px 12px',
                fontSize: 12.5,
              }}>
                <div style={{ color:'var(--text)', fontWeight: 500 }}>{d.toLocaleDateString(undefined,{weekday:'short', day:'numeric'})}</div>
                <div style={{textAlign:'right', fontWeight: 600 }}>{t.calories||'—'}</div>
                <div style={{textAlign:'right', color:'var(--c-protein)', fontWeight: 600 }}>{t.protein_g||'—'}</div>
                <div style={{textAlign:'right', color:'var(--c-carbs)', fontWeight: 600 }}>{t.carbs_g||'—'}</div>
                <div style={{textAlign:'right', color:'var(--c-fat)', fontWeight: 600 }}>{t.fat_g||'—'}</div>
              </div>
            );
          })}
        </div>
      </div>

      <div style={{ height: 60 }}/>
    </div>
  );
}

function StatCard({ label, value, delta }) {
  return (
    <div style={{ ...nutriStyles.card, padding: 14 }}>
      <div style={{ fontSize: 11, color:'var(--muted)', fontWeight: 600, letterSpacing:'0.04em', textTransform:'uppercase' }}>{label}</div>
      <div style={{ fontSize: 24, fontWeight: 600, letterSpacing:'-0.02em', marginTop: 4 }}>{value}</div>
      <div style={{ fontSize: 11, color:'var(--muted)', marginTop: 2 }}>{delta}</div>
    </div>
  );
}

function WeightSpark({ points }) {
  const w = 280, h = 70, pad = 6;
  const min = Math.min(...points), max = Math.max(...points);
  const range = max - min || 1;
  const step = (w - pad*2) / (points.length - 1);
  const pts = points.map((v, i) => {
    const x = pad + i * step;
    const y = h - pad - ((v - min)/range) * (h - pad*2);
    return [x, y];
  });
  const path = pts.map((p, i) => (i ? 'L' : 'M') + p[0] + ',' + p[1]).join(' ');
  const area = path + ` L ${pts[pts.length-1][0]} ${h-pad} L ${pts[0][0]} ${h-pad} Z`;
  return (
    <svg width="100%" height={h} viewBox={`0 0 ${w} ${h}`} preserveAspectRatio="none" style={{ display:'block' }}>
      <defs>
        <linearGradient id="wg" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor="var(--text)" stopOpacity="0.15"/>
          <stop offset="100%" stopColor="var(--text)" stopOpacity="0"/>
        </linearGradient>
      </defs>
      <path d={area} fill="url(#wg)"/>
      <path d={path} stroke="var(--text)" strokeWidth="2" fill="none" strokeLinecap="round" strokeLinejoin="round"/>
      {pts.map((p, i) => (
        <circle key={i} cx={p[0]} cy={p[1]} r="2.5" fill="var(--text)"/>
      ))}
    </svg>
  );
}

// ─────────────────────────────────────────────────────────────
// MEAL DETAIL — modal/sheet
// ─────────────────────────────────────────────────────────────
function MealDetailSheet({ entry, onClose, goals, onDelete }) {
  if (!entry) return null;
  const mealColor = {
    breakfast: '#F5D77A', lunch: '#F0A67A', dinner: '#A99CE0', snack: '#9ED1C0',
  }[entry.meal] || '#D0CDB8';

  return (
    <div style={{
      position: 'absolute', inset: 0, zIndex: 30,
      display: 'flex', flexDirection: 'column',
      background: 'var(--bg)',
      animation: 'sheetIn .25s cubic-bezier(.2,.7,.2,1)',
      paddingTop: 'var(--safe-top)',
    }}>
      {/* Header w/ image area */}
      <div style={{
        position: 'relative',
        height: 200,
        background: `linear-gradient(135deg, ${mealColor}66, ${mealColor}aa)`,
        display: 'grid', placeItems: 'center',
        fontSize: 80, lineHeight: 1,
        flexShrink: 0,
      }}>
        <button onClick={onClose} style={{
          position: 'absolute', top: 14, left: 14,
          width: 36, height: 36, borderRadius: '50%',
          border: '1px solid rgba(0,0,0,0.1)',
          background: 'rgba(255,255,255,0.9)',
          color: '#14140F', display: 'grid', placeItems: 'center', cursor: 'pointer',
        }}><XIcon size={18}/></button>
        <span style={{ filter: 'drop-shadow(0 6px 16px rgba(20,20,15,0.18))' }}>{entry.emoji}</span>
      </div>

      <div style={{ flex: 1, overflow: 'auto', padding: '18px 18px 100px' }}>
        <div>
          <div style={{ fontSize: 22, fontWeight: 700, letterSpacing: '-0.02em' }}>{entry.name || 'Untitled meal'}</div>
          <div style={{ fontSize: 13, color: 'var(--muted)', marginTop: 4 }}>
            {NUTRI_MEAL_LABEL[entry.meal] || entry.meal}{entry.time ? ` · ${entry.time}` : ''} · {entry.calories} cal
          </div>
        </div>

        {/* Macros big */}
        <div style={{
          ...nutriStyles.card, padding: 16, marginTop: 16,
          display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: 4,
        }}>
          <MacroBig label="Cal" val={entry.calories} unit="kcal"/>
          <MacroBig label="Protein" val={entry.protein_g} unit="g" color="var(--c-protein)"/>
          <MacroBig label="Carbs" val={entry.carbs_g} unit="g" color="var(--c-carbs)"/>
          <MacroBig label="Fat" val={entry.fat_g} unit="g" color="var(--c-fat)"/>
        </div>

        {/* Ingredients */}
        {entry.items && entry.items.length > 0 && (
          <>
            <div style={{ fontSize: 14, fontWeight: 600, marginTop: 18, marginBottom: 10 }}>
              Ingredients <span style={{ color:'var(--muted)', fontWeight:500 }}>({entry.items.length})</span>
            </div>
            <div style={{ display:'flex', flexDirection: 'column', gap: 1, background:'var(--border)', borderRadius:12, overflow:'hidden' }}>
              {entry.items.map((it,i) => (
                <div key={i} style={{
                  background: 'var(--surface)',
                  display: 'flex', alignItems: 'center', justifyContent:'space-between',
                  padding: '12px 14px',
                }}>
                  <div>
                    <div style={{ fontSize: 13.5, fontWeight: 500 }}>{it.name}</div>
                    {it.qty && <div style={{ fontSize: 11, color: 'var(--muted)' }}>{it.qty}</div>}
                  </div>
                  <div style={{ fontSize: 13, fontWeight: 600 }}>{it.cal} <span style={{ fontSize: 10, color:'var(--muted)', fontWeight: 500 }}>cal</span></div>
                </div>
              ))}
            </div>
          </>
        )}

        <div style={{ display: 'flex', gap: 10, marginTop: 18 }}>
          <button onClick={onDelete} style={{
            flex: 1, padding: '12px', borderRadius: 999,
            background: 'transparent', color: '#A33',
            border: '1px solid rgba(170,51,51,.35)',
            fontSize: 13.5, fontWeight: 600, cursor: 'pointer', font: 'inherit',
          }}>Delete</button>
          <button onClick={onClose} style={{
            flex: 1, padding: '12px', borderRadius: 999,
            background: 'var(--text)', color: 'var(--bg)',
            border: '1px solid var(--text)',
            fontSize: 13.5, fontWeight: 600, cursor: 'pointer', font: 'inherit',
          }}>Done</button>
        </div>
      </div>
    </div>
  );
}

function MacroBig({ label, val, unit, color }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 2 }}>
      <div style={{ fontSize: 20, fontWeight: 600, color: color || 'var(--text)', letterSpacing: '-0.02em' }}>{val}</div>
      <div style={{ fontSize: 10, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: '0.05em', fontWeight: 600 }}>{label}</div>
      <div style={{ fontSize: 9, color: 'var(--muted-2)' }}>{unit}</div>
    </div>
  );
}

Object.assign(window, {
  HomeScreen, CalendarScreen, FoodsScreen, AddScreen, ProgressScreen, MealDetailSheet,
  prettyDate, FoodCard, FoodRow, PillBtn, Field, QuickChip,
});
