// flows.jsx — interactive Quick Add, Meals, and Supplies surfaces

const QUICK_ACTIONS = [
  { id: 'water',      title: 'Log water',      sub: 'For any plant',       icon: window.I.drop,      target: 'plant', tint: 'pond' },
  { id: 'feed',       title: 'Log feed',       sub: 'Meals, hay, pellets', icon: window.I.bowl,      target: 'pet',   tint: 'honey' },
  { id: 'weight',     title: 'Log weight',     sub: 'For any pet',         icon: window.I.scale,     target: 'pet',   tint: 'terra' },
  { id: 'journal',    title: 'Photo journal',  sub: 'A photo, a note',     icon: window.I.camera,    target: 'all',   tint: 'terra' },
  { id: 'symptom',    title: 'Log symptom',    sub: 'Quick health note',   icon: window.I.heart,     target: 'pet',   tint: 'sage' },
  { id: 'medication', title: 'Add medication', sub: 'Meds and dose',       icon: window.I.heart,     target: 'pet',   tint: 'rust' },
  { id: 'routine',    title: 'Add routine',    sub: 'Recurring task',      icon: window.I.cal,       target: 'all',   tint: 'olive' },
  { id: 'doc',        title: 'Add record',     sub: 'Vet, insurance, ID',  icon: window.I.shop,      target: 'all',   tint: 'forest' },
];

function targetsForAction(folks, action) {
  if (!action || action.target === 'all') return folks || [];
  if (action.target === 'plant') return (folks || []).filter((f) => f.kind === 'plant');
  if (action.target === 'pet') return (folks || []).filter((f) => f.kind === 'pet');
  return [];
}

function QuickAddScreen({ folks, onBack, onLogWater, onLogWeight, onAddMed, onAddDoc, onAddJournal, onAddSymptom, onAddRoutine, onComplete }) {
  const [actionId, setActionId] = React.useState('hub');

  if (actionId !== 'hub') {
    const action = QUICK_ACTIONS.find((a) => a.id === actionId);
    return (
      <QuickActionForm
        action={action}
        folks={folks}
        onBack={() => setActionId('hub')}
        onLogWater={onLogWater}
        onLogWeight={onLogWeight}
        onAddMed={onAddMed}
        onAddDoc={onAddDoc}
        onAddJournal={onAddJournal}
        onAddSymptom={onAddSymptom}
        onAddRoutine={onAddRoutine}
        onComplete={onComplete || onBack}
      />
    );
  }

  return (
    <div className="screen fade-in">
      <window.MiniNav onBack={onBack} title="Quick add" />
      <div className="quick-screen">
        <div className="greet quick-head">
          <div className="date"><span className="dot"></span><span>Quick actions</span></div>
          <h1>What needs <i>tending</i>?</h1>
          <div className="sub">Log care, add records, or update a routine.</div>
        </div>

        <div className="quick-grid">
          {QUICK_ACTIONS.map((a) => {
            const Icon = a.icon;
            return (
              <button key={a.id} className="quick-card" data-tint={a.tint} onClick={() => setActionId(a.id)}>
                <div className="quick-ic"><Icon size={20} sw={1.8} /></div>
                <div className="quick-title">{a.title}</div>
                <div className="quick-sub">{a.sub}</div>
              </button>
            );
          })}
        </div>
      </div>
    </div>
  );
}

