// History — full log with Excel export
const { useState, useContext, useMemo } = React;

function HistoryPage() {
  const { entries, deleteEntry, updateEntry, toast } = useContext(AppCtx);
  const [scope, setScope] = useState('14'); // '14' | 'all'
  const [search, setSearch] = useState('');
  const [view, setView] = useState('cards'); // 'cards' | 'table'
  const [editing, setEditing] = useState(null); // entry being edited

  const today = todayISO();
  const cutoff = scope === '14' ? isoOffset(today, -13) : '0000-01-01';

  const filtered = useMemo(() => {
    const q = search.trim().toLowerCase();
    return entries
      .filter(e => e.date >= cutoff)
      .filter(e => !q || (e.name || '').toLowerCase().includes(q) || (e.notes || '').toLowerCase().includes(q))
      .sort((a, b) => {
        if (a.date !== b.date) return b.date.localeCompare(a.date);
        return (b.createdAt || 0) - (a.createdAt || 0);
      });
  }, [entries, cutoff, search]);

  const byDate = useMemo(() => {
    const map = new Map();
    filtered.forEach(e => {
      if (!map.has(e.date)) map.set(e.date, []);
      map.get(e.date).push(e);
    });
    return [...map.entries()];
  }, [filtered]);

  function exportExcel() {
    try {
      const rows = filtered.map(e => ({
        Date: e.date,
        Meal: e.meal,
        Item: e.name,
        Calories: e.calories || 0,
        'Fat (g)': e.fat || 0,
        'Sat Fat (g)': e.satFat || 0,
        'Trans Fat (g)': e.transFat || 0,
        'Cholesterol (mg)': e.cholesterol || 0,
        'Sodium (mg)': e.sodium || 0,
        'Carbs (g)': e.carbs || 0,
        'Fiber (g)': e.fiber || 0,
        'Sugar (g)': e.sugar || 0,
        'Protein (g)': e.protein || 0,
        'Vit A (mcg)': e.vitA || 0,
        'Vit B6 (mg)': e.vitB6 || 0,
        'Vit B12 (mcg)': e.vitB12 || 0,
        'Vit C (mg)': e.vitC || 0,
        'Vit D (mcg)': e.vitD || 0,
        'Calcium (mg)': e.calcium || 0,
        'Iron (mg)': e.iron || 0,
        'Potassium (mg)': e.potassium || 0,
        'Caffeine (mg)': e.caffeine || 0,
        'Water (oz)': e.water || 0,
        'Other': e.other || '',
        'Notes': e.notes || ''
      }));
      const ws = XLSX.utils.json_to_sheet(rows);
      // column widths
      ws['!cols'] = [
        { wch: 12 }, { wch: 10 }, { wch: 36 }, { wch: 9 },
        ...Array(20).fill({ wch: 10 }),
        { wch: 28 }, { wch: 28 }
      ];
      const wb = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(wb, ws, 'Nutrition Log');
      const fname = `nutrition-log_${today}.xlsx`;
      XLSX.writeFile(wb, fname);
      toast('Excel downloaded');
    } catch (e) {
      console.error(e);
      toast('Export failed', 'error');
    }
  }

  return (
    <div>
      <div className="row-between mb-24" style={{ flexWrap: 'wrap', gap: 12 }}>
        <div>
          <div className="eyebrow">History</div>
          <h1 className="display mt-8">Your full log</h1>
          <p className="muted" style={{ fontSize: 13 }}>
            {filtered.length} entr{filtered.length === 1 ? 'y' : 'ies'}
            {scope === '14' ? ' (last 14 days)' : ' (all time)'}
          </p>
        </div>
        <div className="row" style={{ gap: 10, flexWrap: 'wrap' }}>
          <div className="segmented">
            <button className={scope === '14' ? 'active' : ''} onClick={() => setScope('14')}>14 days</button>
            <button className={scope === 'all' ? 'active' : ''} onClick={() => setScope('all')}>All history</button>
          </div>
          <div className="segmented">
            <button className={view === 'cards' ? 'active' : ''} onClick={() => setView('cards')}>Cards</button>
            <button className={view === 'table' ? 'active' : ''} onClick={() => setView('table')}>Table</button>
          </div>
          <button className="btn btn-primary" onClick={exportExcel}>
            <Icon name="download" /> Export Excel
          </button>
        </div>
      </div>

      <div className="row mb-16" style={{ gap: 10, flexWrap: 'wrap' }}>
        <div style={{ position: 'relative', flex: 1, minWidth: 240, maxWidth: 420 }}>
          <input
            className="input"
            placeholder="Search food name or notes…"
            value={search} onChange={e => setSearch(e.target.value)}
            style={{ paddingLeft: 36 }}
          />
          <div style={{ position: 'absolute', left: 12, top: '50%', transform: 'translateY(-50%)', color: 'var(--text-dim)', pointerEvents: 'none' }}>
            <Icon name="search" size={14} />
          </div>
        </div>
      </div>

      {filtered.length === 0 ? (
        <div className="card">
          <div className="empty-state">
            <div className="em-icon"><Icon name="history" size={22} /></div>
            <div>No entries match your filter.</div>
          </div>
        </div>
      ) : view === 'cards' ? (
        <div className="grid" style={{ gap: 16 }}>
          {byDate.map(([date, list]) => (
            <HistoryDayCard
              key={date} date={date} entries={list}
              onDelete={(id) => { deleteEntry(id); toast('Removed'); }}
              onEdit={(entry) => setEditing(entry)}
            />
          ))}
        </div>
      ) : (
        <HistoryTable
          entries={filtered}
          onDelete={(id) => { deleteEntry(id); toast('Removed'); }}
          onEdit={(entry) => setEditing(entry)}
        />
      )}

      {editing && (
        <EditEntryModal
          entry={editing}
          onClose={() => setEditing(null)}
          onSave={(patch) => {
            updateEntry(editing.id, patch);
            setEditing(null);
            toast('Updated');
          }}
        />
      )}
    </div>
  );
}

