// Log Food — single OR multiple item lookup with Claude
const { useState, useEffect, useContext } = React;

function LogFoodPage() {
  const { addEntries, toast, prefs } = useContext(AppCtx);

  const [text, setText] = useState('');
  const [date, setDate] = useState(todayISO());
  const [meal, setMeal] = useState(defaultMealForHour(todayHour()));
  const [waterOz, setWaterOz] = useState('');
  const [loading, setLoading] = useState(false);
  const [progress, setProgress] = useState(null);
  // items: parsed list waiting for review/add. null = not yet looked up.
  const [items, setItems] = useState(null);

  async function handleLookup() {
    if (meal === 'Water') {
      const oz = parseFloat(waterOz);
      if (!oz || oz <= 0) {
        toast('Enter water amount (oz)', 'error');
        return;
      }
      setItems([{
        _id: 'w_' + Date.now(), _selected: true,
        name: `Water (${oz} oz)`,
        servingDescription: `${oz} oz`,
        calories: 0, fat: 0, satFat: 0, transFat: 0, cholesterol: 0,
        sodium: 0, carbs: 0, fiber: 0, sugar: 0, protein: 0,
        vitA: 0, vitB6: 0, vitB12: 0, vitC: 0, vitD: 0,
        calcium: 0, iron: 0, potassium: 0, caffeine: 0, water: oz,
        other: ''
      }]);
      return;
    }
    if (!text.trim()) {
      toast('Type a food or meal first', 'error');
      return;
    }
    setLoading(true);
    setProgress(null);
    setItems(null);
    try {
      const result = await claudeLookupSingle(text, (p) => setProgress(p));
      const list = (result.items || []).map(it => ({
        ...it, _id: Math.random().toString(36).slice(2), _selected: true
      }));
      if (!list.length) {
        toast('No items parsed — try rephrasing', 'error');
        return;
      }
      setItems(list);
    } catch (e) {
      console.error('Lookup failed', e);
      toast('Lookup failed: ' + (e.message || 'try again'), 'error');
    } finally {
      setLoading(false);
      setProgress(null);
    }
  }

  function toggleItem(id) {
    setItems(items => items.map(it => it._id === id ? { ...it, _selected: !it._selected } : it));
  }
  function updateItem(id, patch) {
    setItems(items => items.map(it => it._id === id ? { ...it, ...patch } : it));
  }
  function removeItem(id) {
    setItems(items => items.filter(it => it._id !== id));
  }

  function handleAddAll() {
    const selected = items.filter(it => it._selected);
    if (!selected.length) { toast('Select at least one item', 'error'); return; }
    // Apply form-level date + meal to all (Log Food behavior)
    const entries = selected.map(({ _id, _selected, ...rest }) => ({
      ...rest, date, meal, notes: rest.notes || ''
    }));
    addEntries(entries);
    toast(`Logged ${entries.length} item${entries.length === 1 ? '' : 's'}`);
    setItems(null);
    setText('');
    setWaterOz('');
  }

  function handleCancel() {
    setItems(null);
  }

  const isWater = meal === 'Water';
  const selectedCount = items ? items.filter(it => it._selected).length : 0;

  return (
    <div>
      <div className="row-between mb-24" style={{ flexWrap: 'wrap' }}>
        <div>
          <div className="eyebrow">Log Food</div>
          <h1 className="display mt-8">What did you eat?</h1>
          <p className="muted" style={{ maxWidth: 560 }}>
            Describe a single item or a whole meal in plain English. Claude looks up the nutrition.
          </p>
        </div>
      </div>

      <div className="grid grid-2 grid-cols-mobile-1" style={{ alignItems: 'start' }}>
        <div className="card">
          <div className="grid" style={{ gridTemplateColumns: '1fr 1fr', gap: 14 }}>
            <div className="field">
              <label>Date</label>
              <input className="input" type="date" value={date}
                     onChange={e => setDate(e.target.value)} />
            </div>
            <div className="field">
              <label>Meal</label>
              <select className="select" value={meal} onChange={e => setMeal(e.target.value)}>
                {MEALS.map(m => <option key={m} value={m}>{m}</option>)}
              </select>
            </div>
          </div>

          <div className="field mt-16">
            <label>{isWater ? 'Water amount' : 'Food / meal'}</label>
            {isWater ? (
              <div style={{ display: 'flex', gap: 10, alignItems: 'center', flexWrap: 'wrap' }}>
                <input className="input" type="number" inputMode="decimal" placeholder="16"
                       value={waterOz} onChange={e => setWaterOz(e.target.value)}
                       style={{ flex: '1 1 120px', minWidth: 100 }} />
                <span className="chip">oz</span>
                <div className="row" style={{ gap: 6, flexWrap: 'wrap' }}>
                  {[8, 12, 16, 24, 32].map(q => (
                    <button key={q} className="btn btn-sm btn-ghost"
                            onClick={() => setWaterOz(String((+waterOz || 0) + q))}>
                      +{q}
                    </button>
                  ))}
                </div>
              </div>
            ) : (
              <textarea className="textarea"
                placeholder={`Single item: "2 scrambled eggs with cheese"

Or list out everything you ate at this meal:
• Chipotle chicken bowl with brown rice and black beans
• Side of guac
• Large coke`}
                value={text} onChange={e => setText(e.target.value)} />
            )}
          </div>

          <div className="row-between mt-16" style={{ flexWrap: 'wrap', gap: 10 }}>
            <div className="muted" style={{ fontSize: 12 }}>
              <Icon name="sparkle" size={12} /> Powered by Claude
            </div>
            <button className="btn btn-primary btn-lg" onClick={handleLookup} disabled={loading}>
              {loading ? <><span className="spinner" /> Looking up…</> : <><Icon name="search" /> Look up</>}
            </button>
          </div>
        </div>

        <div>
          {loading ? (
            <LoadingPreview progress={progress} />
          ) : items && items.length > 0 ? (
            <LogReviewPanel
              items={items}
              meal={meal}
              date={date}
              selectedCount={selectedCount}
              onToggle={toggleItem}
              onUpdate={updateItem}
              onRemove={removeItem}
              onAddAll={handleAddAll}
              onCancel={handleCancel}
              showMicros={prefs.showMicros}
            />
          ) : (
            <EmptyPreview isWater={isWater} />
          )}
        </div>
      </div>
    </div>
  );
}