function QuickActionForm({ action, folks, onBack, onLogWater, onLogWeight, onAddMed, onAddDoc, onAddJournal, onAddSymptom, onAddRoutine, onComplete }) {
  const targets = React.useMemo(() => targetsForAction(folks, action), [folks, action]);
  const [folkId, setFolkId] = React.useState(targets[0]?.id || '');
  const [title, setTitle] = React.useState('');
  const [note, setNote] = React.useState('');
  const [amount, setAmount] = React.useState('');
  const [severity, setSeverity] = React.useState('mild');
  const [time, setTime] = React.useState('09:00');
  const [freq, setFreq] = React.useState('daily');
  const [photoUrl, setPhotoUrl] = React.useState('');
  const [saved, setSaved] = React.useState(false);
  const fileRef = React.useRef(null);

  React.useEffect(() => {
    if (!targets.some((f) => f.id === folkId)) setFolkId(targets[0]?.id || '');
  }, [targets, folkId]);

  const folk = targets.find((f) => f.id === folkId);
  const Icon = action?.icon || window.I.plus;
  const today = window.TOOLS_NOW.toISOString();

  const onPickPhoto = (e) => {
    const file = e.target.files && e.target.files[0];
    if (!file) return;
    const reader = new FileReader();
    reader.onload = (ev) => setPhotoUrl(ev.target.result);
    reader.readAsDataURL(file);
  };

  const valid = (() => {
    if (!folk) return false;
    if (action.id === 'water') return true;
    if (action.id === 'weight') return Number.isFinite(parseFloat(amount)) && parseFloat(amount) > 0;
    if (action.id === 'journal') return true;
    return !!title.trim();
  })();

  const save = () => {
    if (!valid || !folk) return;
    if (action.id === 'water') {
      onLogWater && onLogWater(folk.id, { date: today, note: note.trim() });
    } else if (action.id === 'feed') {
      onAddRoutine && onAddRoutine({
        id: `q-feed-${Date.now()}`,
        time: window.TOOLS_NOW.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit', hour12: false }),
        folkId: folk.id,
        verb: `Fed ${folk.name}`,
        detail: title.trim() || 'quick feed log',
        kind: 'feed',
        done: true,
        source: 'custom',
        recurrence: { type: 'once', date: 'today' },
      });
    } else if (action.id === 'weight') {
      onLogWeight && onLogWeight(folk.id, { date: today, kg: parseFloat(amount) });
    } else if (action.id === 'journal') {
      onAddJournal && onAddJournal(folk.id, {
        id: `j-${Date.now()}`,
        date: today,
        photoUrl: photoUrl || (window.speciesIconSrc && window.speciesIconSrc(folk)) || '',
        note: note.trim() || 'A quiet moment worth keeping.',
      });
    } else if (action.id === 'symptom') {
      onAddSymptom && onAddSymptom(folk.id, {
        id: `s-${Date.now()}`,
        date: today,
        symptom: title.trim(),
        severity,
        note: note.trim(),
      });
    } else if (action.id === 'medication') {
      onAddMed && onAddMed(folk.id, {
        name: title.trim(),
        dose: amount.trim(),
        freq,
        start: today,
        note: note.trim(),
      });
    } else if (action.id === 'doc') {
      onAddDoc && onAddDoc(folk.id, {
        title: title.trim(),
        type: 'vet',
        date: today,
        note: note.trim(),
        fileName: '',
        fileUrl: '',
      });
    } else if (action.id === 'routine') {
      onAddRoutine && onAddRoutine({
        id: `q-routine-${Date.now()}`,
        time,
        folkId: folk.id,
        verb: title.trim(),
        detail: note.trim() || 'custom reminder',
        kind: folk.kind === 'plant' ? 'water' : 'feed',
        done: false,
        source: 'custom',
        recurrence: { type: freq },
      });
    }
    setSaved(true);
    window.setTimeout(() => {
      if (onComplete) onComplete();
    }, 650);
  };

  return (
    <div className="screen fade-in">
      <window.MiniNav onBack={onBack} title={action.title} />
      <div className="quick-form">
        <div className="quick-form-hero" data-tint={action.tint}>
          <div className="quick-hero-ic"><Icon size={24} sw={1.8} /></div>
          <div>
            <div className="h-mono">Quick add</div>
            <h2>{action.title}</h2>
            <p>{action.sub}</p>
          </div>
        </div>

        {!targets.length ? (
          <div className="health-card quick-empty">
            <div className="health-empty-mark">+</div>
            <div className="health-empty-t">No matching folk yet.</div>
            <div className="health-empty-s">Add a {action.target === 'plant' ? 'plant' : 'pet'} first, then this action will be ready.</div>
          </div>
        ) : (
          <>
            <div className="quick-pick">
              {targets.map((f) => (
                <button key={f.id} className={folkId === f.id ? 'on' : ''} onClick={() => setFolkId(f.id)}>
                  <window.FolkAvatar folk={f} />
                  <span>{f.name}</span>
                </button>
              ))}
            </div>

            {action.id === 'journal' && (
              <div className="health-form quick-fields">
                <button className="health-file-btn jr-pick" onClick={() => fileRef.current?.click()}>
                  <window.I.camera size={18} sw={1.7} />
                  <span>{photoUrl ? 'Photo selected' : 'Pick photo or use demo card'}</span>
                </button>
                <input ref={fileRef} type="file" accept="image/*" style={{ display: 'none' }} onChange={onPickPhoto} />
                {photoUrl && <img className="quick-photo-preview" src={photoUrl} alt="" />}
                <input className="health-input" value={note} onChange={(e) => setNote(e.target.value)}
                       placeholder="What do you want to remember?" />
              </div>
            )}

            {action.id !== 'water' && action.id !== 'weight' && action.id !== 'journal' && (
              <div className="health-form quick-fields">
                <input className="health-input" autoFocus value={title} onChange={(e) => setTitle(e.target.value)}
                       placeholder={
                         action.id === 'feed' ? 'What did they eat?' :
                         action.id === 'symptom' ? "What's off?" :
                         action.id === 'medication' ? 'Medication name' :
                         action.id === 'doc' ? 'Record title' :
                         'Reminder title'
                       } />
                {action.id === 'routine' && (
                  <div className="health-form-row split">
                    <input className="health-input" type="time" value={time} onChange={(e) => setTime(e.target.value)} />
                    <select className="health-input" value={freq} onChange={(e) => setFreq(e.target.value)}>
                      <option value="daily">Daily</option>
                      <option value="weekly">Weekly</option>
                      <option value="monthly">Monthly</option>
                    </select>
                  </div>
                )}
                {action.id === 'symptom' && (
                  <div className="doc-type-tabs">
                    {['mild', 'moderate', 'urgent'].map((s) => (
                      <button key={s} type="button" className={severity === s ? 'on' : ''} onClick={() => setSeverity(s)}>{s}</button>
                    ))}
                  </div>
                )}
                {action.id === 'medication' && (
                  <div className="health-form-row split">
                    <input className="health-input" value={amount} onChange={(e) => setAmount(e.target.value)} placeholder="Dose" />
                    <select className="health-input" value={freq} onChange={(e) => setFreq(e.target.value)}>
                      <option value="daily">Once daily</option>
                      <option value="twice daily">Twice daily</option>
                      <option value="weekly">Weekly</option>
                      <option value="as needed">As needed</option>
                    </select>
                  </div>
                )}
                <input className="health-input" value={note} onChange={(e) => setNote(e.target.value)}
                       placeholder={action.id === 'routine' ? 'Details (optional)' : 'Notes (optional)'} />
              </div>
            )}

            {action.id === 'water' && (
              <div className="health-form quick-fields">
                <input className="health-input" value={note} onChange={(e) => setNote(e.target.value)}
                       placeholder={`Notes for ${folk?.name || 'this plant'} (optional)`} />
              </div>
            )}

            {action.id === 'weight' && (
              <div className="health-form quick-fields">
                <div className="health-form-row split">
                  <input className="health-input" autoFocus type="number" step="0.01" min="0"
                         value={amount} onChange={(e) => setAmount(e.target.value)} placeholder="Weight" />
                  <div className="quick-unit">kg</div>
                </div>
              </div>
            )}

            <button className="cta quick-save" onClick={save} disabled={!valid} style={{ opacity: valid ? 1 : 0.45 }}>
              {saved ? 'Saved to Tendlet' : `Save for ${folk?.name || 'them'}`}
            </button>
          </>
        )}
      </div>
    </div>
  );
}