function EditEntryModal({ entry, onClose, onSave }) {
  const [date, setDate] = useState(entry.date);
  const [meal, setMeal] = useState(entry.meal);
  const meals = ['Breakfast', 'Lunch', 'Dinner', 'Snack', 'Water'];

  function handleSubmit(e) {
    e.preventDefault();
    onSave({ date, meal });
  }

  return (
    <div
      onClick={onClose}
      style={{
        position: 'fixed', inset: 0, zIndex: 60,
        background: 'rgba(0,0,0,0.55)',
        display: 'grid', placeItems: 'center',
        padding: 16, animation: 'fadeIn .15s ease-out'
      }}
    >
      <form
        onClick={(e) => e.stopPropagation()}
        onSubmit={handleSubmit}
        style={{
          background: 'var(--bg-card)', border: '1px solid var(--line)',
          borderRadius: 18, padding: 22, width: 'min(420px, 100%)',
          boxShadow: 'var(--shadow-lg)', fontFamily: 'var(--sans)'
        }}
      >
        <div className="row-between mb-16">
          <div>
            <div className="eyebrow">Edit entry</div>
            <div style={{ fontFamily: 'var(--serif)', fontSize: 22, marginTop: 4 }}>{entry.name}</div>
          </div>
          <button type="button" className="icon-btn" onClick={onClose} aria-label="Close">×</button>
        </div>

        <div className="field mb-16">
          <label>Date</label>
          <input className="input" type="date" value={date} onChange={(e) => setDate(e.target.value)} required />
        </div>

        <div className="field mb-16">
          <label>Meal</label>
          <div className="segmented" style={{ width: '100%', flexWrap: 'wrap' }}>
            {meals.map(m => (
              <button
                key={m} type="button"
                className={meal === m ? 'active' : ''}
                style={{ flex: 1, minWidth: 70 }}
                onClick={() => setMeal(m)}
              >{m}</button>
            ))}
          </div>
        </div>

        <div className="row" style={{ gap: 10, justifyContent: 'flex-end' }}>
          <button type="button" className="btn btn-ghost" onClick={onClose}>Cancel</button>
          <button type="submit" className="btn btn-primary">Save changes</button>
        </div>
      </form>
    </div>
  );
}