function LoadingPreview({ progress }) {
  const msg = progress
    ? (progress.stage === 'looking up'
        ? `Looking up nutrition · ${progress.done} of ${progress.total}`
        : `Parsing items · found ${progress.total}`)
    : 'Claude is analyzing your entry…';
  const pct = progress && progress.total ? Math.round((progress.done / progress.total) * 100) : 0;
  return (
    <div className="card" style={{ minHeight: 360 }}>
      <div className="row" style={{ gap: 12, alignItems: 'center', marginBottom: 16 }}>
        <span className="spinner" style={{ color: 'var(--accent)' }} />
        <span className="muted">{msg}</span>
      </div>
      {progress && progress.stage === 'looking up' && (
        <div className="progress thick mb-16">
          <span style={{ width: pct + '%' }} />
        </div>
      )}
      {[80, 65, 95, 50].map((w, i) => (
        <div key={i} style={{ background: 'var(--bg-elev)', height: i === 0 ? 22 : 14, borderRadius: 8, width: w + '%', marginBottom: 10 }} />
      ))}
      <hr className="divider" />
      <div className="grid grid-4">
        {[0,1,2,3].map(i => <div key={i} style={{ background: 'var(--bg-elev)', height: 64, borderRadius: 10 }} />)}
      </div>
    </div>
  );
}

function EmptyPreview({ isWater }) {
  return (
    <div className="card" style={{ minHeight: 360, display: 'grid', placeItems: 'center', textAlign: 'center' }}>
      <div style={{ maxWidth: 280 }}>
        <div style={{ width: 56, height: 56, borderRadius: 16, background: 'var(--accent-soft)', display: 'grid', placeItems: 'center', color: 'var(--accent)', margin: '0 auto 18px' }}>
          <Icon name={isWater ? 'log' : 'sparkle'} size={26} />
        </div>
        <div className="display" style={{ fontSize: 22, marginBottom: 8 }}>
          {isWater ? 'Hydrate up' : 'Preview will appear here'}
        </div>
        <p className="muted" style={{ fontSize: 13 }}>
          {isWater
            ? 'Tap a quick-add chip or type a custom amount, then look it up.'
            : 'Type one item or a whole meal — calories, macros, and micros are returned as a structured preview you can add to your log.'}
        </p>
      </div>
    </div>
  );
}