const DEMO_WEEK = [
  { k: 'mon', d: 'M', date: 11 },
  { k: 'tue', d: 'T', date: 12 },
  { k: 'wed', d: 'W', date: 13 },
  { k: 'thu', d: 'T', date: 14 },
  { k: 'fri', d: 'F', date: 15 },
  { k: 'sat', d: 'S', date: 16 },
  { k: 'sun', d: 'S', date: 17 },
];
const DEMO_WEEK_NAMES = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];

function mealsForFolk(folk, dayIndex) {
  const s = (folk.species || '').toLowerCase();
  if (s.includes('guinea')) {
    return [
      { id: 'hay', label: 'Fresh hay', amount: 'unlimited', note: 'Replace damp hay' },
      { id: 'greens', label: dayIndex % 2 ? 'Romaine + cucumber' : 'Romaine + bell pepper', amount: '55 g', note: 'Vitamin C friendly' },
      { id: 'pellets', label: 'Cavy pellets', amount: '18 g', note: 'Plain, fortified' },
    ];
  }
  if (s.includes('cat')) {
    return [
      { id: 'breakfast', label: 'Wet breakfast', amount: '40 g', note: 'Add warm water' },
      { id: 'dinner', label: 'Wet dinner', amount: '45 g', note: 'Salmon rotation' },
    ];
  }
  if (s.includes('dog')) {
    return [
      { id: 'breakfast', label: 'Breakfast', amount: '120 g', note: 'Kibble + splash water' },
      { id: 'dinner', label: 'Dinner', amount: '140 g', note: 'After evening walk' },
      { id: 'chew', label: 'Dental chew', amount: '1', note: 'Supervised' },
    ];
  }
  if (s.includes('fish') || s.includes('betta')) {
    return [
      { id: 'pellets', label: 'Pellets', amount: '3', note: 'Remove uneaten food' },
    ];
  }
  return [
    { id: 'morning', label: 'Morning feed', amount: 'per plan', note: 'Fresh water too' },
    { id: 'evening', label: 'Evening feed', amount: 'per plan', note: 'Watch appetite' },
  ];
}

