// Paste Day — free-form multi-meal/multi-day parsing
const { useState, useContext } = React;

function PasteDayPage() {
  const { addEntries, toast, prefs } = useContext(AppCtx);
  const [text, setText] = useState('');
  const [defaultDate, setDefaultDate] = useState(todayISO());
  const [loading, setLoading] = useState(false);
  const [progress, setProgress] = useState(null);
  const [items, setItems] = useState(null); // parsed preview

  async function handleLookup() {
    if (!text.trim()) { toast('Paste some food notes first', 'error'); return; }
    setLoading(true);
    setProgress(null);
    setItems(null);
    try {
      const result = await claudeLookupMulti(text, (p) => setProgress(p));
      const list = (result.items || []).map(it => ({
        ...it,
        date: it.date || defaultDate,
        meal: it.meal || 'Snack',
        _selected: true,
        _id: Math.random().toString(36).slice(2)
      }));
      setItems(list);
      if (!list.length) toast('No items detected — try rephrasing', 'error');
    } catch (e) {
      console.error(e);
      toast('Parse 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).map(({ _selected, _id, ...rest }) => rest);
    if (!selected.length) { toast('Select at least one item', 'error'); return; }
    addEntries(selected);
    toast(`Logged ${selected.length} item${selected.length === 1 ? '' : 's'}`);
    setItems(null);
    setText('');
  }

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

  return (
    <div>
      <div className="mb-24">
        <div className="eyebrow">Paste Day · Multi-Meal Logging</div>
        <h1 className="display mt-8">Dump your food notes</h1>
        <p className="muted" style={{ maxWidth: 600 }}>
          Paste any free-form notes — one meal, a whole day, or several days. Claude breaks them
          into structured entries with nutrition for each.
        </p>
      </div>

      {!items && (
        <div className="card">
          <div className="field" style={{ maxWidth: 280, marginBottom: 14 }}>
            <label>Default date (if no date in notes)</label>
            <input className="input" type="date" value={defaultDate}
                   onChange={e => setDefaultDate(e.target.value)} />
          </div>

          <div className="field">
            <label>Notes</label>
            <textarea className="textarea" style={{ minHeight: 220 }}
              placeholder={`Paste anything — examples:

5/18 breakfast — bowl of overnight oats with peanut butter and a banana, black coffee
lunch — chicken caesar wrap, kettle chips, can of LaCroix
dinner — ribeye, baked potato, asparagus, glass of red wine
snack — handful of almonds and a square of dark chocolate

OR

Yesterday I had eggs and toast for breakfast, a chipotle bowl for lunch, salmon and rice for dinner, plus 64oz of water throughout the day`}
              value={text} onChange={e => setText(e.target.value)} />
          </div>

          <div className="row-between mt-16">
            <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" /> {progress
                    ? (progress.stage === 'looking up'
                        ? `Looking up ${progress.done}/${progress.total}…`
                        : `Found ${progress.total}…`)
                    : 'Parsing…'}</>
                : <><Icon name="sparkle" /> Look up & parse</>}
            </button>
          </div>
        </div>
      )}

      {items && (
        <div>
          <div className="row-between mb-16" style={{ flexWrap: 'wrap', gap: 12 }}>
            <div>
              <div className="display" style={{ fontSize: 22 }}>{items.length} item{items.length === 1 ? '' : 's'} parsed</div>
              <div className="muted" style={{ fontSize: 13 }}>Review · adjust · add</div>
            </div>
            <div className="row" style={{ gap: 10 }}>
              <button className="btn btn-ghost" onClick={() => { setItems(null); }}>← Back</button>
              <button className="btn btn-primary" onClick={handleAddAll} disabled={!selectedCount} style={{ whiteSpace: 'nowrap' }}>
                <Icon name="plus" /> Add {selectedCount} to log
              </button>
            </div>
          </div>

          <div className="grid" style={{ gap: 10 }}>
            {items.map(it => (
              <ParsedItemRow key={it._id} item={it}
                onToggle={() => toggleItem(it._id)}
                onChange={(patch) => updateItem(it._id, patch)}
                onRemove={() => removeItem(it._id)}
                showMicros={prefs.showMicros}
              />
            ))}
          </div>

          <div className="row-between mt-24" style={{ gap: 10, flexWrap: 'wrap' }}>
            <button className="btn btn-ghost" onClick={() => { setItems(null); }}>Cancel</button>
            <button className="btn btn-primary btn-lg" onClick={handleAddAll} disabled={!selectedCount}>
              <Icon name="plus" /> Add {selectedCount} to log
            </button>
          </div>
        </div>
      )}
    </div>
  );
}