function HistoryDayCard({ date, entries, onDelete, onEdit }) {
  const totals = sumEntries(entries);
  const water = entries.filter(e => e.meal === 'Water').reduce((s,e) => s + (e.water || 0), 0);
  return (
    <div className="daycard">
      <div className="daycard-head">
        <div>
          <h3 className="display" style={{ fontSize: 22 }}>{relativeDayLabel(date)}</h3>
          <div className="muted" style={{ fontSize: 12 }}>{formatDayLong(date)}</div>
        </div>
        <div className="row" style={{ gap: 14, fontSize: 12, flexWrap: 'wrap' }}>
          <KStat label="cal" v={Math.round(totals.calories)} accent="var(--accent)" />
          <KStat label="P" v={Math.round(totals.protein)} unit="g" accent="var(--protein)" />
          <KStat label="C" v={Math.round(totals.carbs)} unit="g" accent="var(--carbs)" />
          <KStat label="F" v={Math.round(totals.fat)} unit="g" accent="var(--fat)" />
          {water > 0 && <KStat label="H₂O" v={Math.round(water)} unit="oz" accent="var(--water)" />}
        </div>
      </div>

      {['Breakfast','Lunch','Dinner','Snack','Water'].map(meal => {
        const list = entries.filter(e => e.meal === meal);
        if (!list.length) return null;
        const mTotal = sumEntries(list);
        return (
          <div key={meal} className="meal-section">
            <div className="row-between mb-8">
              <span className="meal-pill" data-meal={meal}><span className="dot" /> {meal}</span>
              <span className="muted" style={{ fontSize: 11, fontFamily: 'var(--mono)' }}>
                {meal === 'Water' ? `${Math.round(mTotal.water)} oz` : `${Math.round(mTotal.calories)} cal`}
              </span>
            </div>
            {list.map(e => (
              <div key={e.id} className="log-row">
                <div className="lr-name">
                  {e.name}
                  {e.notes && e.notes !== e.name && <small>{e.notes}</small>}
                </div>
                <div className="lr-cal">
                  {meal === 'Water' ? `${Math.round(e.water)} oz` : `${Math.round(e.calories)} cal`}
                </div>
                <button className="lr-edit" onClick={() => onEdit(e)} aria-label="Edit"><Icon name="edit" size={14} /></button>
                <button className="lr-del" onClick={() => onDelete(e.id)} aria-label="Delete"><Icon name="trash" size={14} /></button>
              </div>
            ))}
          </div>
        );
      })}
    </div>
  );
}

function KStat({ label, v, unit, accent }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end' }}>
      <div className="num" style={{ fontSize: 18, color: accent, lineHeight: 1 }}>{v}{unit ? <span style={{ fontSize: 11, color: 'var(--text-dim)', marginLeft: 2 }}>{unit}</span> : null}</div>
      <div style={{ fontSize: 10, letterSpacing: 0.14 + 'em', textTransform: 'uppercase', color: 'var(--text-dim)' }}>{label}</div>
    </div>
  );
}

function HistoryTable({ entries, onDelete, onEdit }) {
  return (
    <div className="tbl-wrap">
      <table className="tbl">
        <thead>
          <tr>
            <th>Date</th>
            <th>Meal</th>
            <th>Item</th>
            <th className="num-col">Cal</th>
            <th className="num-col">P</th>
            <th className="num-col">C</th>
            <th className="num-col">F</th>
            <th className="num-col">Fiber</th>
            <th className="num-col">Sodium</th>
            <th className="num-col">Caf</th>
            <th className="num-col">H₂O</th>
            <th></th>
          </tr>
        </thead>
        <tbody>
          {entries.map(e => (
            <tr key={e.id}>
              <td>{e.date}</td>
              <td><span className="meal-pill" data-meal={e.meal}><span className="dot" /> {e.meal}</span></td>
              <td>{e.name}</td>
              <td className="num-col">{Math.round(e.calories || 0)}</td>
              <td className="num-col">{fmtNum(e.protein, 1)}</td>
              <td className="num-col">{fmtNum(e.carbs, 1)}</td>
              <td className="num-col">{fmtNum(e.fat, 1)}</td>
              <td className="num-col">{fmtNum(e.fiber, 1)}</td>
              <td className="num-col">{Math.round(e.sodium || 0)}</td>
              <td className="num-col">{Math.round(e.caffeine || 0)}</td>
              <td className="num-col">{Math.round(e.water || 0)}</td>
              <td>
                <div className="row" style={{ gap: 4, justifyContent: 'flex-end' }}>
                  <button className="lr-edit" onClick={() => onEdit(e)} aria-label="Edit"><Icon name="edit" size={14} /></button>
                  <button className="lr-del" onClick={() => onDelete(e.id)} aria-label="Delete"><Icon name="trash" size={14} /></button>
                </div>
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

window.HistoryPage = HistoryPage;