function groceryRowsFor(folks, shopItems) {
  const pets = (folks || []).filter((f) => f.kind === 'pet');
  const base = [];
  pets.forEach((f) => {
    mealsForFolk(f, 3).forEach((m) => {
      base.push({
        id: `${f.id}-${m.id}`,
        name: m.label,
        amount: m.amount,
        note: f.name,
        folkId: f.id,
        source: 'meal',
      });
    });
  });
  const supplies = (shopItems || []).filter((it) => it.low).map((it) => ({
    id: `shop-${it.id}`,
    name: it.item || it.name,
    amount: 'running low',
    note: it.vendor || 'supply list',
    folkId: it.for || it.folkId,
    source: 'shop',
  }));
  return [...base, ...supplies];
}

function MealsScreen({ folks, mealWeekStarted, onStartMealWeek, onResetMealWeek, fedMeals, onToggleFed, shopItems, onToggleShopLow, onOpenShop, openDetail }) {
  const [sub, setSub] = React.useState('week');
  const [day, setDay] = React.useState(3);
  const [checkedGroceries, setCheckedGroceries] = React.useState({});
  const pets = (folks || []).filter((f) => f.kind === 'pet');
  const rows = groceryRowsFor(folks, shopItems);
  const checkedGroceryCount = rows.filter((r) => checkedGroceries[r.id]).length;
  const fedCount = pets.reduce((n, f) => n + mealsForFolk(f, day).filter((m) => fedMeals?.[`${f.id}-${day}-${m.id}`]).length, 0);
  const totalMeals = pets.reduce((n, f) => n + mealsForFolk(f, day).length, 0);
  const dayName = DEMO_WEEK_NAMES[day] || 'Today';
  const mealSummary = pets.length ? `${pets.length} animal plans` : 'No animal plans yet';
  const grocerySummary = `${checkedGroceryCount}/${rows.length} bought`;
  const markFed = (key) => {
    if (!mealWeekStarted) onStartMealWeek && onStartMealWeek();
    onToggleFed && onToggleFed(key);
  };
  const dayCounts = DEMO_WEEK.map((_, i) => {
    const total = pets.reduce((n, f) => n + mealsForFolk(f, i).length, 0);
    const done = pets.reduce((n, f) => n + mealsForFolk(f, i).filter((m) => fedMeals?.[`${f.id}-${i}-${m.id}`]).length, 0);
    return { total, done };
  });

  return (
    <div className="screen meals-screen fade-in">
      <div style={{ height: 54 }} />
      <div className="meals-top">
        <div className="meals-title-row">
          <div>
            <div className="h-mono meals-kicker">Meals</div>
            <h1>Meals</h1>
          </div>
          <span>{sub === 'week' ? mealSummary : grocerySummary}</span>
        </div>
        <div className="meal-tabs">
          <button type="button" className={sub === 'week' ? 'on' : ''} onClick={() => setSub('week')}>
            <window.I.forkKnife size={15} /> Feedings
          </button>
          <button type="button" className={sub === 'grocery' ? 'on' : ''} onClick={() => setSub('grocery')}>
            <window.I.shop size={15} /> Groceries
          </button>
        </div>
        {sub === 'week' && (
          <div className="meals-context">
            <h1>Feeding rhythm</h1>
            <p>{pets.length ? `${pets.length} animal meal plans, one calm checklist.` : 'Add an animal to build a meal plan.'}</p>
          </div>
        )}
      </div>

      {sub === 'week' && (
        <div className="meals-body">
          {!pets.length ? (
            <div className="health-card quick-empty">
              <div className="health-empty-mark">+</div>
              <div className="health-empty-t">No pets yet.</div>
              <div className="health-empty-s">Add an animal to see species-aware meal plans.</div>
            </div>
          ) : (
            <>
              <div className="meal-dashboard">
                <div className="meal-dashboard-icon">
                  {mealWeekStarted ? <window.I.check size={15} sw={2.2} /> : <window.I.cal size={15} sw={1.9} />}
                </div>
                <div className="meal-dashboard-copy">
                  <div className="h-mono">Feedings · {dayName}</div>
                  <h2>{mealWeekStarted ? 'Tracking today' : 'Cycle preview'}</h2>
                  <p>{fedCount}/{totalMeals} marked for Thursday, May 14.</p>
                </div>
                <button type="button" onClick={mealWeekStarted ? onResetMealWeek : onStartMealWeek}>
                  {mealWeekStarted ? 'Reset' : 'Start week'}
                </button>
              </div>
              <div className="week-strip meal-week">
                {DEMO_WEEK.map((d, i) => {
                  const counts = dayCounts[i];
                  return (
                  <button key={d.k} className={'day' + (i === day ? ' today' : '')} onClick={() => setDay(i)}>
                    <div className="d">{d.d}</div>
                    <div className="n">{d.date}</div>
                    <div className="ct">{counts.done}/{counts.total}</div>
                  </button>
                  );
                })}
              </div>
              {pets.map((f) => (
                <MealCard key={f.id} folk={f} day={day} meals={mealsForFolk(f, day)}
                          fedMeals={fedMeals} onToggleFed={markFed} openDetail={openDetail} />
              ))}
            </>
          )}
        </div>
      )}

      {sub === 'grocery' && (
        <div className="meals-body">
          <div className="grocery-hero">
            <div className="grocery-hero-icon"><window.I.shop size={16} sw={1.8} /></div>
            <div>
              <div className="h-mono">Seven-day list</div>
              <h2>Groceries</h2>
              <p>{checkedGroceryCount}/{rows.length} checked · meal-plan ingredients and low supplies.</p>
            </div>
            <button type="button" onClick={onOpenShop}>Supplies</button>
          </div>
          <div className="grocery-list">
            {rows.map((r) => {
              const done = !!checkedGroceries[r.id];
              const folk = (folks || []).find((f) => f.id === r.folkId);
              return (
                <div key={r.id} className={'grocery-row' + (done ? ' done' : '')}>
                  <button className="check"
                          aria-label={done ? `Put ${r.name} back on the grocery list` : `Check off ${r.name}`}
                          onClick={() => setCheckedGroceries((p) => ({ ...p, [r.id]: !p[r.id] }))}>
                    <window.I.check size={14} sw={2.4} />
                  </button>
                  <div className="grocery-copy">
                    <b>{r.name}</b>
                    <span>{r.amount} · {r.note}</span>
                  </div>
                  <div className="grocery-meta">
                    {folk && <button className="grocery-avatar" onClick={() => openDetail(folk.id)}><window.FolkAvatar folk={folk} /></button>}
                    <span className={'grocery-source ' + r.source}>{r.source === 'shop' ? 'Supply' : 'Meal'}</span>
                    {r.source === 'shop' && <button className="stock-btn" onClick={() => onToggleShopLow && onToggleShopLow(r.id.replace('shop-', ''))}>Stocked</button>}
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      )}
    </div>
  );
}

function MealCard({ folk, day, meals, fedMeals, onToggleFed, openDetail }) {
  const doneCount = meals.filter((m) => fedMeals?.[`${folk.id}-${day}-${m.id}`]).length;
  return (
    <div className="meal-card">
      <button className="meal-person" onClick={() => openDetail(folk.id)}>
        <window.FolkAvatar folk={folk} />
        <div>
          <b>{folk.name}</b>
          <span>{folk.species}</span>
        </div>
        <em>{doneCount}/{meals.length}</em>
      </button>
      <div className="meal-rows">
        {meals.map((m) => {
          const key = `${folk.id}-${day}-${m.id}`;
          const done = !!fedMeals?.[key];
          return (
            <button key={m.id} className={'meal-row' + (done ? ' done' : '')} onClick={() => onToggleFed(key)}>
              <div className="meal-check"><window.I.check size={13} sw={2.4} /></div>
              <div className="meal-copy">
                <b>{m.label}</b>
                <span>{m.amount} · {m.note}</span>
              </div>
              <div className="meal-state">{done ? 'Fed' : 'Tap'}</div>
            </button>
          );
        })}
      </div>
    </div>
  );
}

function ShopScreen({ folks, items, onBack, onToggleLow, onAddItem, onUpdateItem, onRemoveItem, openDetail }) {
  const [adding, setAdding] = React.useState(false);
  const [editing, setEditing] = React.useState(null);
  const [name, setName] = React.useState('');
  const [note, setNote] = React.useState('');
  const [folkId, setFolkId] = React.useState('');
  const low = (items || []).filter((it) => it.low);
  const stocked = (items || []).filter((it) => !it.low);
  const displayName = (it) => it.item || it.name;

  const save = () => {
    if (!name.trim()) return;
    onAddItem && onAddItem({ item: name.trim(), name: name.trim(), vendor: note.trim(), low: true, for: folkId || null });
    setName(''); setNote(''); setFolkId(''); setAdding(false);
  };
  const beginEdit = (it) => {
    setEditing(it);
    setAdding(false);
    setName(displayName(it));
    setNote(it.vendor || '');
    setFolkId(it.for || it.folkId || '');
  };
  const saveEdit = () => {
    if (!editing || !name.trim()) return;
    onUpdateItem && onUpdateItem(editing.id, {
      item: name.trim(),
      name: name.trim(),
      vendor: note.trim(),
      for: folkId || null,
      folkId: folkId || null,
    });
    setEditing(null); setName(''); setNote(''); setFolkId('');
  };
  const cancelEdit = () => {
    setEditing(null); setAdding(false); setName(''); setNote(''); setFolkId('');
  };

  const section = (title, list) => (
    <div className="shop-section">
      <div className="h-mono shop-kicker">{title}</div>
      <div className="shop-list">
        {list.map((it) => {
          const fid = it.for || it.folkId;
          const folk = (folks || []).find((f) => f.id === fid);
          return (
            <div key={it.id} className={'shop-row' + (!it.low ? ' stocked' : '')}>
              <button className="check"
                      aria-label={it.low ? `Mark ${displayName(it)} stocked` : `Mark ${displayName(it)} running low`}
                      onClick={() => onToggleLow && onToggleLow(it.id)}>
                <window.I.check size={14} sw={2.4} />
              </button>
              <div className="shop-copy">
                <b>{displayName(it)}</b>
                <span>{it.low ? 'running low' : 'stocked'}{it.vendor ? ` · ${it.vendor}` : ''}</span>
              </div>
              {folk && <button className="grocery-avatar" onClick={() => openDetail(folk.id)}><window.FolkAvatar folk={folk} /></button>}
              <button className="shop-edit-btn" onClick={() => beginEdit(it)} aria-label={`Edit ${displayName(it)}`}>
                <window.I.more size={16} sw={1.8} />
              </button>
              <button className="r-del" onClick={() => onRemoveItem && onRemoveItem(it.id)} aria-label="Remove">
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor"
                     strokeWidth="2" strokeLinecap="round"><path d="M6 6l12 12M18 6L6 18"/></svg>
              </button>
            </div>
          );
        })}
      </div>
    </div>
  );

  return (
    <div className="screen shop-screen fade-in">
      <window.MiniNav onBack={onBack} title="Supplies" />
      <div className="shop-head">
        <h1>What supplies are <i>running low</i>?</h1>
        <div className="sub">Tap a row to mark stocked, or attach it to a specific folk.</div>
      </div>
      {low.length > 0 && section('Running low', low)}
      {stocked.length > 0 && section('Stocked', stocked)}
      {!items?.length && (
        <div className="health-card quick-empty">
          <div className="health-empty-mark">◧</div>
          <div className="health-empty-t">No supplies yet.</div>
          <div className="health-empty-s">Add litter, treats, soil, food, or other care supplies.</div>
        </div>
      )}
      {adding || editing ? (
        <div className="health-card shop-add">
          <input className="health-input" autoFocus value={name} onChange={(e) => setName(e.target.value)} placeholder="Supply name" />
          <input className="health-input" value={note} onChange={(e) => setNote(e.target.value)} placeholder="Brand, size, or note" />
          <select className="health-input" value={folkId} onChange={(e) => setFolkId(e.target.value)}>
            <option value="">Household supply</option>
            {(folks || []).map((f) => <option key={f.id} value={f.id}>{f.name}</option>)}
          </select>
          <div className="r-add-actions">
            <button className="r-cancel" onClick={cancelEdit}>Cancel</button>
            <button className="r-save" onClick={editing ? saveEdit : save} disabled={!name.trim()} style={{ opacity: name.trim() ? 1 : 0.45 }}>
              {editing ? 'Save changes' : 'Add supply'}
            </button>
          </div>
        </div>
      ) : (
        <button className="r-add shop-add-btn" onClick={() => setAdding(true)}>
          <span className="r-plus">+</span>
          <span>Add a supply</span>
        </button>
      )}
    </div>
  );
}

Object.assign(window, { QuickAddScreen, MealsScreen, ShopScreen, mealsForFolk });