/* ---------- Multi-item review panel ---------- */
function LogReviewPanel({ items, meal, date, selectedCount, onToggle, onUpdate, onRemove, onAddAll, onCancel, showMicros }) {
  const isSingle = items.length === 1;

  // Totals across selected items
  const totals = items.filter(i => i._selected).reduce((acc, it) => {
    SUMMABLE.forEach(k => { acc[k] = (acc[k] || 0) + (Number(it[k]) || 0); });
    return acc;
  }, {});

  return (
    <div className="preview">
      <div style={{ marginBottom: 4 }}>
        <span className="meal-pill" data-meal={meal} style={{ marginRight: 6 }}><span className="dot" /> {meal}</span>
        <span className="chip">{relativeDayLabel(date)}</span>
      </div>
      <h3 className="display mt-8">{isSingle ? items[0].name : `${items.length} item${items.length === 1 ? '' : 's'} parsed`}</h3>
      {isSingle && items[0].servingDescription && (
        <div className="chip mt-8">{items[0].servingDescription}</div>
      )}

      <div className="macros-strip">
        <div className="macro" data-k="calories">
          <div className="v">{fmtNum(totals.calories || 0)}</div>
          <div className="l">cal</div>
        </div>
        <div className="macro" data-k="protein">
          <div className="v">{fmtNum(totals.protein || 0, 1)}<small style={{fontSize:11,marginLeft:2,color:'var(--text-dim)'}}>g</small></div>
          <div className="l">protein</div>
        </div>
        <div className="macro" data-k="carbs">
          <div className="v">{fmtNum(totals.carbs || 0, 1)}<small style={{fontSize:11,marginLeft:2,color:'var(--text-dim)'}}>g</small></div>
          <div className="l">carbs</div>
        </div>
        <div className="macro" data-k="fat">
          <div className="v">{fmtNum(totals.fat || 0, 1)}<small style={{fontSize:11,marginLeft:2,color:'var(--text-dim)'}}>g</small></div>
          <div className="l">fat</div>
        </div>
      </div>

      {/* Per-item rows when multiple */}
      {!isSingle && (
        <div className="grid" style={{ gap: 8, marginTop: 8 }}>
          {items.map(it => (
            <div key={it._id} className="card-tight" style={{
              border: '1px solid var(--line)', borderRadius: 12, padding: 12,
              background: 'var(--bg-elev)', opacity: it._selected ? 1 : 0.5,
              display: 'flex', alignItems: 'center', gap: 12
            }}>
              <button onClick={() => onToggle(it._id)} title="Include in log"
                      style={{
                        width: 20, height: 20, borderRadius: 5,
                        border: '1.5px solid ' + (it._selected ? 'var(--accent)' : 'var(--line)'),
                        background: it._selected ? 'var(--accent)' : 'transparent',
                        color: '#fff', cursor: 'pointer', display: 'grid', placeItems: 'center', padding: 0,
                        flexShrink: 0
                      }}>
                {it._selected && <svg width="11" height="11" viewBox="0 0 12 12"><path d="M2 6.5l2.5 2.5L10 3" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/></svg>}
              </button>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontWeight: 500, fontSize: 14, lineHeight: 1.2 }}>{it.name}</div>
                {it.servingDescription && <div className="muted" style={{ fontSize: 11 }}>{it.servingDescription}</div>}
              </div>
              <div className="num" style={{ fontSize: 13, color: 'var(--accent)' }}>{fmtNum(it.calories || 0)} cal</div>
              <button className="lr-del" onClick={() => onRemove(it._id)} aria-label="Remove"><Icon name="trash" size={14} /></button>
            </div>
          ))}
        </div>
      )}

      {/* Single-item: show full breakdown */}
      {isSingle && (
        <>
          <hr className="divider" />
          <div className="grid grid-2" style={{ fontSize: 13 }}>
            <KV label="Fiber" v={items[0].fiber} u="g" digits={1} />
            <KV label="Sugar" v={items[0].sugar} u="g" digits={1} />
            <KV label="Sodium" v={items[0].sodium} u="mg" />
            <KV label="Cholesterol" v={items[0].cholesterol} u="mg" />
            <KV label="Sat. Fat" v={items[0].satFat} u="g" digits={1} />
            <KV label="Caffeine" v={items[0].caffeine} u="mg" />
            <KV label="Water" v={items[0].water} u="oz" />
            <KV label="Potassium" v={items[0].potassium} u="mg" />
          </div>
          {showMicros && (
            <>
              <hr className="divider" />
              <div className="label mb-8">Micronutrients</div>
              <div className="micro-strip">
                {[
                  ['Vit A', items[0].vitA, 'mcg'],
                  ['Vit B6', items[0].vitB6, 'mg'],
                  ['Vit B12', items[0].vitB12, 'mcg'],
                  ['Vit C', items[0].vitC, 'mg'],
                  ['Vit D', items[0].vitD, 'mcg'],
                  ['Calcium', items[0].calcium, 'mg'],
                  ['Iron', items[0].iron, 'mg']
                ].filter(([_,v]) => Number(v) > 0).map(([n,v,u]) => (
                  <span key={n} className="chip">{n} <strong style={{ color: 'var(--text)', marginLeft: 4 }}>{fmtNum(v, v < 1 ? 2 : 0)}{u}</strong></span>
                ))}
                {items[0].other ? <span className="chip" style={{ background: 'transparent' }}>{items[0].other}</span> : null}
              </div>
            </>
          )}
        </>
      )}

      <div className="row-between mt-24" style={{ gap: 10, flexWrap: 'wrap' }}>
        <button className="btn btn-ghost" onClick={onCancel}>Discard</button>
        <button className="btn btn-primary" onClick={onAddAll} disabled={!selectedCount}>
          <Icon name="plus" /> Add {isSingle ? 'to Log' : `${selectedCount} to log`}
        </button>
      </div>
    </div>
  );
}

function KV({ label, v, u, digits = 0 }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'space-between', padding: '6px 0', borderBottom: '1px dashed var(--line-soft)' }}>
      <span className="muted" style={{ fontSize: 12 }}>{label}</span>
      <span className="num" style={{ fontSize: 13 }}>{fmtNum(v || 0, digits)} <span className="dim">{u}</span></span>
    </div>
  );
}

window.LogFoodPage = LogFoodPage;