function ParsedItemRow({ item, onToggle, onChange, onRemove, showMicros }) {
  const [open, setOpen] = useState(false);
  return (
    <div className="card-tight card" style={{ padding: 16, opacity: item._selected ? 1 : 0.5 }}>
      <div className="row" style={{ gap: 12, alignItems: 'flex-start' }}>
        <button onClick={onToggle} title="Include in log"
                style={{
                  width: 22, height: 22, borderRadius: 6,
                  border: '1.5px solid ' + (item._selected ? 'var(--accent)' : 'var(--line)'),
                  background: item._selected ? 'var(--accent)' : 'transparent',
                  color: '#fff', cursor: 'pointer', display: 'grid', placeItems: 'center', padding: 0,
                  marginTop: 2, flexShrink: 0
                }}>
          {item._selected && <svg width="12" height="12" 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 className="row-between" style={{ gap: 10, flexWrap: 'wrap' }}>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontWeight: 500, fontSize: 15 }}>{item.name}</div>
              {item.servingDescription && <div className="muted" style={{ fontSize: 12 }}>{item.servingDescription}</div>}
            </div>
            <div className="row" style={{ gap: 6 }}>
              <span className="chip" style={{ background: 'var(--accent-soft)', color: 'var(--accent)' }}>
                <span className="num">{fmtNum(item.calories)}</span> cal
              </span>
              <button className="icon-btn" style={{ width: 32, height: 32 }} onClick={() => setOpen(o => !o)} title="Details">
                <Icon name="info" size={14} />
              </button>
              <button className="icon-btn" style={{ width: 32, height: 32 }} onClick={onRemove} title="Remove">
                <Icon name="trash" size={14} />
              </button>
            </div>
          </div>

          <div className="row mt-12" style={{ gap: 10, flexWrap: 'wrap', fontSize: 12 }}>
            <select className="select" value={item.meal}
                    onChange={e => onChange({ meal: e.target.value })}
                    style={{ width: 'auto', padding: '6px 28px 6px 10px', fontSize: 12 }}>
              {MEALS.map(m => <option key={m} value={m}>{m}</option>)}
            </select>
            <input className="input" type="date" value={item.date}
                   onChange={e => onChange({ date: e.target.value })}
                   style={{ width: 'auto', padding: '6px 10px', fontSize: 12 }} />
            <span className="chip"><span className="num">{fmtNum(item.protein,1)}g</span> P</span>
            <span className="chip"><span className="num">{fmtNum(item.carbs,1)}g</span> C</span>
            <span className="chip"><span className="num">{fmtNum(item.fat,1)}g</span> F</span>
            {item.water > 0 && <span className="chip"><span className="num">{fmtNum(item.water)}oz</span> H₂O</span>}
            {item.caffeine > 0 && <span className="chip"><span className="num">{fmtNum(item.caffeine)}mg</span> caf</span>}
          </div>

          {open && (
            <div className="mt-12" style={{ background: 'var(--bg-elev)', borderRadius: 10, padding: 12 }}>
              <div className="grid grid-2" style={{ fontSize: 12, gap: 6 }}>
                <KVMini l="Fiber" v={item.fiber} u="g" d={1} />
                <KVMini l="Sugar" v={item.sugar} u="g" d={1} />
                <KVMini l="Sat. Fat" v={item.satFat} u="g" d={1} />
                <KVMini l="Sodium" v={item.sodium} u="mg" />
                <KVMini l="Cholesterol" v={item.cholesterol} u="mg" />
                <KVMini l="Potassium" v={item.potassium} u="mg" />
              </div>
              {showMicros && (
                <div className="micro-strip mt-12">
                  {[
                    ['Vit A', item.vitA, 'mcg'], ['Vit C', item.vitC, 'mg'],
                    ['Vit D', item.vitD, 'mcg'], ['Vit B6', item.vitB6, 'mg'],
                    ['Vit B12', item.vitB12, 'mcg'],
                    ['Calcium', item.calcium, 'mg'], ['Iron', item.iron, 'mg']
                  ].filter(([_,v]) => Number(v) > 0).map(([n,v,u]) => (
                    <span key={n} className="chip">{n} {fmtNum(v, v < 1 ? 2 : 0)}{u}</span>
                  ))}
                </div>
              )}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

function KVMini({ l, v, u, d = 0 }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'space-between' }}>
      <span className="muted">{l}</span>
      <span className="num">{fmtNum(v || 0, d)} <span className="dim">{u}</span></span>
    </div>
  );
}

window.PasteDayPage = PasteDayPage;
